String comparison in Java
== performs a reference equality check, whether the 2 objects (strings in this case) refer to the same object in the memory.
The equals() method will check whether the contents or the states of 2 objects are the same. I.e. Compared string contains the same sequence of characters.
Definitely, the use of the equals() method is recommended.
Obviously == is faster, but will (might) give false results in many cases if you just want to tell if 2 Strings hold the same text.
1 2 3 4 |
String s1 = "String1"; String s2 = "String2"; System.out.println((s1.equals(s2))?"true":"false"); // true System.out.println((str1==str2) ? "true" : "false"); // true |
Why are both lines prints true? String literals created without null are stored in the String pool in the special area of JVM heap. So both s1 and s2 point to the same object in the pool.
1 2 3 4 5 |
String s1 = new String("String1"); String s2 = new String("String2"); System.out.println((s1.equals(s2))?"true":"false"); // false System.out.println((str1==str2) ? "true" : "false"); // true |
If you create a String object using the new keyword a separate space is allocated to it on the heap.
Comparing with null
== handles null strings fine, but calling .equals() from a null string will cause an exception:
1 2 3 4 5 6 |
String nullString1 = null; String nullString2 = null; System.out.print(nullString1 == nullString2); // true System.out.print(nullString1.equals(nullString2)); // Throws a NullPointerException |
So if you know that string1 may be null, you can check it for null first and then check to equals
1 |
System.out.print(string1 != null && string1.equals("testEqual")); |
Or the better way
1 2 |
System.out.print("testEquals".equals(fooString1)); // "testEquals" is never null System.out.print(Objects.equals(fooString1, "testEquals")); |