Why are local variables not initialized in Java?

后端 未结 15 1102
不知归路
不知归路 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:59

    I could think of following 2 reasons

    1. As most of the answers said by putting the constraint of initialising the local variable, it is ensured that the local variable gets assigned a value as programmer wants and ensures expected results are computed.
    2. Instance variables can be hidden by declaring local variables (same name) - to ensure expected behaviour, local variables are forced to be initailised a value. (Would totally avoid this though)

提交回复
热议问题