Java, What is the difference between assigning null to object and just declaration

后端 未结 2 1147
独厮守ぢ
独厮守ぢ 2020-12-03 02:48

What is difference between :

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

Can anyone please answer me?

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 03:22

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

提交回复
热议问题