Nullpointer exception

前端 未结 5 1764
予麋鹿
予麋鹿 2020-12-02 01:05

There is a possiblity that this may be a dupicate question. I initialize a String variable to null.I may or may not update it with a value.Now I want to check whether this v

相关标签:
5条回答
  • 2020-12-02 01:19

    if you are checking whether "s" is null, then do not apply a dot(.) after "s". Doing that would throw NullPOinterException, as applying dot(.) means that you are trying to access on a pointer location which is basically null at the moment !

    Also try to use library functions that check whether a string is null or empty. you may use StringUtils.isEmpty(s) from apache library which checked both

    0 讨论(0)
  • 2020-12-02 01:24

    If you use

    if (x == null)
    

    you will not get a NullPointerException.

    I suspect you're doing:

    if (x.y == null)
    

    which is throwing because x is null, not because x.y is null.

    If that doesn't explain it, please post the code you're using to test for nullity.

    0 讨论(0)
  • 2020-12-02 01:32

    String is immutable

    @Test(expected = NullPointerException.class)
    public void testStringEqualsNull() {
        String s = null;
        s.equals(null);
    }
    
    @Test
    public void testStringEqualsNull2() {
        String s = null;
        TestCase.assertTrue(s == null);
    }
    
    0 讨论(0)
  • 2020-12-02 01:33

    I am comparing s==null only

    can you show the code snippet that you have written s==null will never throw a NPE

    0 讨论(0)
  • 2020-12-02 01:35

    I guess you are doing something like this,

      String s = null;
    
      if (s.equals(null))
    

    You either check for null like this

      if (s == null)
    

    A better approach is to ignore the null and just check for the expected value like this,

      if ("Expected value".equals(s))
    

    In this case, the result is always false when s is null.

    0 讨论(0)
提交回复
热议问题