java 字符串不能改变。但是 int, char 可以改变
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1956376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String can't change. But int, char can change
提问by Keating
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?
我读过在 Java 中 String 类型的对象不能改变。但是 int 和 char 变量可以。为什么?你能举个例子吗?
Thank you. (I am a newer -_- )
谢谢你。(我是新人-_-)
回答by Seburdis
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:
正如 bzabhi 所说,字符串在 Java 中是不可变的。这意味着字符串对象永远不会改变。这并不意味着您不能更改字符串变量,只是您不能更改字符串的底层内存表示。例如:
String str = "Hello";
str += " World!";
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.
在执行这些行之后, str 将指向内存中的一个新字符串。原始的“Hello”字符串仍然存在于内存中,但很可能不会存在太久。假设没有情有可原的情况,没有任何东西指向原始字符串,因此它将被垃圾收集。
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.
我想最好的方法是说当示例的第 2 行执行时,内存中的新字符串是从原始字符串和添加到其中的字符串的串联中创建的。str 变量只是对内存位置的引用,然后更改为指向刚刚创建的新变量。
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:
我在这一点上并不是特别了解,但是,据我所知,这就是所有“非原始”值都会发生的情况。在某些时候从 Object 派生的任何东西都遵循这些规则。原始值,例如 ints、bools、chars、floats 和 doubles,允许更改内存中的实际值。所以,从这个:
int num = 5;
num += 2;
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.
内存中的实际值会发生变化。此代码示例将简单地更改内存中 num 变量的值,而不是创建新对象和更改引用。
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.
至于为什么这是真的,这只是 Java 制造商的设计决定。我敢肯定有人会评论为什么这样做,但这不是我所知道的。
回答by itowlson
int and char can't change either. As with strings, you can put a different value into the same variable, but an integer itself doesn't change. 3 will always be 3; you can't modify it to be 4.
int 和 char 也不能改变。与字符串一样,您可以将不同的值放入同一个变量中,但整数本身不会改变。3 永远是 3;您不能将其修改为 4。
回答by TofuBeer
String is an immutable type (the value inside of it cannot change). The same is true for all primitive types (boolean, byte, char, short, int, long, float, and double).
String 是一个不可变类型(它里面的值不能改变)。对于所有原始类型(boolean、byte、char、short、int、long、float 和 double)也是如此。
int x;
String s;
x = 1;
x = 2;
s = "hello";
s = "world";
x++; // x = x + 1;
x--; // x = x - 1;
As you can see, in no case can you alter the constant value (1, 2, "hello", "world") but you can alter where they are pointing (if you warp your mind a bit and say that an int variable points at a constant int value).
如您所见,在任何情况下都不能更改常量值 (1, 2, "hello", "world") 但您可以更改它们指向的位置(如果您稍微扭曲一下并说 int 变量指向在一个恒定的 int 值)。
回答by Stephen C
I'm not sure that it is possible to show (by example) that Strings cannot change. But you can confirm this by reading the description section of Javadoc for the String class, then reading the methods section and noting that there are no methods that can change a String.
我不确定是否可以(通过示例)显示字符串不能更改。但是您可以通过阅读String 类的Javadoc的描述部分,然后阅读方法部分并注意没有可以更改字符串的方法来确认这一点。
EDIT: There are many reasons why Strings are designed to be immutable in Java. The most important reason is that immutable Strings are easier to use correctly than mutable ones. And if you do need the mutable equivalent of a String for some reason, you can use the StringBuilder (or StringBuffer) class.
编辑:在 Java 中将字符串设计为不可变的原因有很多。最重要的原因是不可变字符串比可变字符串更容易正确使用。如果出于某种原因确实需要 String 的可变等价物,则可以使用 StringBuilder(或 StringBuffer)类。
回答by Jeremy Raymond
It's also worthwhile to note that since strings are immutable, that if they are passed into a method, they can't be modified inside of the method and then have those changes seen outside of the method scope.
还值得注意的是,由于字符串是不可变的,如果将它们传递给方法,则不能在方法内部修改它们,然后在方法范围之外看到这些更改。
public void changeIt(String s) {
// I can't do anything to s here that changes the value
// original string object passed into this method
}
public void changeIt(SomeObject o) {
// if SomeObject is mutable, I can do things to it that will
// be visible outside of this method call
}
回答by Rushil Paul
Strings are immutable in java. Nevertheless, you can still append or prepend values to strings. By values, I mean primitive data types or other strings.
字符串在java. 尽管如此,您仍然可以向字符串附加或预先添加值。通过值,我指的是原始数据类型或其他字符串。
However, a StringBufferis mutable, i.e. it can be changed in memory (a new memory block doesn't have to be allocated), which makes it quite efficient. Also, consider the following example:
但是,StringBuffer是可变的,即它可以在内存中更改(不必分配新的内存块),这使得它非常有效。另外,请考虑以下示例:
StringBuffer mystringbuffer = new StringBuffer(5000);
for (int i = 0; i<=1000; i++)
{
mystringbuffer.append ( 'Number ' + i + '\n');
}
System.out.print (mystringbuffer);
Rather than creating one thousand strings, we create a single object (mystringbuffer), which can expand in length. We can also set a recommended starting size (in this case, 5000 bytes), which means that the buffer doesn't have to be continually requesting memory when a new string is appended to it.
我们不是创建一千个字符串,而是创建一个mystringbuffer可以扩展长度的对象 ( )。我们还可以设置推荐的起始大小(在本例中为 5000 字节),这意味着缓冲区不必在向其附加新字符串时不断请求内存。
While a StringBufferwon't improve efficiency in every situation, if your application uses strings that grow in length, it would be efficient. Code can also be clearer with StringBuffers, because the append method saves you from having to use long assignment statements.
虽然 aStringBuffer不会在所有情况下都提高效率,但如果您的应用程序使用长度增加的字符串,它将是有效的。代码也可以用StringBuffers更清晰,因为 append 方法使您不必使用长赋值语句。
回答by mpen
This little article can probably explain it better than I can: http://www.jchq.net/tutorial/09_02Tut.htm
这篇小文章可能比我更能解释它:http: //www.jchq.net/tutorial/09_02Tut.htm

