What is the difference between immutable and final in java?

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

    Immutable:

    when you change the String, create new String object ('abcdef') and change the reference from 'abce' to 'abcdef'.But you can not remove 'abcd'. Only change the reference. That is immutable.

    final:

    Actually final is a keyword.When you add it to variable, you can not change the reference.

    0 讨论(0)
  • 2021-01-31 09:44

    When you have a field declared as final, the reference will not change. It will always point at the same Object.

    if the Object is not immutable, the methods on it can be used to change the Object itself - it is the same Object, but its properties have been changed.

    0 讨论(0)
  • 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;}
    
    0 讨论(0)
提交回复
热议问题