Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strings...

 
Ramya Iyer
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ramya,
I see that your code says

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

Roopesh.
 
Lalitha Vydyula
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 579
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic