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;
}
AvaTaylor
  • 623
  • 4
  • 16

4 Answers4

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));
}
Amit Bera
  • 7,075
  • 1
  • 19
  • 42
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));
}
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
1

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

ddyer
  • 1,792
  • 19
  • 26
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);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249