File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String comparision 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 comparision" Watch "String comparision" New topic
Author

String comparision

Jay Ashar
Ranch Hand

Joined: Oct 13, 2002
Posts: 208
public class test {
public static void main(String args[]) {
String s1 = "abc";
String s2 = "abc";
if(s1 == s2)
System.out.println(1);
else
System.out.println(2);
if(s1.equals(s2))
System.out.println(3);
else
System.out.println(4);
}
}

what is the output?


SCJP 1.4<br />SCWCD 1.3
Yan Bai
Ranch Hand

Joined: Jul 21, 2002
Posts: 125
Print out:
1
3


SCJP 1.4
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
Wouldn't it be better to compile and run this yourself instead of posting the question here?
Now, if you do this and then don't understand why the program behaved like it did, you can ask a better question.


Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Jay Ashar
Ranch Hand

Joined: Oct 13, 2002
Posts: 208
Yes I did compile and run before asking question
but
Integer i = new Integer(5);
Integer i1 = new Integer(5);
i == i1, returns false
and
String s = "abc";
String s1 = "abc";
s == s1 returns true
that was bit confusing
but anyway Thanks for the idea of asking me to compile and run and putting a better question.
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
OK, that's a much better question.
Each time you create a "new Integer", you get a different Integer object. When you do "i==i1", you are comparing the object references, and these objects are not the same, so it's false.
The compiler treats String literals specially. Every instance of the string literal "foo", no matter where it appears, is the same String object. So "s==s1" is true.
This is true only of String literals, not Strings in general. If you had
String s = "abc";
String s1 = s.charAt(0) + "bc";
then s==s1 will be false. The two strings have the same contents but are different objects.
[ October 31, 2002: Message edited by: Ron Newman ]
Jay Ashar
Ranch Hand

Joined: Oct 13, 2002
Posts: 208
Thanks for explanation, I didnt know dumb questions were not allowed here.
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
The question is not "dumb". However, if the question is "what does this code do", the best way to find out the answer is to compile and run it. Then come back here and ask why it behaved the way it did.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String comparision