Java – Difference between equals() method and == operator

"==" operator compares 2 objects memory reference. Now, lets have a look at the simple example below:

Example 1:

String str1 = "test";

String str2 = "test";

if (str1 == str2) {
System.out.println("str1 == str2 is TRUE");
} else {
System.out.println("str1 == str2 is FALSE");
}

Output:

str1 == str2 is TRUE

Example 2:

String str1 = new String("test");

String str2 = new String("test");

if (str1 == str2) {
System.out.println("str1 == str2 is TRUE");
} else {
System.out.println("str1 == str2 is FALSE");
}

Output:

str1 == str2 is FALSE

In the code above, Outputs of Example 1 and Example 2 are different. Because, when you create String, JVM searches that literal in String pool, if it matches, same reference will be given to that new String. So, Example 1 output is TRUE.

In Example 2, the output is FALSE. Because, 2 objects refer to different memory location.

Example 3:

String str1 = new String("test");

String str2 = new String("test");

if (str1.equals(str2)) {
System.out.println("str1 == str2 is TRUE");
} else {
System.out.println("str1 == str2 is FALSE");
}

Output:

str1 == str2 is TRUE

String class overrides default equals() method, so that it can check only values of the Strings, not location in memory. If values of 2 string objects are same, it will be equal.

Example 4:

String str1 = new String("test").intern();

String str2 = new String("test").intern();

if (str1 == str2) {
System.out.println("str1 == str2 is TRUE");
} else {
System.out.println("str1 == str2 is FALSE");
}

Output:

str1 == str2 is TRUE

Lastly, When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

Leave a Reply