wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Strings... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


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

Strings...

Ramya Iyer
Ranch Hand

Joined: Jul 29, 2003
Posts: 66
What is the output displayed by the following program?
public class test
{
public static void main(String a[])
{
String s1 = "ab";
String s2 = "abcd";
String s5 = "abcd";
String s3 = "cd";
String s4 = s1 + s3;
s1 = s4;
System.out.print("s1 "+((s1 == s2)? "==" : "!=")+" s2\n");
System.out.print("s5 "+((s5 == s2)? "==" : "!=")+" s2");

}
}

I thought it should be s1 == s2 and s5 == s2. because all the 4 strings s1, s2,s4 and s5 point to the same literal "abcd". But I find that answer is s1 != s2. Can some one explain?
Roopesh Gulecha
Ranch Hand

Joined: Aug 09, 2005
Posts: 32
Ramya,
I see that your code says

How can "ab" be equal to "abcd" ?
Hope this helps.

Roopesh.
Lalitha Vydyula
Ranch Hand

Joined: Jul 20, 2005
Posts: 69
Hi Roopesh,
I guess you did not notice s1 = s4 on line10
public class test
{
public static void main(String a[])
{
String s1 = "ab";
String s2 = "abcd";
String s5 = "abcd";
String s3 = "cd";
String s4 = s1 + s3;
s1 = s4;
System.out.print("s1 "+((s1 == s2)? "==" : "!=")+" s2\n");
System.out.print("s5 "+((s5 == s2)? "==" : "!=")+" s2");

}
}
Roopesh Gulecha
Ranch Hand

Joined: Aug 09, 2005
Posts: 32
How silly...my mistake...Sorry for that..

It is important to remember that Strings do not get interned (adding new strings in the String pool) either when using the keyword new or when two Strings are concatenated and atleast one of the operands is a variable.
Please see the code:


Output is
s1==s2: true
s1==s3: true
s1==s4: false
s1==s7: false

String s7 is a new String and not same as s1 since it uses "variables" s6 and s5.
Hope this helped and I have not left you more confused.

Roopesh.
agrah upadhyay
Ranch Hand

Joined: Sep 01, 2005
Posts: 579
public class test
{
public static void main(String a[])
{
String s1 = "ab";
String s2 = "abcd";
String s5 = "abcd";
String s3 = "cd";
String s4 = s1 + s3;
s1 = s4;
System.out.print("s1 "+((s1 == s2)? "==" : "!=")+" s2\n");
System.out.print("s5 "+((s5 == s2)? "==" : "!=")+" s2");

}
}
##############################################################
Hello Ms.Ramya
s1,s2,s5,s3 are compile time strings ,created in pool.but s4 is created at runtime where a stringbuffer is created then valueOf() method is called Then Again toString() Method is Called.
Runtime string 'll obviously 've Different Memory Location


Agrah Upadhyay
B.tech
3rd Year
 
wood burning stoves
 
subject: Strings...