Java-Programming-Docs Help

Array Immutability

It is useful to return an array clone from a method if you do not want the caller of your method to modify the underlying array structure. While you can declare arrays to be final, as in the following example:

final static int[] array = {1, 2, 3, 4, 5, 6};

Declaring an object reference final (specifically, an array reference here) does not restrict you from modifying the object. It only limits you from changing what the final variable refers to. While the following line results in a compilation error:

class FinalArrayDemo { public static void main(String[] args) { array = new int[]{7, 8, 9, 10}; } }

Changing an individual element is perfectly legal:

class FinalArrayDemo { public static void main(String[] args) { array = new int[]{7, 8, 9, 10}; array[2] = 12; } }
    Last modified: 16 July 2024