It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String equals question 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 equals question" Watch "String equals question" New topic

String equals question

Srinivas Kumar
Ranch Hand

Joined: Jul 14, 2005
Posts: 52
String s1="ABC";
String s2="ABC";
String s2=new String("ABC");
System.out.println("s1==s2 "+ (s1==s2));
System.out.println("s1==s3 "+ (s1==s3));

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

Joined: Feb 24, 2006
Posts: 6662

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

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Srinivas Kumar
Ranch Hand

Joined: Jul 14, 2005
Posts: 52
Thanks John. I got it.
yes, there was typo in my previous post.sorry for that.
I agree. Here's the link:
subject: String equals question
jQuery in Action, 3rd edition