File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about String

 
bobbie Giant
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • 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!
 
Davy Kelly
Ranch Hand
Posts: 384
  • 0
  • Mark post as helpful
  • send pies
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bobbie,
I made a small program with 1 added print statement just to show you what i mean:
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12022
25
Chrome Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see.
Thanks for both kind answers.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic