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.

Share:
14,904
Paolo Forgia
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, 2022

Comments

  • Paolo Forgia
    Paolo Forgia over 1 year

    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?