Many Java beginners find it difficult to differentiate between == operator and the “equals()” method when comparing String variables in Java. They assume that both operations perform the same function and either one can be used to compare two string variables. I have even seen many experienced programmers committing the mistake of using “==” to compare the values of two strings.

So what is the difference between “==” and “equals()” and what is the correct method of comparing two string variables?

The == operator:

The “==” operator compares the references of two objects in memory. It returns true if both objects point to exact same location in memory. Remember that Strings are immutable in Java, so if you have a String variable str1 with a value of “abc” and then you create another variable str2 with value “abc”, rather than creating a new String variable with same value, Java will simply point str2 to same memory location that holds the value for str1.

In this scenario str1==str2 will return true because both str1 and str2 are referencing the same object in memory.

However, if you create a new variable using the String constructor, like String str3=new String(“abc”); Java will allocate new memory space for str3. Now although str1 and str3 have exact same value, str1==str3 will return false because they are two distinct objects in the memory.

The equals() method:

The equals method compare the text content or the value of two string variables. If both variables have exact same value, equals() will return true, otherwise it will return false.
So, str1.equals(str2) , str1.equals(str3), and str2.equals(str3) will all return true.
str1.equals(“xyz”) will return false.

Here is an example to help you understand the difference between “==” and equals().

public class StringComparison{
	public static void main(String args[]){
		String str1 =  new String("abc");
		String str2 =  new String ("abc");
			System.out.println("str1==str2 is true");
			System.out.println("str1==str2 is false");
			System.out.println("str1.equals(str2) is true");
			System.out.println("str1.equals(str2) is false");
		String str3="abc",
		str4 ="abc";
			System.out.println("str3==str4 is true");
			System.out.println("str3==str4 is false");

Here is the output from this program.

 str1==str2 is false
 str1.equals(str2) is true
 str3==str4 is true

Most of the time you need to compare the values of the variable so you will need the equals() method. In situations where you need to check if two variables reference same memory location then you will use “==” operator.

I hope this will help you understand when to use “==” or equals() for Java string comparison.

Image credit: Martyne

If you enjoyed this post, make sure you subscribe to my RSS feed!