为什么必须在 Java 中初始化局部变量,包括原语?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1560685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why must local variables, including primitives, always be initialized in Java?
提问by Gourav
Why must local variables, including primitives, always be initialized in Java? Why is the same not applicable in the case of instance variables?
为什么必须在 Java 中初始化局部变量,包括原语?为什么同样不适用于实例变量?
采纳答案by Jon Skeet
Basically, requiring a variable to be assigned a value before you read it is a Good Thing. It means you won't accidentally read something you didn't intend to. Yes, variables could have default values - but isn't it better for the compiler to be able to catch your bug instead, if it can prove that you're trying to read something which might not have been assigned yet? If you want to give a local variable a default value, you can always assign that explicitly.
基本上,在您读取变量之前要求为其分配一个值是一件好事。这意味着您不会意外阅读您不打算阅读的内容。是的,变量可以有默认值——但是如果编译器能够证明您正在尝试读取可能尚未分配的内容,那么编译器能够捕获您的错误不是更好吗?如果你想给一个局部变量一个默认值,你总是可以显式分配它。
Now that's fine for local variables - but for instance and static variables, the compiler has no way of knowing the order in which methods will be called. Will a property "setter" be called before the "getter"? It has no way of knowing, so it has no way of alerting you to the danger. That's why default values areused for instance/static variables - at least then you'll get a known value (0, false, null etc) instead of just "whatever happened to be in memory at the time." (It also removes the potential security issue of reading sensitive data which hadn't been explicitly wiped.)
现在这对局部变量很好 - 但是对于实例变量和静态变量,编译器无法知道调用方法的顺序。会在“getter”之前调用属性“setter”吗?它无法知道,因此无法提醒您注意危险。为什么缺省值的被用于实例/静态变量-至少,你会得到一个已知值(0,假,空等),而不是“不管发生什么事情是在内存中的时间。” (它还消除了读取未明确擦除的敏感数据的潜在安全问题。)
There was a question about this very recently for C#... - read the answers there as well, as it's basically the same thing. You might also find Eric Lippert's recent blog postinteresting; it's at least around the same area, even though it has a somewhat different thrust.
最近有一个关于 C# 的问题...... - 阅读那里的答案,因为它基本上是一样的。您可能还会发现Eric Lippert 最近的博文很有趣;它至少在同一区域附近,尽管它的推力有些不同。
回答by monksy
Local variables and primitives should be initialized before use because you would know what to expect from the values. Historically, when a new variable was created it would contain random values from the memory [and one could not predict the value]. Java also requires this because it prevents the presence of orphaned variables.
局部变量和原语应该在使用前初始化,因为你会知道从这些值中得到什么。从历史上看,当创建一个新变量时,它会包含内存中的随机值[并且无法预测该值]。Java 也要求这样做,因为它可以防止孤立变量的存在。
回答by James Cronen
In practice all variables need to be initialized before using them.
在实践中,所有变量都需要在使用之前进行初始化。
I can't think of a time you'd want to use a variable before setting its value (unless you're comparing it against null).
我想不出有什么时候您想在设置变量值之前使用它(除非您将它与 null 进行比较)。
回答by quosoo
Well, in case of local variable it's clear what it means 'before' since the program flow between declaration (in method) and reference is sequential. In case of fields declared outside of the method compiler never knows which code is going to be used when so it cannot generate an error as possibly some other method is going to initialize the field before it is used.
好吧,在局部变量的情况下,“之前”的含义很清楚,因为声明(在方法中)和引用之间的程序流程是顺序的。对于在方法之外声明的字段,编译器永远不知道将在何时使用哪个代码,因此它不会产生错误,因为可能有其他方法将在使用该字段之前对其进行初始化。
回答by Steve Kuo
Not totally true. Local variables only need to be initialized if being reference. A local variable can be left uninitialized if never referenced. For example:
不完全正确。局部变量只有在被引用时才需要初始化。如果从未引用过局部变量,则可以保持未初始化状态。例如:
int x; // Valid
int y;
println("y=" + y); // Not valid since y's value has never been assigned
回答by Sven
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables don't have a default value. Unless a local variable has been assigned a value, the compiler will refuse to compile the code that reads it. IMHO, this leads to the conclusion, that initializing a local variable with some default value (like null, which might lead to a NullPointerException later) when it is declared is actually a bad thing. Consider the following example:
在 Java 中,如果类和实例变量未手动初始化,则它们采用默认值(null、0、false)。但是,局部变量没有默认值。除非为局部变量赋值,否则编译器将拒绝编译读取它的代码。恕我直言,这导致了一个结论,即在声明局部变量时使用一些默认值(如 null,这可能会导致 NullPointerException)初始化它实际上是一件坏事。考虑以下示例:
Object o;
if (<some boolean condition>)
o = <some value>;
else
o = <some other value>;
System.out.println(o);
An initialization of o
with null is completely unnecessary, since the Java compiler checks at compile time, that any code-path initializes o
(with either null or some non-null value) before the variable is read. That means, that the compiler will refuse to compile the line System.out.println(o);
if you would comment out any of the two initializations of the variable o
in the code snippet above.
o
with null的初始化是完全没有必要的,因为 Java 编译器在编译时检查任何代码路径o
在读取变量之前初始化(使用 null 或某些非 null 值)。这意味着,System.out.println(o);
如果您o
在上面的代码片段中注释掉变量的两个初始化中的任何一个,编译器将拒绝编译该行。
This holds for Java, and maybe for Java only. I don't know about language like C#. In good old C (and maybe C++) however, it is still recommended to always initialize variables when declaring them, AFAIK. Such "old-school" programming languages might be the reason, that the recommendation to always initialize variables pops up in books and discussions about modern languages like Java, where the compiler keeps track of whether a variable has been initialized or not.
这适用于 Java,也许只适用于 Java。我不知道像 C# 这样的语言。但是,在旧的 C(也许是 C++)中,仍然建议在声明变量时始终初始化变量,AFAIK。这种“老派”编程语言可能是这样的原因,在有关 Java 等现代语言的书籍和讨论中,总是出现建议始终初始化变量的原因,在这些语言中,编译器会跟踪变量是否已初始化。
回答by Shashank Bodkhe
It is necessary to initialize local variables (only when we use them) because they don't get any default value like instance variables.
有必要初始化局部变量(仅在我们使用它们时),因为它们不会像实例变量那样获得任何默认值。
And as basic rule, we should always initialize any variable before using it. Otherwise it may result in an error like nullPointer, etc
作为基本规则,我们应该始终在使用任何变量之前对其进行初始化。否则可能会导致 nullPointer 等错误
Now, why don't local variables get default value? The reason is that local variables reside on stack and is visible only in local method context, unlike instance variables which resides on heap and has scope throughout the program.
现在,为什么局部变量没有获得默认值?原因是局部变量驻留在堆栈上并且仅在本地方法上下文中可见,这与驻留在堆上并在整个程序中具有作用域的实例变量不同。
So when the stack will end local method's value will also get destroyed therefore: 1] They are supposed to be initialized explicitly (when we use them) 2] They should not be initialized implicitly (by null,0 or false) like instance variables
因此,当堆栈结束时,本地方法的值也将被销毁:1] 它们应该被显式初始化(当我们使用它们时)2] 它们不应该像实例变量一样隐式初始化(通过 null,0 或 false)
回答by udoh unyime
Going by the definition of local variable which state, a local variable is declared within a function or is passed as an argument in a function. If you do not initialized a local variable you will encounter exception handling problem because, the compiler will not be able to understand what value the variable holds
根据局部变量的定义,局部变量在函数内声明或作为参数在函数中传递。如果你没有初始化一个局部变量,你会遇到异常处理问题,因为编译器将无法理解变量持有什么值