What is the difference between immutable and final in java?

前端 未结 9 2023
北恋
北恋 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

    final ensure that the address of the object remains the same. Where as the Immutable suggests that we can't change the state of the object once created.

    final is just a keyword whereas Immutable is a pattern.

    In Case of your first question you have marked the variable as final, which means you would not be able to change the memory address of it and can't assign a value once more.

    In case of your second question Immutable ensures you can't change the state of the object you have created.

提交回复
热议问题