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

只谈情不闲聊 提交于 2019-11-26 04:00:31

问题


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?


回答1:


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);



回答2:


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");



回答3:


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.




回答4:


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



回答5:


.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"




回答6:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!