In the case of class fields, there's no difference at all. Fields that aren't explicitly initialised are initialised with the default value for that type when an instance of the class is created; in the case of objects, the default is null
. So:
private MyClass myClass1;
is equivalent to
private MyClass myClass1 = null;
since both will result in myClass1
being null
.
In the case of method variables, there's a pretty large difference. Variables have to have a value declared, even if that's null
, otherwise you'll get (potential) compiler errors when you later try to use it. Doing something like this:
public void myMethod() {
MyClass myClass1;
if(someCondition)
myClass1 = new MyClass();
myClass1.doSomething();
}
would be invalid, since the compiler can't guarantee that myClass1
will have a value. Changing that line to MyClass myClass1 = null;
would be valid, though in practice you could get a runtime error (a NullPointerException
) if someCondition
isn't true.
You could do something like this:
MyClass myClass1;
// calculate some values
myClass1 = new MyClass(arg1, arg2, ...);
but that seems pointless to me; there's no need to have myClass1
mentioned until you're instantiating it. Instead just do:
// calculate some values
MyClass myClass1 = new MyClass(arg1, arg2, ...);