Difference between local variable initialize null and not initialize?

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

    No differences at all expect for one thing, if you don't initialize it and later on you try to use this variable (without changing the reference) means an error at compilation time, but if you initialize it and you use it later on (without changing the reference) means a NullPointerException.

    I show you with an example.

    Without initializing

    Integer y;
    y.intValue(); // Compilation error
    

    With initializing

    Integer x = null;
    x.intValue(); // You are able to compile it but NullPointerException
    

提交回复
热议问题