Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java's concat() method not do anything?

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?

like image 845
soma sekhar Avatar asked May 12 '10 12:05

soma sekhar


People also ask

Why concat is not working in Java?

a String is immutable, meaning you cannot change a String in Java. concat() returns a new, concatenated, string. Show activity on this post.

What is the use of the concat () method in Java?

The concat() method appends (concatenate) a string to the end of another string.

What concat () will?

The CONCAT function combines the text from multiple ranges and/or strings, but it doesn't provide delimiter or IgnoreEmpty arguments. CONCAT replaces the CONCATENATE function. However, the CONCATENATE function will stay available for compatibility with earlier versions of Excel.

What is return type of concat () method?

Java - String concat() Method The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.


2 Answers

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);
like image 64
nos Avatar answered Oct 02 '22 18:10

nos


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");
like image 23
Jesper Avatar answered Oct 02 '22 20:10

Jesper