check if variable is initialized in Java
You can use if (Average == null)
to check if it's null, but you cannot tell if it was explicitly set to null or just null by default.
This works for every Object type (arrays are also objects), because objects' default value is null. The 8 primitive types (int, byte, float, char, long, short, double and boolean) however cannot be null. E.g. an int
is 0 by default if you do not assign a value to it.
Arrays in java works like objects (they are not primitive types).
So yes, you can check if your array was initialized or not with :
private void check(){
if(average == null){
average = new float[4];
}
}
A better solution (if you know the array size when instantiate)
But in my opinion, you'd better initialize the variable in your class constructor, like bellow :
public class MyClass {
private float[] average;
public MyClass(int arraySize) {
this.average = new float[arraySize];
}
}
This way, you'll be sure it is initialized everytime a MyClass
object is created.
An even better solution (even if you don't know the array size when instantiate)
If you don't know the size of the array, i'd better use a List
:
public class MyClass {
private List<Float> average;
public MyClass() {
this.average = new ArrayList<>();
}
}
Lists are resized automatically as they goes full.