CaldwellYSR CaldwellYSR - 6 months ago 73
Java Question

Java check to see if a variable has been initialized

So I'm pretty new to Java. Been taking a class at my college, this first semester is focussing on getting the syntax down and some of the basic ideas right while using a java library called ObjectDraw. Next semester we're going to start getting away from ObjectDraw and into core Java some more. Anyways I have run into a few problems where I need to use something similar to php's isset function. I know php and java are EXTREMELY different so I shouldn't try to compare them but php is my only basis of previous knowledge on something similar to programming. I just wondered if there was some kind of method that would return a boolean value for whether or not an instance variable had been initialized or not. For example...

if(box.isset()) {
box.removeFromCanvas();
}


So far I've had this problem where I am getting a run-time error when my program is trying to hide or remove an object that hasn't been constructed yet.

Answer

Not really - there's absolutely no difference between a field (instance variable) which hasn't been explicitly assigned at all yet, and one which has been assigned with its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been initialized". Null is a perfectly valid variable value. Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);
Comments