Difference between local variable initialize null and not initialize?

前端 未结 6 1421
太阳男子
太阳男子 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:33

    Its better to not set it to null, otherwise you can by accident use it and cause NPE. Compiler wont help you with compile error. Only set to null if you want to have logic like if ( x != null ) { /use it/ }

提交回复
热议问题