aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question about String" Watch "Question about String" New topic
Author

Question about String

bobbie Giant
Greenhorn

Joined: Feb 18, 2004
Posts: 4
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

Joined: Jan 12, 2004
Posts: 384
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


How simple does it have to be???
Davy Kelly
Ranch Hand

Joined: Jan 12, 2004
Posts: 384
Bobbie,
I made a small program with 1 added print statement just to show you what i mean:
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11499
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
bobbie Giant
Greenhorn

Joined: Feb 18, 2004
Posts: 4
I see.
Thanks for both kind answers.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about String