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!
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
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