A very common situation occur when we try to compare a String variable and a string literal.

String str = null;
 
if (str.equals("abc")) { // it throws NPE
    System.out.println("The same");
}

To avoid NullPointerException (NPE) here we can call the equals method on literal rather than the object:

 String str = null;
 
if ("abc".equals(str)) { // no NPE here
    System.out.println("The same");
}

But what if we have two variables of the type String? Any of them may happen to be null. In this case, we can use the special auxiliary class java.util.Objects.

String s1 = null;
String s2 = null;
        
if (Objects.equals(s1, s2)) { // no NPE here
    System.out.println("Strings are the same");
}

This approach is recommended in modern Java programming since it is easy for reading and does not throw NPE.

Leave a Reply

Your email address will not be published.