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;
Use
Objects.equals()
to compare strings, or any other objects if you're using JDK 7 or later. It will handle nulls without throwing exceptions. See more here: how-do-i-compare-strings-in-javaWe cannot use dot operator with null since doing so will give NullPointerException. Therefore we can take advantage of try..catch block in our program. This is a very crude way of solving your problem, but you will get desired output.
Indeed, you cannot use the dot operator on a
null
variable to call a non static method.Despite this, all depends on overriding the
equals()
method of theObject
class. In the case of theString
class, is:If you pass
null
as parameter, both "if" will fail, returningfalse
;An alternative for your case is to build a method for your requirements:
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 aNullPointerException
.It is common practice to use something you know to be non-null for string comparison. For example,
"something".equals(stringThatMayBeNull)
.You will get a NullPointerException in case 1 and case 3.
You cannot call any methods (like
equals()
) on a null object.That piece of code will throw a
NullPointerException
whenever string1 is null and you invokeequals
on it, as is the case when a method is implicitly invoked on any null object.To check if a string is null, use
==
rather thanequals
.Although
result1
andresult3
will not be set due to NullPointerExceptions, result2 would be false (if you ran it outside the context of the other results).