For a field variable you can check by comparing the int
to 0
that is the default value for an int
field :
private int x: // default 0 for an int
...
public void foo(){
if (x == 0){ // valid check
// ...
}
}
Built-in types have a default "reasonable" value :
Default Values
It's not always necessary to assign a value when a field is declared.
Fields that are declared but not initialized will be set to a
reasonable default by the compiler. Generally speaking, this default
will be zero or null, depending on the data type. Relying on such
default values, however, is generally considered bad programming
style.
The following chart summarizes the default values for the above data
types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
For a local variable no check is required and is even possible because the compiler does the check for you.
The compilation will indeed not pass if any statement refers a not initialized variable.
So the code that checks the int
local variable will not compile itself for this reason :
public void foo(){
int a;
if (a==0) { // doesn't compile : The local variable a may not have been initialized
...
}
}