Why can I still make changes to this final variabl

2019-05-10 10:34发布

问题:

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);
    }

}

回答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.



标签: java final