Search code examples
javaclassvariablesstaticfinal

How is my final array being modified?


I have something similar to this:

(SomeClass)
public static final float[][][] values = {...};

public float[][][] variable = values;

So, I create a new instance of this class and pass the values to a public member of this class, like I did up there.

Thing is, when I work with variable now and change it and stuff, it gets changed for all instances of SomeClass.

final cant be modified after declaration I thought? So why isn't variable more like a copy of values but gets modified like a static but not final variable?


Solution

  • What happens is that when you do

    public static final float[][][] values = {...};
    
    public float[][][] variable = values;
    

    both values and variable "point" to the same reference (i.e. to the same location in memory).

    What final means is that you cannot change that reference (i.e. you can't make the variable refer to another location in memory). You can still modify the object the varible refers to.