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];}
}
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];
}
}
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.
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.
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.
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