Java基础之【String为什么是immutable】

原文:

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" ,如果一个变化了,那么所有的都会被改变,所以字符串设计为不可变的

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值