Java – Difference Between Uninitialized Object Variable and Object Variable Initialized to Null

java

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

 // 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