How to compare strings in Java?

String comparison in Java

In Java, string comparison is used to compare two string values for equality or inequality. There are two main ways to compare strings in Java: using the equals()  method and the compareTo()  method.

  • Using equals()  method:

The equals()  method is used to compare two string values for equality. It returns a boolean value of true if the two strings are equal and false otherwise. The syntax for using the equals()  method is as follows:

In this example, the result variable will be assigned the value false, since the strings “hello” and “world” are not equal.

  • Using compareTo()  method:

The compareTo()  method is used to compare two string values lexicographically. It returns an integer value that represents the difference between the two strings. If the two strings are equal, it returns 0. If the first string is greater than the second string, it returns a positive value. If the first string is less than the second string, it returns a negative value. The syntax for using the compareTo()  method is as follows:

Note about the equality operator (==)

==  performs a reference equality check, whether the 2 objects (strings in this case) refer to the same object in the memory.

The equals()  method (as I write before) will check whether the contents or the states of the 2 objects are the same. I.e. Compared string contains the same sequence of characters.

So 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 the 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 is the better way

An important difference between compareTo  and equals :

Useful links
Official javadocs on String

Leave a Reply

Your email address will not be published.

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