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.