Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java final and ragged arrays

Tags:

java

final

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" ?

like image 704
epsilonhalbe Avatar asked Jun 21 '26 07:06

epsilonhalbe


2 Answers

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.

like image 177
rgettman Avatar answered Jun 23 '26 21:06

rgettman


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

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

like image 23
Obicere Avatar answered Jun 23 '26 19:06

Obicere