This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String comparison

 
Navin Manwatkar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String str1 = "String";
String str2 = "Str";
System.out.println(str1 == (str2 + "ing"));

It prints false. why is it so???
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== is used to check if two references point to the same object. You can find more information here, here and here...
 
Ben Power
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that a variable pointing to an Object (such as String, or Thread, or fill in the blank) contains only the location in memory where the object is stored. So str2 doesn't contain the actual object, it only tells you where to find the object.

As Ankit pointed out, == only compares the contents of the variable - in this case, the location in memory where the String object you created is stored. Two strings that contain the same characters might be separate objects, and thus would have different locations in memory. So then, when you compare their memory locations, it returns false, even though the strings are "meaningfully equal."

The Object class has a method called equals() that String overrides. It checks to see whether the strings contain the same data. Try changing it to this:



Also do see the articles Ankit linked to. This is a key concept to understand for any Java programmer.
 
Deepika Joshi
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== compares object references not content of objects.
It is imp to note that String is immutable.
 
Navin Manwatkar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot to all of you..... :)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic