What is the difference between immutable and final in java?

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

    final

    The object cannot be changed.

    final String s = "Hello";
    // Not allowed.
    s = "Bye";
    

    immutable

    The contents of the object cannot be changed.

    BigInteger one = BigInteger.ONE;
    // Does not change `one` or `BigInteger.ONE`.
    one.add(BigInteger.ONE);
    // Have to do it this way.
    BigInteger two = one.add(one);
    

提交回复
热议问题