Search code examples
javaimmutabilityfinal

Why won't declaring an array final make it immutable in Java?


Why won't declaring an array final make it immutable in Java? Doesn't declaring something final mean it can't be changed?

From question related to immutable array it's clear that declaring an array final doesn't make it unchangeable.

The following is possible.

final int[] array = new int[] {0, 1, 2, 3};
array[0] = 42;

My question is: What is the function of declaring final here then?


Solution

  • final is only about the reference that is marked by it; there is no such thing as an immutable array in Java. When you say

    private final int[] xs = new int[20];
    

    you won't be allowed to say

    xs = new int[10];
    

    later on. That's all what final is about. More generally, ensuring that an object is immutable is often hard work and full of a range of subtleties. The language itself doesn't give much to this end out of the box.