Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question about String.

 
Jianfeng Qian
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Tester {
public static void main(String[] args) {
String s="Dont";
String s1 = "Dontcry";
String s2 = "Dont"+"cry";
String s3=s+"cry";
String s4=s+"cry";
System.out.println("s1 == s2?"+(s1 == s2));
System.out.println("s3 == s4?"+(s3 == s4));
} // main()
} // Tester
output
s1 == s2?true
s3 == s4?false
//why s3!=s4?
 
Bilal Al-Sallakh
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Dont"+"cry" is evaluated at compile time to "Dontcry" which is already in the strings-literals pool, while (s + "cry") is evaluated at runtime and the result is a new string stored in the heap (not in the pool), so s3 and d4 will refer to different objects.

If you mean why the compiler doesn't evaluate it at copmile time, consider a more general case where s is not local to the method: how can the compiler garantee that s doesn't change?

Hope this helps
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To illustrate Bilal's point, change
String s="Dont";
to this
final String s="Dont";

You will get:
s1 == s2?true
s3 == s4?true
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as a general rule, one should never use == to test for equality between object instances.

== checks whether 2 references refer to the same object instance in memory, not whether they refer to 2 object instances containing the same data.
 
Vincent Brabant
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please try this code:


System.identityHashCode() method return the same hashcode an object would have been given by the default Object.hashCode() method.
And because the default hashCode() method is it's memory address expressed as an int, you will directly see if references are pointing to the same memory location.

Hope it can help you.
 
Jianfeng Qian
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you ! Now I understand it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic