Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a variable is set?

Tags:

java

variables

In PHP, there is a isset function. What about Java? I think I can use == null with objects, but what about value types like int

like image 280
Jiew Meng Avatar asked Oct 09 '11 12:10

Jiew Meng


People also ask

How do you check if a variable is set or not in shell script?

To check if a variable is set in Bash Scripting, use-v var or-z ${var} as an expression with if command. This checking of whether a variable is already set or not, is helpful when you have multiple script files, and the functionality of a script file depends on the variables set in the previously run scripts, etc.

How do I check if an environment variable is set in bash?

To confirm whether a variable is set or not in Bash Scripting, we can use -v var or -z ${var} options as an expression with the combination of 'if' conditional command.


2 Answers

Java's compiler won't let you define variables and use them before they were assigned a value, so the problem doesn't exist in the same form as it exists in php.

EDIT

If in your case the compiler didn't stop you already (because this is eg an instance variable) the best solution is probably to initialize the variable to some "special" value as suggested by Guest11239193. Like this:

int x = 0; // because by convention 0 is a reasonable default here 

Of course, what a "safe, reasonable" initialization value is depends on the application.

Afterwards, you could

if (x == 0) { // only allow setting if x has its initial value     x = somenewvalue; } 

Or you could access x via a setter that inhibits changing more than once (probably overkill for most cases):

private int x; private boolean x_was_touched = false;  public void setX (int newXvalue) {     if (!x_was_touched) {        x = newXvalue;        x_was_touched = true;     } }  public int getX() {     return x; } 

You could also use an Integer, int's object brother, which could be initialized to null

Integer x = null;  

However, the fact that you think you need that knowledge may hide a deeper logic flaw in your program, so I'd suggest you explore the reason why you want to know if a primitive value (primitive as opposed to objects, int vs Integer) wasn't touched.

like image 95
fvu Avatar answered Sep 29 '22 06:09

fvu


A non-existing variable doesn't exist in Java.

like image 41
Mob Avatar answered Sep 29 '22 06:09

Mob