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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With