How to compare strings in Java?

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:

Correct null handling

== handles null strings fine, but calling .equals() from a null string will cause an exception: