What is the difference between immutable and final in java?

前端 未结 9 1851
北恋
北恋 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:45

    When you use keyword "final", that means that you cannot change the reference of the object that the variable points to. So, in this case variable "name" cannot be made to point to another string object. However, please note that we can change the contents of the object since we are using a final reference. Also Strings in java are inherently immutable. i.e. you cannot change its contents. So, in your case, final will make a final reference to a string object. and since you can't change the variable to point to another string object, code fails.

    See the code below to understand working of final variable.

    public class test {
    
    public static void main(String[] args) {
        final A aObject = new A();
        System.out.println("Old value :" + aObject.a);
        aObject.a = 2;
        System.out.println("New value :" + aObject.a);
    }} 
    
    class A {
    public int a = 1;}
    

提交回复
热议问题