問(wèn)題描述
我讀到在 Java 中,String 類型的對(duì)象不能改變.但是 int 和 char 變量可以.為什么?可以舉個(gè)例子嗎?
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 所說(shuō),字符串在 Java 中是不可變的.這意味著字符串對(duì)象永遠(yuǎn)不會(huì)改變.這并不意味著您不能更改字符串變量,只是您不能更改字符串的底層內(nèi)存表示.例如:
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!";
在這些行執(zhí)行之后,str 將指向內(nèi)存中的一個(gè)新字符串.原始的Hello"字符串仍然存在于內(nèi)存中,但很可能不會(huì)存在太久.假設(shè)沒(méi)有情有可原的情況,任何東西都不會(huì)指向原始字符串,所以它將被垃圾收集.
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.
我想最好的說(shuō)法是,當(dāng)示例的第 2 行執(zhí)行時(shí),內(nèi)存中的一個(gè)新字符串是由原始字符串和添加到其中的字符串的串聯(lián)創(chuàng)建的.str 變量只是對(duì)內(nèi)存位置的引用,然后更改為指向剛剛創(chuàng)建的新變量.
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.
我對(duì)這一點(diǎn)并不是特別了解,但據(jù)我了解,這就是所有非原始"值都會(huì)發(fā)生的情況.任何從 Object 派生的東西都遵循這些規(guī)則.原始值,例如 ints、bools、chars、float 和 doubles 允許更改內(nèi)存中的實(shí)際值.所以,從這里:
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;
內(nèi)存中的實(shí)際值發(fā)生變化.此代碼示例不會(huì)創(chuàng)建新對(duì)象并更改引用,而是僅更改 num 變量在內(nèi)存中的值.
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.
至于為什么會(huì)這樣,這只是Java制造商的設(shè)計(jì)決定.我相信有人會(huì)評(píng)論為什么會(huì)這樣,但我不知道.
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.
這篇關(guān)于字符串不能改變.但是int、char可以改變的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!