What is the difference between immutable and final in java?

前端 未结 9 1995
北恋
北恋 2021-01-31 08:51

I was recently asked this quesion. But was not able to explain concisely what exactly sets both these concepts apart.

For example

Final and Immutable:<

9条回答
  •  渐次进展
    2021-01-31 09:34

    Immutable : String and wrapper classes are immutable. Because of the String constant pool they can't change their value inside an object, but they can change references of object holding different values.

    String s1 = new String("cant't change");
    

    Final : when we create a reference of String

    Final String s2 = "cant't change";
    

    The reference for s2 is pointing to object which has value " can't change" inside it.

    The reference s will now always point to the object holding value "can't change". It's reference can't be changed.

提交回复
热议问题