Java null String equals result
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-java
And if you're not running JDK 7 or later you can copy the equals
method from Objects
like this:
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
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)
.