Default values of instance variables and local variables

后端 未结 2 640
轻奢々
轻奢々 2020-12-31 05:13

I read that Java provides default values to class properties but not to local variables. Is that correct? If so what is the reason behind this? When you are doing something

相关标签:
2条回答
  • 2020-12-31 05:47

    The non-technical reason behind may also be the following one:

    If you declare a local variable you do this in order to use it. And usage is connected with assigning a value. Therefore, accessing a declared but not initialized variable makes not that much sense - the programmer might simply have forgotten to initialize the variable.

    Fields, however, might only be used untill or after a specified point in the object's lifetime. Forcing the programmer to initialize them all would not be good.

    0 讨论(0)
  • 2020-12-31 06:01

    Standard local variables are stored on the stack and aren't actually created until they are initialized. If a local variable isn't used, it doesn't go on the stack. Member variables, however, are allocated in the heap, and thusly have a default placeholder (null reference or default primitive).

    0 讨论(0)
提交回复
热议问题