I have the following two object variables
Date a;
Date b=null;
Definitely both ‘a’ and ‘b’ are not referring to any objects.
Now if I invoke following statement
System.out.println(a.toString());
There will be a compile time error, whereas if I invoke the following statement
System.out.println(b.toString());
There will be no compile time error but there will be a runtime error. What is the reason for this and what value will be actually stored in ‘b’ to represent a null value?
5
Thats because the state of local variables is controlled within its scope
// method/loop/if/try-catch etc...
{
Date d; // if it's not intialised in this scope then its not intialised anywhere
}
Which is not the case for fields
class Foo{
Date d; // it could be intialised anywhere, so its out of control and java will set to null for you
}
Now, why its fine to set a variable to null and use it immediately? maybe that is a historical mistake that sometimes leads to horrible mistakes
{
Date d = null;
try{
}catch{ // hide it here
}
return d;
}
Now what’s the semantic difference?
Date d;
just declares variable that can hold a reference that points to an object of type Date
, however
Date d= null;
does exactly the same but the reference is pointing to null this time, null is like any reference, it takes a space of a native pointer, that is 4 byte on 32-bit machines and 8 bytes on 64-bit machines
8
There is no difference for class fields. They are null
by default for objects, 0 for numeric values and false
for booleans.
For variables declared in methods – Java requires them to be initialized. Not initializing them causes a compile time error when they are accessed.
What’s the reason? Class fields can be modified by any method. In any order the method is invoked. All non-private fields may be modified by other classes and/or classes extending that class. Hence, there is no point in notifying about an uninitialized variable, since it may be assigned in many, many places.
Variables inside methods, however, are local and can be modified only inside the method itself. Hence it is both possible and rational to point possible mistakes. And the compiler tries to do it. If it knows the field is not initialized, it will show an error, because that’s never what you want. If it is not sure – it will give a warning, so that you can make sure.
public static class Test {
Date a; // ok
Date b = null; // ok
public void test() {
Date c;
Date d = null;
System.out.println(a.toString());
System.out.println(b.toString());
System.out.println(c.toString()); // error
System.out.println(d.toString()); // warning
}
}
0