Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String equals question

 
Srinivas Kumar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s1="ABC";
String s2="ABC";
String s2=new String("ABC");
System.out.println("s1==s2 "+ (s1==s2));
System.out.println("s1.equals(s2)"+s1.equals(s2));
System.out.println("s1==s3 "+ (s1==s3));

Answer:
true
true
false
Can anybody explain the difference between 1st and last answers in the output.
As per my understanding, even first answer shoud be false.
 
Deepak Bala
Bartender
Posts: 6663
5
Firefox Browser Linux MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is s3 ? A typo perhaps. Strings created without the new operator exist in a String pool. If two Strings in the pool are the same, the references are fly weighted to point to the same object thus == is satisfied. With the new operator however you also have a String object on the heap
 
Srinivas Kumar
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks John. I got it.
yes, there was typo in my previous post.sorry for that.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic