This code:
String s = "TEST";
String s2 = s.trim();
s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);
results in this output:
S = TEST
S2 = TEST
BUILD SUCCESSFUL (total time: 0 seconds)
Why are "TEST" and "ING" not concatenated together?
Because String
is immutable - class String
does not contain methods that change the content of the String
object itself. The concat()
method returns a new String
that contains the result of the operation. Instead of this:
s.concat("ING");
Try this:
s = s.concat("ING");
I think what you want to do is:
s2 = s.concat("ING");
The concat function does not change the string s, it just returns s with the argument appended.
concat
returns a string, so you are basically calling concat without storing what it returns.
Try this:
String s = "Hello";
String str = s.concat(" World");
System.out.println(s);
System.out.println(str);
Should print:
Hello
Hello World
.concat()
method returns new concatenated value.
there you did s.concat("ING")
--> this gives return value "Testing". But you have to receive it in declared variable.
If you did s=s.concat("ING");
then the value of "s" will change into "TESTING"
As String is immutable when concat() is called on any String obj as
String s ="abc"; new String obj is created in String pool ref by s
s = s.concat("def"); here one more String obj with val abcdef is created and referenced by s
来源:https://stackoverflow.com/questions/2818796/why-does-javas-concat-method-not-do-anything