Why can I still make changes to this final variable? [duplicate]

纵然是瞬间 提交于 2019-12-10 10:20:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!