当string是不可变的时,怎么来System.out.println(s.concat(" some string"));返回更改后的值

时间:2016-10-04 06:13:21

标签: java string immutability

我写了以下代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String s = new String("abc");
    System.out.println(s.concat("def"));
}

它正在向我返回输出:" abcdef"

如果字符串是不可变的,这怎么可能。

3 个答案:

答案 0 :(得分:6)

s.concat("def")会返回一个新的String实例。 String引用的s实例保持不变。

您可以添加另一个println语句,以便自己查看:

public static void main(String[] args) {
    String s = new String("abc");
    System.out.println(s.concat("def"));
    System.out.println(s);
}

您还可以在concat

的Javadoc中看到它
  

如果参数字符串的长度为0,则返回此String对象。否则,返回一个String对象,该对象表示一个字符序列,该字符序列是由此String对象表示的字符序列和由参数字符串表示的字符序列的串联。

仅当您将空String传递给此方法时,才会返回原始String

答案 1 :(得分:2)

它返回一个新的String而不是一个已更改的String

public static void main(String[] args) {
    String s = new String("abc");
    System.out.println(s.concat("def"));
    System.out.println(s);
}

答案 2 :(得分:1)

来自Oracle Java Docs

public String concat(String str)
Concatenates the specified string to the end of this string.
  

如果参数字符串的长度为0,则此String对象为   回。否则,创建一个新的String对象,表示一个   字符序列,是字符序列的串联   由此String对象和字符序列表示   由参数字符串表示。

Examples:

 "cares".concat("s") returns "caress"
 "to".concat("get").concat("her") returns "together"
  

参数:str - 连接到此结尾的String   字符串。

     

返回:表示此对象的串联的字符串   字符后跟字符串参数的字符。