Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 738
chartle7 Avatar asked Jan 04 '12 21:01

chartle7


People also ask

How do you check if a variable is defined?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do you check if a variable exists or not in Java?

The typeof operator will check whether a variable is defined or not. The typeof operator doesn't throw a ReferenceError exception when it is used with an undeclared variable. The typeof null will return an object. So, check for null also.

How do you check if a variable is not defined?

To check if a variable is undefined, you can use comparison operators — the equality operator == or strict equality operator === . If you declare a variable but not assign a value, it will return undefined automatically. Thus, if you try to display the value of such variable, the word "undefined" will be displayed.

How do you check if a variable has a value?

To check if a variable is not given a value, you would only need to check against undefined and null. This is assuming 0 , "" , and objects(even empty object and array) are valid "values". Show activity on this post.


2 Answers

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) {
    //...
}
like image 189
Bhesh Gurung Avatar answered Oct 05 '22 23:10

Bhesh Gurung


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.

like image 20
th3n3wguy Avatar answered Oct 06 '22 00:10

th3n3wguy