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.

Continue reading