Question

why is this code working?

public class Final {
    public final int[][] arr = new int[2][];
    Final(){
        arr[0] = new int[4];
        arr[0] = new int[5];
        arr[1] = new int[4];
        }
    public static void main(String[] args) {
        Final fi = new Final();
        System.out.println(fi.arr[0].length);
        System.out.println(fi.arr[1].length);
    }
}

whereas the following does not work (which is correct as I assume).

public class Final {
    public final int[] arr;
    Final(){
        arr = new int[4];
        arr = new int[5];
        }
    public static void main(String[] args) {
        Final fi = new Final();
        System.out.println(fi.arr.length);
    }
}

When is the final statement "kicking in" ?

Was it helpful?

Solution

The final keyword indicates that the value of the variable will not change once it's initialized. That makes the most sense for primitives, where final int = 5; means it can't be reassigned 6.

For reference variables, it means that it can't be re-assigned to another reference, because the value is the reference to an object. But it doesn't stop you from modifying the contents of the array. It just stops you from doing another assignment to the reference variable. That's why the second piece of code doesn't work -- you assign it another object after it was already assigned for the first time.

OTHER TIPS

You are not modifying the basket, but rather the apples inside.

The instance of int[][] never changes, just the content inside of it.

The fact that arr is marked final just means you can't make arr reference a different value. You're still completely free to modify the contents of the array.

So that means that this is not allowed:

arr = new int[4];
arr = new int[5]; //Reassigning a final variable that's already initialized- bad!

but this is fine:

 arr[0] = new int[4]; 
 arr[0] = new int[5];
 arr[1] = new int[4]; //We haven't changed the array that arr is pointing to

Arrays are objects in Java. Object-Variables are in fact references to an object. Final variables or final fields are references that cannot point to another object after initialization. The referenced object itself can be modified. You've to distinguish the reference and the referenced object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top