What is the difference between immutable and final in java?

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

    final String name = "John";
    

    When you write the above your code is telling the compiler that the reference name will always point to the same memory location. Now why I say memory location because it might happen that the object the reference is pointing to is mutable like array or list of integers. So if I say final int[] arr = {5,6,1}; I can do arr[2] = 3; but I can't do arr = {3,4,5} cause you will be trying to assign a new int[] to final variable arr which is a new memory location and seeing this compiler will show error.

    String name = "John";
    name = "Sam"; 
    

    Above the name variable of type String is immutable because String in java is immutable which means you can't change the state of the object pointed out by the reference name once it is created and even if you change it to Sam it is now a different object which is pointed by the reference name and the previous object John will have no reference and can be collected by garbage collector whenever it runs if it has no other references pointing to it.

提交回复
热议问题