Reputation: 504
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?
Upvotes: 20
Views: 30156
Reputation: 52185
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
Upvotes: 4
Reputation: 21
.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"
Upvotes: 2
Reputation:
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
Upvotes: 0
Reputation: 1779
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.
Upvotes: 3
Reputation: 229108
a String is immutable, meaning you cannot change a String in Java. concat() returns a new, concatenated, string.
String s = "TEST";
String s2 = s.trim();
String s3 = s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);
System.out.println("S3 = "+s3);
Upvotes: 49
Reputation: 206816
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");
Upvotes: 11