• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

needs explanation for the output

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class StringRef
{
public static void main(String [] args)
{
String s1 = "abc";
String s2 = "def";
String s3 = s2;
s2 = "ghi";
System.out.println(s1 + s2 + s3);
}

}

OUTPUT:abcghidef

why for the above program the output is not "abcghighi"
can anybody provide the explanation for the above?

thanks&cheers
venkat
 
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hai venkatramsimha ,




In the code,
line 1 : String abc assign to s1
line 2 : String def assign to s2
line 3 : s3 also now pointing to def
line 4 : s2 now pointing to ghi(but still s3 points to def)

So it prints abcghidef






s3=s2;
means we r assinging the s2 reference to s3 ie,now s3 contain "def"
so s2 is pointing nothing,then s2 is assined with some other string
 
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
In Line 1 s2 point s "def", Line 2 s3 points "def" because s2 has a reference value of string object "def". So s3 also point to "def" in Line 3 you change the reference value of s2. It point to the object "ghi". So s3 reference values are not updated here. So output is abcghidef.
 
reply
    Bookmark Topic Watch Topic
  • New Topic