• 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

Question about String

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
the code fragment as following:
//
String s1="abcd";
s1.concat("ef");
System.out.println(s1);
//the output is "abcd".--Ok,sure.
System.out.println(s1.concat("ef"));
//the output is "abcdef"--Why not "abcd"?
Great thanks for anyone's answer!
 
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Bobbie

the code fragment as following:
//
String s1="abcd";
s1.concat("ef");
System.out.println(s1);
//the output is "abcd".--Ok,sure.
System.out.println(s1.concat("ef"));
//the output is "abcdef"--Why not "abcd"?
Great thanks for anyone's answer!


s1 cannot concatenate ef to the end because you did not assign s1 for this: s1 = s1.concat("ef");
but in the print statement it is printing what s1.concat("ef"); would have been, but still not assigning the value to s1
Hope this helps.
Davy
 
Davy Kelly
Ranch Hand
Posts: 384
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Bobbie,
I made a small program with 1 added print statement just to show you what i mean:
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
another way to look at it is that String.concat() returns a string. the first concat returns the string, but it is lost. so, as you said, System.out.println(s1) prints abcd.
the second concat() also returns a string, which is passed to the println method. println is NOT printing s1, but the string returned by concat.
 
bobbie Giant
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I see.
Thanks for both kind answers.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic