1

I have two strings ...

String s1 = /* any string, could be null */;
String s2 = /* any string, could be null */;

I need to know if they are equal.

I can't do s1.equals(s2) because NullPointer if s1 == null.

Is this the best way to check if they are equal?

public boolean stringsAreEqual(String s1, String s2) {
    boolean bEqual = false;
    if ((s1 == null) && (s2 == null)) {
        bEqual = true;
    } else if ((s1 != null) && s1.equals(s2)) {
        bEqual = true;
    } else if ((s2 != null) && s2.equals(s1)) {
        bEqual = true;
    }  
    return bEqual;
}
1
  • 1
    @Swati Don't recommend third party libs please.
    – Anish B.
    Commented Sep 18, 2020 at 4:37

4 Answers 4

10

You do not need to create a new method for that. You can use java.util.Objects#equals(Object a, Object b) from the Java standard library. Below is the definition as on JDK.

public static boolean equals(Object a, Object b) {
    return (a == b) || (a != null && a.equals(b));
}
1

You can compare strings like this. This is what Java internal code uses.

public boolean stringsAreEqual(String s1, String s2) {
    return (s1 == null ? s2 == null : s1.equals(s2));
}
1

A==null ? B==null : A.equals(B)

2
  • Please add more information or explanation to justify the answer. Commented Sep 18, 2020 at 5:09
  • Less "readable" than I normally would write, but this is a nice concise solution. :)
    – AvaTaylor
    Commented Sep 18, 2020 at 5:13
1

It seems like you could first make the method static, and second test if s1 is null, if it is test s2 for null. Otherwise compare s1 and s2. Like,

public static boolean stringsAreEqual(String s1, String s2) {
    if (s1 == null) {
        return s2 == null;
    }
    return s1.equals(s2);
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.