Java 的设计者是否有任何理由认为局部变量不应该被赋予默认值?说真的,如果实例变量可以被赋予默认值,那么为什么我们不能对局部变量做同样的事情呢?
这也会导致问题,如 this comment to a blog post 中所述。 :
Well this rule is most frustrating when trying to close a resource in a finally block. If I instantiate the resource inside a try, but try to close it within the finally, I get this error. If I move the instantiation outside the try, I get another error stating that a it must be within a try.
Very frustrating.
最佳答案
声明局部变量主要是为了进行一些计算。因此,设置变量的值是程序员的决定,不应该采用默认值。
如果程序员错误地没有初始化局部变量并且它采用默认值,那么输出可能是一些意外的值。因此,对于局部变量,编译器会要求程序员在访问变量之前使用某个值对其进行初始化,以避免使用未定义的值。
关于java - 为什么Java中的局部变量没有初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59080942/