Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String Objects

 
Raghu Shree
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class StringEqual
{
public static void main(String args[])
{
String s1="JavaServerPages";
String s2="JavaServer"+"Pages"; //Line 1

String s3="Pages";
String s4="JavaServer"+s3; //Line 2

if (s1==s2)
System.out.println ("s1 and s2 are equal");
else
System.out.println ("s1 and s2 are not equal");

if (s1==s4)
System.out.println ("s1 and s4 are equal");
else
System.out.println ("s1 and s4 are not equal");
}
}

output
s1 and s2 are equal
s1 and s4 are not equal

What does JVM do in line 1 and line. Could any one explain me
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi raghu

String s1="JavaServerPages";
String s2="JavaServer"+"Pages"; //Line 1

This is equal because it is determined at a compile time itself

String s3="Pages";
String s4="JavaServer"+s3; //Line 2

But in this case it is not because S4 is resolved only at run time.
In Runtime whenever a operation is performed on Strings ,it returns new String Object it doesnot refer to old one.

but if u declare s3 as final it will be true

final String s3="Pages";
String s4="JavaServer"+s3;

This is equal because S3 is final and treated as constant.So S4 determined at a compile time itself
 
Raghu Shree
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks vidya? any more suggestions
 
Parameswaran Thangavel
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi vidyasagar
can u point out how mnany objects were created
for me its

JavaServerPages
Pages
JavaServer

 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI Paramesh

Totally 4 created...

At compile time

JavaServerPages
Pages
JavaServer

At Run time

JavaServerPages
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic