Reputation: 237
In my app in android I need to check if a variable has been defined yet so I dont get a null pointer exception. Any way around this?
Upvotes: 20
Views: 81548
Reputation: 51
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
Upvotes: 1
Reputation: 51030
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) {
//...
}
Upvotes: 40
Reputation: 3747
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.
Upvotes: 3