wood burning stoves*
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String equals question" Watch "String equals question" New topic
Author

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.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

Joined: Feb 24, 2006
Posts: 6657
    
    5

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: http://aspose.com/file-tools
 
subject: String equals question
 
Similar Threads
== & equals()
Question on Strings and String pool
String Pool
String problem
(s1==s5) Vs s1==s5