Wednesday 13 February 2008

java variable to be initialized to null

This topic concerns variable scope.

Local variable: It's called in the local method, has no default value.
instance variable: It's from other class which is called by local class ('s method).

Here is an example:

Local Object
References


Objects references, too, behave differently when declared
within a method rather than as instance variables. With instance variable object
references, you can get away with leaving an object reference uninitialized, as
long as the code checks to make sure the reference isn't null before using
it. Remember, to the compiler, null is a value.
You can't use the dot operator on a null reference,
because there is no object at the other end of it, but a
null reference is not the same as an uninitialized reference. Locally declared references can't
get away with checking for null before use,
unless you explicitly initialize the local variable to null. The compiler
will complain about the following code:


import java.util.Date;
public class TimeTravel {
public static void main(String [] args) {
Date date;
if (date == null)
System.out.println("date is null");
}
}

Compiling the code results in an error similar to the
following:


%javac TimeTravel.java
TimeTravel.java:5: Variable date may not have been initialized.
if (date == null)
1 error

Instance variable references are always given a default value of
null, until
explicitly initialized to something else. But local references are not given a
default value; in other words, they aren't null. If you don't
initialize a local reference variable, then by default, its value iswell that's the whole point—it doesn't have any value at
all! So we'll make this simple: Just set the darn thing to null explicitly, until you're ready to initialize it
to something else. The following local variable will compile properly:


Date date = null; // Explicitly set the local reference
// variable to null



Powered by ScribeFire.

1 comment:

Jay Patel said...

This is really good explanation. Thanks.

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter