How to compare strings in Java?

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.

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.

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:

So if you know that string1 may be null, you can check it for null first and then check to equals

Or the better way


Leave a Reply

Your email address will not be published.

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