Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java null String equals result

Please help me how does the string.equals in java work with null value? Is there some problem with exceptions? Three cases:

boolean result1,result2, result3;

    //1st case
    String string1 = null;
    String string2 = null;
    result = string1.equals(string2);
    //2nd case
    String string1 = "something";
    String string2 = null;
    result2 = string1.equals(string2);
    //3rd case 
    String string1 = null;
    String string2 = "something";
    result3 = string1.equals(string2);

What the values of results are? I expect this values:

result1 is true;
result2 is false;
result3 is false;

like image 620
user1097772 Avatar asked Jun 13 '12 03:06

user1097772


1 Answers

You cannot use the dereference (dot, '.') operator to access instance variables or call methods on an instance if that instance is null. Doing so will yield a NullPointerException.

It is common practice to use something you know to be non-null for string comparison. For example, "something".equals(stringThatMayBeNull).

like image 72
sjr Avatar answered Oct 12 '22 23:10

sjr