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" ?
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.
You are not modifying the basket, but rather the apples inside.
The instance of int[][] never changes, just the content inside of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With