Compare Strings avoiding NullPointerException
14,904
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
.
Author by
Paolo Forgia
What's the deal with vertical-align: baseline? How to horizontally center a in another ? Why PasswordField use String instead of char[] in Vaadin? What is the difference between “ABC” and new String(“ABC”)? #SOreadytohelp
Updated on June 26, 2022Comments
-
Paolo Forgia over 1 year
When I code I often have to compare two Strings. I know that calling
string.equals()
throws ajava.lang.NullPointerException
if theString
isnull
, 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
isnull
or not.I would like to avoid this repetition without having an error thrown, is it possible?