为什么局部变量没有在Java中初始化? [英] Why are local variables not initialized in Java?

查看:176
本文介绍了为什么局部变量没有在Java中初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java的设计者是否认为局部变量不应该被赋予默认值?说真的,如果实例变量可以给出一个默认值,那么为什么我们不能对局部变量做同样的事情呢?

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, then why can't we do the same for local variables?

它还会导致问题,如< a href =http://javahowto.blogspot.com/2007/01/variable-might-not-have-been.html?showComment=1206851400000#c1463508649088298714\"rel =noreferrer>此评论发表在博文中:


这个规则在尝试关闭finally块中的资源时最令人沮丧。如果我在try中实例化资源,但尝试在finally中关闭它,我会收到此错误。如果我在try之外移动实例化,我会收到另一个错误,指出它必须在try中。

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.

非常令人沮丧。


推荐答案

声明局部变量主要用于进行一些计算。因此程序员决定设置变量的值,它不应该采用默认值。如果程序员错误地没有初始化局部变量并且它采用默认值,那么输出可能是一些意外的值。因此,在局部变量的情况下,编译器会要求程序员在访问变量之前使用某个值进行初始化,以避免使用未定义的值。

Local variables are declared mostly to do some calculation. So its the programmer's decision to set the value of the variable and it should not take a default value. If the programmer, by mistake, did not initialize a local variable and it take default value, then the output could be some unexpected value. So in case of local variables, the compiler will ask the programmer to initialize with some value before they access the variable to avoid the usage of undefined values.

这篇关于为什么局部变量没有在Java中初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆