Technocrat's Perspective

-a technical blog

Why use equals() to compare strings in Java

Hi All,

Many might aware of the reason to use equals() method in Java string comparison. Let me summarize the reason behind using it. I once tried to write a simple java program to compare both strings in java using double equals operator(==). I assigned value to the first variable as “Hello” and to the next variable i assigned the value as like “Hel” + “lo”. I then compared both the variable using double equals operator(==). As everyone expects, I too think that it goes through the equals condition. But it went to non-equal condition loop. I went on to search for the reason with google. Let me write the code snippet of it

String firstName = “Mahesh” ;
String lastName = “Mah”+”esh” ;
if(firstName==lastName) {
System.out.println(“Equals”);
}
else {
System.out.println(“Not Equals”);
}

OUTPUT: Not Equals

The reason behind failing of String comparison using double equals operator is it looks for the reference value. Hence for string comparison you should use only equals() or equalsIgnoreCase()

Thanks for reading,
Regards,
Muthuselvan N

Advertisement

June 14, 2010 - Posted by | Technology, Tools |

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.