Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
在Java中,String对象是不可变的。不可变仅仅意味着不可修改或不可改变。
Once string object is created its data or state can't be changed but a new string object is created.
一旦创建了string对象,它的数据或状态就不能更改,只能创建一个新的string对象。
Let's try to understand the immutability concept by the example given below:
让我们试着通过下面的例子来理解这个不变性的概念:
1 class Testimmutablestring{
2 public static void main(String args[]){
3 String s="Sachin";
4 s.concat(" Tendulkar");
5 //concat() method appends the string at the end
6 //concat()方法将字符串追加到末尾
7 System.out.println(s);
8 //will print Sachin because strings are immutable objects
9 因为字符串是不可变的对象,所以会打印Sachin
10 }
11 }
Output: Sachin
Now it can be understood by the diagram given below.
现在可以通过下图来理解。
Here Sachin is not changed but a new object is created with sachintendulkar.
这里没有改变Sachin,而是使用sachintendulkar创建了一个新对象。
That is why string is known as immutable.
这就是为什么字符串是不可变的。
As you can see in the above figure that two objects are created but s reference variable still refers to "Sachin" not to "Sachin Tendulkar".
从上图中可以看出,创建了两个对象,但是s引用变量仍然指向“Sachin”而不是“Sachin Tendulkar”。
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For example:
但是如果我们明确地将它赋值给引用变量,它将引用“Sachin Tendulkar”对象。例如:
1 class Testimmutablestring1{
2 public static void main(String args[]){
3 String s="Sachin";
4 s=s.concat(" Tendulkar");
5 System.out.println(s);
6 }
7 }
Output: Sachin Tendukar
In such case, s points to the "Sachin Tendulkar".
在这种情况下,s指向“Sachin Tendulkar”。
Please notice that still sachin object is not modified.
请注意,仍然没有修改sachin对象。
Why string objects are immutable in java?
为什么字符串对象在java中是不可变的?
Because java uses the concept of string literal.
因为java使用了字符串文字的概念。
Suppose there are 5 reference variables,all referes to one object "sachin".
假设有5个引用变量,都引用一个对象“sachin”。
If one reference variable changes the value of the object, it will be affected to all the reference variables.
如果一个引用变量改变了对象的值,它将影响到所有引用变量。
That is why string objects are immutable in java.
这就是为什么字符串对象在java中是不可变的。
同时推荐观看另两篇博文,加深理解:Java——理解字符串不变性 、Java中的字符串不变性