6

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?

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58

1 Answers1

24

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.

Community
  • 1
  • 1
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
  • What if both strings are null? – saumilsdk Aug 28 '20 at 18:03
  • @saumilsdk It is not possible to call `null.equals(string)`. In case both Strings are a variable you need to call `!= null` on the first one in order to avoid the exception. – Paolo Forgia Sep 07 '20 at 16:09
  • Is there a better solution using Optional in that case? – saumilsdk Sep 08 '20 at 07:56
  • if you are looking for a different option, https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#equals-java.lang.CharSequence-java.lang.CharSequence- – Swarup Donepudi Dec 05 '22 at 09:01