The problem is that your code has an assumption that
private final int TOTALNUMS = nums.length;
would execute after the constructor, because textually it follows it. That is an incorrect assumption - this line executes before the constructor, at the time nums
is still null
. This is what is causing the exception.
To fix this problem, move the initialization of TOTALNUMS
into the constructor:
private final int TOTALNUMS; // It's OK to leave it final - you are allowed to set it in the constructor
...
public IntegerArray(int[] array) {
nums = array;
TOTALNUMS = nums.length; // If nums is set to a non-null array, this would not cause an exception
}
Finally, note that there is little point in keeping a separate final
variable for the length of nums
, because its length is always available to you, and you do not need to "synchronize" the two if you decide to set nums
to a different array later on.