Why are local variables not initialized in Java?

后端 未结 15 929
不知归路
不知归路 2020-11-22 09:28

Was there any reason why the designers of Java felt that local variables should not be given a default value? Seriously, if instance variables can be given a default value,

15条回答
  •  遥遥无期
    2020-11-22 09:44

    The local variables are stored on a stack, but instance variables are stored on the heap, so there are some chances that a previous value on the stack will be read instead of a default value as happens in the heap. For that reason the jvm doesn't allow to use a local variable without initialize it.

提交回复
热议问题