How to compare Java Strings correctly

One of the most common bugs I’ve seen in Java programs is the use of the == operator to compare two String objects. Most of the time the result may be accurate but it is not always guaranteed.
We need to understand the difference between == and the Object.equals method.

The == operator checks the reference of two objects, i.e. it checks if both operands are the same objects. The Object.equals method, on the other hand, compares the value of the two operands.

Consider following example

package com.zparacha.utils; 
public class StringUtilities { 
  public static void main(String args[]) { 
     String a = new String("ABC"); 
     String b = "abc"; 
     String c = "abc"; 
     System.out.println("a = " + a + ", b = " + b + ", c = " + c); 
     System.out.println("a==b is " + (a==b)); 
     System.out.println("a==c is " + (a==c)); 
     System.out.println("b==c is " + (b==c)); 
     System.out.println("a.equals(c) is " + a.equals(c)); 
     System.out.println("b.equals(c) is " + b.equals(c)); 
  } 
}

 

Here is the output of this program

a = abc, b = abc, c = abc
a==b is false
a==c is false
b==c is true
a.equals(c) is true
b.equals(c) is true

As you can see, all three String variables have the same value of “abc”, but the two comparison methods gave different results.

It depends on how the object is initialized. If a String object is created using String literal (e.g.; String b = “abc”; and String c = “abc”;), it may be interned. Interned means that the character sequence "abc"will be stored at a specific memory location, and whenever the same literal is used again, the JVM will not create a new String object instead it will use the reference of the first String object created with the same value. This is the most efficient way of creating String objects.

If you use a String constructor (like  String a = new String("abc");), Java will always create a new object. Then, if you try to compare this String with another String using the == operator, you will always get a “false” return, since you are checking references to two distinct objects.

So, it is highly recommended to use String literals to create new String objects for efficiency and use Object.equals method to compare String to ensure that you get the expected results.