aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String comparison Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String comparison" Watch "String comparison" New topic
Author

String comparison

Navin Manwatkar
Greenhorn

Joined: Jan 11, 2010
Posts: 9
String str1 = "String";
String str2 = "Str";
System.out.println(str1 == (str2 + "ing"));

It prints false. why is it so???


Navin Manwatkar
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9303
    
  17

== is used to check if two references point to the same object. You can find more information here, here and here...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Ben Power
Ranch Hand

Joined: Dec 30, 2009
Posts: 31
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.


SCJP 6
Deepika Joshi
Ranch Hand

Joined: Feb 24, 2009
Posts: 268
== compares object references not content of objects.
It is imp to note that String is immutable.
Navin Manwatkar
Greenhorn

Joined: Jan 11, 2010
Posts: 9
Thanks a lot to all of you..... :)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String comparison