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:

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.