Compare Strings in Java
The String
class provides a method equals()
to compare string values. The double equal sign ==
only compares the references, not the values.
String a = new String("test"); String b = new String("test"); System.out.println(a.equals(b)); // true System.out.println(a == b); // false
Here “a” and “b” are pointing to two different String objects. The equals()
method will check the value of the two strings, while ==
only checks the references (the memory addresses of the two string objects).
----- ---------- | a | --> | "test" | ----- ---------- ----- ---------- | b | --> | "test" | ----- ----------
new String("test").equals("test"); // true new String("test") == "test"; // false new String("test") == new String("test"); // false
However, string literals are “interned” and they refer to the same object if they have the same value.
System.out.println("test" == "test"); // true String a = "test"; String b = "test"; System.out.println(a == b); // true
Concatenation of string literals are done at compile time. This may result in the same literals.
System.out.println("test" == "te" + "st"); // true
Be aware of null values. The double-equal sign ==
compares null references as well, but .equals()
can not be invoked from a null string.
String a = null; String b = null; String c = "test"; System.out.println(a == b); // true System.out.println(a == c); // false System.out.println(a.equals(c)); // throws exception System.out.println(c.equals(a)); // false
The String
class also provides some other methods comparing strings.
public boolean equalsIgnoreCase(String anotherString)
Compares strings ignoring case considerations.public int compareTo(String anotherString)
Compares two strings lexicographically. compareTo returns 0 exactly when the equals(Object) method would return true.
String a = “Hello World”; String b = a; String c = new String(“Hello World”); System.out.println(c.equals(a)); // true System.out.println(b.equals(a)); // true System.out.println(c.equalsIgnoreCase("hello world")); // true System.out.println(c.compareTo(a)); // 0 System.out.println(c.compareTo("Iello World")); System.out.println(c.compareTo("Hello Xorld")); System.out.println(c.compareTo("Aello World"));