Difference between local variable initialize null and not initialize?

前端 未结 6 1402
太阳男子
太阳男子 2020-12-10 15:09

In Java, what is the difference and best way to do?

Integer x = null; // x later assign some value.
Integer y; // y later initialize and use it.
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 15:40

    Local variables must be assigned to something before they are used.

    Integer x = null;
    myFunction(x);
    // myFunction is called with the argument null
    
    Integer y;
    myFunction(y);
    // This will not compile because the variable has not been initialised
    

    Class variables are always initialised to a default value (null for object types, something like zero for primitives) if you don't explicitly initialise them. Local variables are not implicitly initialised.

提交回复
热议问题