Java – 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?

Best Solution

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) {