Java check to see if a variable has been initialized
Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.
Now if you know that once assigned, the value will never reassigned a value of null, you can use:
if (box != null) {
box.removeFromCanvas();
}
(and that also avoids a possible NullPointerException
) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:
if (box != null) {
box.removeFromCanvas();
// Forget about the box - we don't want to try to remove it again
box = null;
}
The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):
// Won't compile
String x;
System.out.println(x);
// Will compile, prints null
String y = null;
System.out.println(y);
Instance variables or fields, along with static variables, are assigned default values based on the variable type:
- int:
0
- char:
\u0000
or0
- double:
0.0
- boolean:
false
- reference:
null
Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.