This question already has an answer here:
- Final variable manipulation in Java 9 answers
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);
}
}
final
refers to not being able to change the reference, e.g. you cannot sayname = 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.
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.