File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in String...Plz Help Me 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 "Doubt in String...Plz Help Me" Watch "Doubt in String...Plz Help Me" New topic

Doubt in String...Plz Help Me

Thangaraj Selvamani
Ranch Hand

Joined: Sep 20, 2008
Posts: 61
class MWC114 {
public static void main(String[] s) {
String s1 = new String("ABCDEFG"), s2 = new String("EFGHIJ");
String s3 = s1.substring(4,7), s4 = s2.substring(0,3);
System.out.println(s3 == s4);
String a="Hai";
String b="Hai";
System.out.println(a == b);


Why First System.out.println Shows False...
Even though Both s3 and s4 refers to same value "EFG"

[ October 15, 2008: Message edited by: Thangaraj Raj ]
Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
Its because s3 and s4 are two different reference variables. So, even though their contents are the same, when you use == operator, it returns false.

Whereas, in the second println statement, the String constant pool comes into picture. If the JVM finds the same string in the pool, instead of creating a new object, it will make the new reference point to the already existing String.

So, since "Hai" is already present in the pool (which was created through String a="Hai"), JVM just points the reference b to it, and hence it returns true when comparing a and b using == operator.
subhasish nag
Ranch Hand

Joined: Apr 25, 2008
Posts: 101
s3 and s4 are reffrering two different objects.== checks wheather bothe references two same object or not.If you use equals() method then the result will be true.
And in a==b it returns true as ure creating String without new operator. So at the the time of creating object referenced by a stored in String pool and b references to the same object.If you use new operator for creating String then it will return false.

Thanks,<br />Subhasish
Thangaraj Selvamani
Ranch Hand

Joined: Sep 20, 2008
Posts: 61
I agree. Here's the link:
subject: Doubt in String...Plz Help Me
It's not a secret anymore!