问题
If name is declared final, why i can still call name.append and the output is: shreya? I thought final variables cannot be changed once a value is assigned?
public class Test1 {
final static StringBuilder name = new StringBuilder("sh");
public static void main(String[] args) {
name.append("reya");
System.out.println(name);
}
}
回答1:
final refers to not being able to change the reference, e.g. you cannot say name = new StringBuilder(). It does not make the referenced object immutable.
Immutability is a property of a class. An object of a mutable type is always mutable.
回答2:
You have to start making the distinction between variables, values (reference values and primitive values) and objects and primitives.
A variable is container for a value. That value is either a reference value (for objects) or a primitive value.
You cannot use the assignment operator to assign a new value to a final variable once it has been initialized with its original value.
来源:https://stackoverflow.com/questions/27850989/why-can-i-still-make-changes-to-this-final-variable