字符串不能更改。但是int,char可以改变 [英] String can't change. But int, char can change

查看:129
本文介绍了字符串不能更改。但是int,char可以改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过在Java中一个String类型的对象不能改变。但是int和char变量可以。为什么?你能给我一个例子吗?

I've read that in Java an object of type String can't change. But int and char variables can. Why is it? Can you give me an example?

谢谢。
(I am a newer -_-)

Thank you. (I am a newer -_- )

推荐答案

正如bzabhi所说,字符串在Java中是不可变的。这意味着一个字符串对象永远不会改变。这并不意味着你不能改变字符串变量,只是你不能改变字符串的底层内存表示。例如:

As bzabhi said, strings are immutable in Java. This means that a string object will never change. This does not mean you can not change string variables, just that you cannot change the underlying memory representation of the string. for an example:

String str = "Hello";
str += " World!";

执行这些行后,str将指向内存中的一个新字符串。原始的Hello字符串仍然存在于内存中,但很可能不会长时间存在。假设没有可减轻的情况,没有什么会指向原始字符串,所以它将被垃圾收集。

Following the execution of these lines, str will point to a new string in memory. The original "Hello" string still exists in memory, but most likely it will not be there for long. Assuming that there are no extenuating circumstances, nothing will be pointing at the original string, so it will be garbage collected.

我猜测最好的方法是,当示例的第2行执行时,内存中的一个新字符串从原始字符串的连接创建并将字符串添加到它。然后,将str变量(仅仅是对内存位置的引用)更改为指向刚创建的新变量。

I guess the best way to put this would be to say that when line 2 of the example executes, a new string in memory is created from the concatenation of the original string and the string being added to it. The str variable, which is just a reference to a memory location, is then changed to point at the new variable that was just created.

我不是特别了解这一点,但是,据我所知,这是所有非原始值发生的。任何在某种程度上派生自Object遵循这些规则。原始值,例如int,bools,chars,float和double允许改变内存中的实际值。所以,从这:

I am not particularly knowledgeable on the point, but, as I understand it, this is what happens with all "non-primitive" values. Anything that at some point derives from Object follows these rules. Primitive values, such as ints, bools, chars, floats and doubles allow the actual value in memory to be changed. So, from this:

int num = 5;
num += 2;

内存变化的实际值。

至于为什么这是真的,它是真的,而不是创建一个新的对象和更改引用,只是Java制造商的设计决策。我相信有人会评论为什么这样做,但这不是我知道的。

As for why this is true, it is simply a design decision by the makers of Java. I'm sure someone will comment on why this was made, but that isn't something I know.

这篇关于字符串不能更改。但是int,char可以改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆