Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Strings avoiding NullPointerException [duplicate]

When I code I often have to compare two Strings. I know that calling string.equals() throws a java.lang.NullPointerException if the String is null, so what I always do is:

if (string != null && string.equals("something") {
    // Do something
}

This results in having lots of methods that always contains a condition whether a String is null or not.

I would like to avoid this repetition without having an error thrown, is it possible?

like image 700
Paolo Forgia Avatar asked Apr 14 '17 10:04

Paolo Forgia


People also ask

How do I ignore NullPointerException?

How to avoid the NullPointerException? To avoid the NullPointerException, we must ensure that all the objects are initialized properly, before you use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.

What can help us in avoiding NullPointerException?

The NullPointerException can be avoided using checks and preventive techniques like the following: Making sure an object is initialized properly by adding a null check before referencing its methods or properties. Using Apache Commons StringUtils for String operations e.g. using StringUtils.

Can you use == to compare strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do you compare two string objects for their equality?

Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.


1 Answers

Yes, it's possible. Just do:

if ("something".equals(string)) {
    // Do something
}

This will prevent throwing a java.lang.NullPointerException since the Object who calls equals() is not null.

like image 188
Paolo Forgia Avatar answered Sep 29 '22 09:09

Paolo Forgia