字符串不能改变.但是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?
谢谢.(我是新人-_-)
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 派生的东西都遵循这些规则.原始值,例如 ints、bools、chars、float 和 doubles 允许更改内存中的实际值.所以,从这里:
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;
内存中的实际值发生变化.此代码示例不会创建新对象并更改引用,而是仅更改 num 变量在内存中的值.
the actual value in memory changes. Rather than creating a new object and changing the reference, this code sample will simply change the value in memory for the num variable.
至于为什么会这样,这只是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.
相关文章