Immutable String in Java(在Java中String字符串的不变性)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Immutable String in Java(在Java中String字符串的不变性),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2296字,纯文字阅读大概需要4分钟。
内容图文
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中的字符串不变性
原文:https://www.cnblogs.com/LinQingYang/p/12682610.html
内容总结
以上是互联网集市为您收集整理的Immutable String in Java(在Java中String字符串的不变性)全部内容,希望文章能够帮你解决Immutable String in Java(在Java中String字符串的不变性)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。