How to test if a variable is set?

In Java it is a compiler error to use a variable without being set.

Class and instance variables are initialized with what is considered a default "null" value, depending on the data type.

So a isset like function does not make sense.


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.


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


You can't check if the variable is set. You can:

  1. Initialize the variable that makes sense as an initial value -- such 0 for a counter, the maximal integer value if you're calculating a minimum, etc.
  2. Initialize the variable to a value that you aren't going to use, for example -1 if you're going to use unsigned integer values and an empty string for a string.
  3. Introduce a boolean flag that indicates whether you have started doing something.

Tags:

Java

Variables