Test strings equality
== tests object references, .equals() tests the string values.
Sometimes it looks as if == compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.
For example:
1 2 3 4 5 6 7 8 9 10 11 |
String fooString1 = new String("foo"); String fooString2 = new String("foo"); // Evaluates to false fooString1 == fooString2; // Evaluates to true fooString1.equals(fooString2); // Evaluates to true, because Java uses the same object "bar" == "bar"; |
Correct null handling
== handles null strings fine, but calling .equals() from a null string will cause an exception:
1 2 3 4 5 6 7 8 |
String nullString1 = null; String nullString2 = null; // Evaluates to true nullString1 == nullString2; // Throws an Exception nullString1.equals(nullString2); |