5

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,202
  • 8
  • 42
  • 57

1 Answers1

21

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,202
  • 8
  • 42
  • 57