• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

String comparison

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String str1 = "String";
String str2 = "Str";
System.out.println(str1 == (str2 + "ing"));

It prints false. why is it so???
 
Sheriff
Posts: 9691
42
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot to all of you..... :)
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic