Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two Strings when both can be null? [duplicate]

I am aware that it is better to call the equals method over using the == operator (see this question). I want two strings to compare as equal if they are both null or if they represent the same string. Unfortunately the equals method will throw an NPE if the strings are null. My code is currently:

boolean equals(String s1, String s2) {   if (s1 == null && s2 == null) {     return true;   }   if (s1 == null || s2 == null) {     return false;   }   return s1.equals(s2); } 

This is inelegant. What is the correct way to perform this test?

like image 767
Benjy Kessler Avatar asked May 06 '15 15:05

Benjy Kessler


People also ask

Can we compare string with null?

string == null compares if the object is null. string. equals("foo") compares the value inside of that object. string == "foo" doesn't always work, because you're trying to see if the objects are the same, not the values they represent.

Can we compare 2 null?

Two null values are considered equal. Furthermore, this method can be used to sort a list of Strings with null entries: assertThat(StringUtils. compare(null, null)) .

Is StringUtils equals null safe?

Bonus: Using Apache CommonsThe equals() method of StringUtils class is a null-safe version of the equals() method of String class, which also handles null values.


2 Answers

If Java 7+, use Objects.equals(); its documentation explicitly specifies that:

[...] if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.

which is what you want.

If you don't, your method can be rewritten to:

return s1 == null ? s2 == null : s1.equals(s2); 

This works because the .equals() contract guarantees that for any object o, o.equals(null) is always false.

like image 170
fge Avatar answered Sep 24 '22 18:09

fge


From Objects.equals():

return (a == b) || (a != null && a.equals(b)); 

Very simple, self-explaining and elegant.

like image 27
Alex Salauyou Avatar answered Sep 23 '22 18:09

Alex Salauyou