Difference between local variable initialize null and not initialize?

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

    No difference at all. Both cases when ever you want to use it, local variable must be in initialized form(must have a value).

    From Java doc

    Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

提交回复
热议问题