views:

170

answers:

4

Consider the code below,

String s = "TEST";
String s2 = s.trim();

s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);

Output obtained :

S = TEST
S2 = TEST
BUILD SUCCESSFUL (total time: 0 seconds)

Why "ING" is not concatenated?

+2  A: 

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");
Jesper
yup..its working in this manner..thanku..
soma sekhar
+13  A: 

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);
nos
Thank you..my doubt got clarified.. :)
soma sekhar
@soma sekhar, if this answer solved your question, you should accept it.
matt b
+2  A: 

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.

MatsT
+1  A: 

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

npinti