chartle7
chartle7

Reputation: 237

Is there a way to check if a variable is defined in Java?

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

Answers (3)

Nirmal Lamrin
Nirmal Lamrin

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

Bhesh Gurung
Bhesh Gurung

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

th3n3wguy
th3n3wguy

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

Related Questions