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?
Best Answer
Thats because the state of local variables is controlled within its scope
Which is not the case for fields
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
Now what's the semantic difference?
just declares variable that can hold a reference that points to an object of type
Date
, howeverdoes 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