Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if variable is initialized in Java [duplicate]

Tags:

java

Is there a way in Java to check the variable is initialized of not inside a class. I found for javascript but not for Java. Hear is an example of what I am looking for.

private float[] Average;
private void Check(){
if(/*variable is not initialized*/){ Average = new float[4];}
}
like image 643
mr_azad Avatar asked Dec 27 '15 01:12

mr_azad


2 Answers

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.

like image 103
Anthony Raymond Avatar answered Sep 20 '22 18:09

Anthony Raymond


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.

like image 45
Andrea Dusza Avatar answered Sep 19 '22 18:09

Andrea Dusza