I have a doubt from one of the answers in stackoverflow to the following question:
How many String objects are created by the following code?
String x = new String("xyz");
String y = "abc";
x = x + y;
In Stephen's answer he mentioned x and y are not constant variables.
My doubt- String is a final class, and it's instance will be a constant because String is an immutable class. Why is the reference variable of this constant class not a constant variable? - I do agree with Stephen though as x = x + y;
points at "xyzabc" created in the heap memory.
There are a few concepts that you need to understand.
Marking a class as final
does not make it immutable. It just makes it un-inheritable.
JLS §8.1.1.2
A class can be declared final if its definition is complete and no subclasses are desired or required.
It is a compile-time error if the name of a final class appears in the extends clause (§8.1.4) of another class declaration; this implies that a final class cannot have any subclasses.
A class is said to be immutable when the values that it stores cannot be changed after initialisation.
A constant variable is a variable marked with final
.
JLS §4.12.4
A variable can be declared final. A final variable may only be assigned to once. Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.
It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.
x
and y
here are not constants because they are not marked final
. That's it .
"But strings can't change, so they are constants, right?" you might ask.
String
objects themselves can't change, but string variables can . I'll show you:
String s = "Hello";
s = "Goodbye";
The variable's value is changed so that it refers to another string. The original string "Hello" is not changed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.