字符串在java中是不可变的[重复]

时间:2021-08-08 15:50:59

This question already has an answer here:

这个问题在这里已有答案:

I have the following code, which I have written to check how string is immutable.

我有以下代码,我已编写以检查字符串是如何不可变的。

My code is:

我的代码是:

class Check
{
   public static void main(String k[])
   {
      String a1="JohnPlayer";
      a1.concat("America");//line no 6
      String a2="America";//line no 7
      a1=a1+a2;//line no 8
      System.out.println("Value of a1="+a1);
   }
}

In line no 6, when I use concat, it print only "JohnPlayer", while If I concatenate a1 and a2 using a1+a2, it prints the concatenated value "JohnPlayerAmerica" . In this case, how can I say String is immutable?

在第6行,当我使用concat时,它只打印“JohnPlayer”,而如果我使用a1 + a2连接a1和a2,它会打印连接值“JohnPlayerAmerica”。在这种情况下,我怎么能说String是不可变的?

1 个解决方案

#1


1  

String is immutable.

字符串是不可变的。

a1.concat("America");

returns a new String instance which you ignore. a1 is unchanged.

返回您忽略的新String实例。 a1没有变化。

a1=a1+a2;

creates a new String instance and assigns it to the a1 variable. The original String referenced by a1 is unchanged.

创建一个新的String实例并将其分配给a1变量。 a1引用的原始String未更改。

This is similar to writing :

这与写作类似:

a1 = a1.concat("America");

#1


1  

String is immutable.

字符串是不可变的。

a1.concat("America");

returns a new String instance which you ignore. a1 is unchanged.

返回您忽略的新String实例。 a1没有变化。

a1=a1+a2;

creates a new String instance and assigns it to the a1 variable. The original String referenced by a1 is unchanged.

创建一个新的String实例并将其分配给a1变量。 a1引用的原始String未更改。

This is similar to writing :

这与写作类似:

a1 = a1.concat("America");