34

What is difference between :

  • Object o = null; and
  • Object o; (just declaration)

Can anyone please answer me?

Salah Eddine Taouririt
  • 24,925
  • 20
  • 60
  • 96
김준호
  • 15,997
  • 9
  • 44
  • 38

2 Answers2

45

It depends on the scope where you declare the variable. For instance, local variables don't have default values in which case you will have to assign null manually, where as in case of instance variables assigning null is redundant since instance variables get default values.

public class Test {
    Object propertyObj1;
    Object propertyObj2 = null; // assigning null is redundant here as instance vars get default values 

    public void method() {
        Object localVariableObj1;
        localVariableObj1.getClass(); // illegal, a compiler error comes up as local vars don't get default values

        Object localVariableObj2 = null;
        localVariableObj2.getClass(); // no compiler error as localVariableObj2 has been set to null

        propertyObj1.getClass(); // no compiler error
        propertyObj2.getClass(); // no compiler error
    }
}
Ben Blank
  • 54,908
  • 28
  • 127
  • 156
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • 1
    could u pls fix the code tho? `Object localVariableObj1.getClass();` is invalid.. Same with `Object localVariableObj2.getClass();` – Tommy Schmidt Apr 09 '18 at 18:39
3

As mentioned, object reference as instance variable need not be assigned null as those take null as default value. But local variables must be initialized otherwise you will get compilation error saying The local variable s may not have been initialized.

For more details you can refer this link

Madhusudan Joshi
  • 4,438
  • 3
  • 26
  • 42