原文:
https://www.javatpoint.com/immutable-string
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对象被创建它的数据或状态就不能被改变 除了一个新的对象被创立
下面看例子:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
输出:Sachin
上面显示及concat并没有起作用
再看下面例子:
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
输出:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not modified.
在上面例子,s的应用地址指向了Sachin Tendulkar,但是注意 sachin字符串对象依旧没有被修改
译者注:
通过String源码可以看出 private final char value[]; 表明是不可修改的 但是如果看StirngBuffer StringBuilder,char value[]并不是final的
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
}
Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "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使用字符串文字的概念(这个我觉得翻译难以理解,所以google的,其余的我都是自己翻译的),假设有5个引用都是依赖于一个字符串对象"scchin" ,如果一个变化了,那么所有的都会被改变,所以字符串设计为不可变的