string.concat与字符串连接中的+运算符之间的区别

时间:2018-05-31 14:42:48

标签: java string-concatenation

(这个问题可能重复,但我真的不理解其他答案)

您有以下代码:

String str ="football";
str.concat(" game");
System.out.println(str); // it prints football

但是这段代码:

String str ="football";
str = str + " game";
System.out.println(str); // it prints football game

那么差异是什么以及究竟发生了什么?

2 个答案:

答案 0 :(得分:4)

str.concat(" game");str + " game";具有相同的含义。如果你没有将结果分配回某个地方,它就会丢失。你需要这样做:

str = str.concat(" game");

答案 1 :(得分:2)

' concat'函数是不可变的,因此它的结果必须放在一个变量中。使用:

str = str.concat(" game");
相关问题