Is there a way to check if a variable is defined in Java?
if (variableName != null)
{
//Do something if the variable is declared.
}
else
{
//Do something if the variable doesn't have a value
}
I think that should do it.
It will throw an exception if we try to use an undefined variable in java. To over come these make use of wrapper Class and assigned it to null.
Integer a = null; //correct
int a = null;//error
The code won't compile if you try to use an undefined variable, because, In Java, variables must be defined before they are used.
But note that variables can be null, and it is possible to check if one is null to avoid NullPointerException
:
if (var != null) {
//...
}