Java == (double equals) vs. equals method

Java == (double equals) vs. equals method:

The double equals sign == compares references while equals compares values for equality. See this and this for more.


Code:
java equality checking
java equality checking

Here both of the string literal point to the same object in the String Constant Pool so their comparison value is true,

String a = "abc";
String b = "abc";

if(a == b){
    System.out.println("Match");
}else{
    System.out.println("Mismatch");
}

But this comparison false,

String e = new String("a");
String f = new String("a");

if(e == f){
    System.out.println("Match");
}else{
    System.out.println("Mismatch");
}

Here two new String objects are created. Then their reference is compared to see if they point to same object. Since they points two distinct objects in the heap the value returned in false. So the output is “Mismatch”.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s