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?
为什么Java的设计者认为不应该给局部变量一个默认值?认真地说,如果可以给实例变量一个默认值,那么为什么不能对局部变量做同样的处理呢?
And it also leads to problems as explained in 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.
当试图在finally块中关闭资源时,这个规则是最令人沮丧的。如果在try中实例化资源,但是在finally中尝试关闭它,就会得到这个错误。如果我将实例化移到try之外,就会得到另一个错误,说明它必须在try中。
Very frustrating.
非常令人沮丧。
13 个解决方案
#1
54
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.
局部变量的声明主要是为了做一些计算。因此,程序员决定设置变量的值,而不应该采用默认值。如果程序员错误地没有初始化一个局部变量,并且它取默认值,那么输出可能是一些意想不到的值。因此,对于局部变量,编译器会要求程序员在访问变量之前初始化一些值,以避免使用未定义的值。
#2
22
The "problem" you link to seems to be describing this situation:
你链接到的“问题”似乎描述了这种情况:
SomeObject so;
try {
// Do some work here ...
so = new SomeObject();
so.DoUsefulThings();
} finally {
so.CleanUp(); // Compiler error here
}
The commenter's complaint is that the compiler balks at the line in the finally
section, claiming that so
might be uninitialized. The comment then mentions another way of writing the code, probably something like this:
commenter的抱怨是,编译器在最后一节的行中不小心,声称这样可能没有初始化。评论接着提到了另一种编写代码的方式,可能是这样的:
// Do some work here ...
SomeObject so = new SomeObject();
try {
so.DoUsefulThings();
} finally {
so.CleanUp();
}
The commenter is unhappy with that solution because the compiler then says that the code "must be within a try." I guess that means some of the code may raise an exception that isn't handled anymore. I'm not sure. Neither version of my code handles any exceptions, so anything exception-related in the first version should work the same in the second.
评论者对这个解决方案不满意,因为编译器会说代码“必须在尝试中”。我想这意味着一些代码可能会引发一个不被处理的异常。我不确定。我的代码的两个版本都不处理任何异常,因此第一个版本中与异常相关的任何异常都应该在第二个版本中工作。
Anyway, this second version of code is the correct way to write it. In the first version, the compiler's error message was correct. The so
variable might be uninitialized. In particular, if the SomeObject
constructor fails, so
will not be initialized, and so it will be an error to attempt to call so.CleanUp
. Always enter the try
section after you have acquired the resource that the finally
section finalizes.
无论如何,这第二个版本的代码是正确的写法。在第一个版本中,编译器的错误消息是正确的。so变量可能没有初始化。特别是,如果SomeObject构造函数失败,则不会初始化,因此尝试调用so. cleanup将是错误的。在获得最后一节最终完成的资源之后,总是要进入try部分。
The try
-finally
block after the so
initialization is there only to protect the SomeObject
instance, to make sure it gets cleaned up no matter what else happens. If there are other things that need to run, but they aren't related to whether the SomeObject
instance was property allocated, then they should go in another try
-finally
block, probably one that wraps the one I've shown.
so初始化后的try-finally块仅用于保护SomeObject实例,以确保无论发生什么情况,它都得到清理。如果还有其他东西需要运行,但它们与是否分配了SomeObject实例无关,那么它们应该进入另一个try-finally块,可能是一个封装了我展示的那个的块。
Requiring variables to be assigned manually before use does not lead to real problems. It only leads to minor hassles, but your code will be better for it. You'll have variables with more limited scope, and try
-finally
blocks that don't try to protect too much.
在使用之前需要手动分配变量不会导致真正的问题。它只会引起小的麻烦,但是您的代码会更好。您将拥有具有更有限范围的变量,并尝试最终阻塞,而不会试图保护太多。
If local variables had default values, then so
in the first example would have been null
. That wouldn't really have solved anything. Instead of getting a compile-time error in the finally
block, you'd have a NullPointerException
lurking there that might hide whatever other exception could occur in the "Do some work here" section of the code. (Or do exceptions in finally
sections automatically chain to the previous exception? I don't remember. Even so, you'd have an extra exception in the way of the real one.)
如果局部变量具有默认值,那么在第一个例子中,它将是空的。这并不能解决任何问题。不是在finally块中获得编译时错误,而是存在一个NullPointerException,它可能隐藏代码的“Do some work here”部分中可能发生的任何其他异常。(还是最后部分中的异常会自动链接到前面的异常?我不记得了。即便如此,你也会有一个真正的例外。
#3
12
Moreover, in the example below, an exception may have been thrown inside the SomeObject construction, in which case the 'so' variable would be null and the call to CleanUp will throw a NullPointerException
此外,在下面的示例中,在SomeObject构造中可能抛出了一个异常,在这种情况下,“so”变量将为null,对CleanUp的调用将抛出一个NullPointerException
SomeObject so;
try {
// Do some work here ...
so = new SomeObject();
so.DoUsefulThings();
} finally {
so.CleanUp(); // Compiler error here
}
What I tend to do is this:
我倾向于这样做:
SomeObject so = null;
try {
// Do some work here ...
so = new SomeObject();
so.DoUsefulThings();
} finally {
if (so != null) {
so.CleanUp(); // safe
}
}
#4
10
Notice that the final instance/member variables don't get initialized by default. Because those are final and can't be changed in the program afterwards. That's the reason that Java doesn't give any default value for them and force the programmer to initialize it.
注意,默认情况下不会初始化最后的实例/成员变量。因为这些都是最终的,以后在程序中不能更改。这就是为什么Java没有为它们提供任何默认值并强制程序员初始化它。
On the other hand, non-final member variables can be changed later. Hence the compiler doesn't let them remain uninitialised, precisely, because those can be changed later. Regarding local variables, the scope of local variables is much narrower. Compiler knows when its getting used. Hence, forcing programmer to initialize the variable makes sense.
另一方面,可以稍后更改非最终成员变量。因此,编译器不会让它们保持未初始化,准确地说,因为稍后可以修改它们。对于局部变量,局部变量的范围要小得多。编译器知道它何时被使用。因此,强迫程序员初始化变量是有意义的。
#5
9
The actual answer to your question is because method variables are instantiated by simply adding a number to the stack pointer. To zero them would be an extra step. For class variables they are put into initialized memory on the heap.
您的问题的实际答案是,方法变量是通过向堆栈指针添加一个数字来实例化的。将它们归零将是额外的一步。对于类变量,它们被放在堆上的初始化内存中。
Why not take the extra step? Take a step back--Nobody mentioned that the "warning" in this case is a Very Good Thing.
为什么不采取额外的步骤呢?退一步说——没有人提到在这种情况下的“警告”是一件好事。
You should never initialize your variable to zero or null on the first pass (when you are first coding it). Either assign it to the actual value or don't assign it at all because if you don't then java can tell you when you really screw up. Take Electric Monk's answer as a great example. In the first case, it's actually amazingly useful that it's telling you that if the try() fails because SomeObject's constructor threw an exception, then you would end up with an NPE in the finally. If the constructor can't throw an exception, it shouldn't be in the try.
您不应该在第一次传递时将变量初始化为0或null(当您第一次编码时)。要么将它赋值给实际值,要么根本不赋值,因为如果不赋值,java就会告诉您什么时候真正出错。以电和尚的回答为例。在第一种情况下,它实际上非常有用,它告诉您,如果try()失败是因为某个对象的构造函数抛出了一个异常,那么您最终将得到一个NPE。如果构造函数不能抛出异常,则不应该抛出异常。
This warning is an awesome multi-path bad programmer checker that has saved me from doing stupid stuff since it checks every path and makes sure that if you used the variable in some path then you had to initialize it in every path that lead up to it. I now never explicitly initialize variables until I determine that it is the correct thing to do.
这个警告是一个非常棒的多路径糟糕的程序员检查器,它避免了我做一些愚蠢的事情,因为它检查了每条路径,并确保如果你在某个路径中使用这个变量,那么你必须在通向它的每条路径中初始化它。我现在从来没有显式地初始化变量,直到我确定它是正确的。
On top of that, isn't it better to explicitly say "int size=0" rather than "int size" and make the next programmer go figure out that you intend it to be zero?
最重要的是,明确地说“int size=0”而不是“int size”,让下一个程序员明白您想让它为0,不是更好吗?
On the flip side I can't come up with a single valid reason to have the compiler initialize all uninitialized variables to 0.
另一方面,我无法找到一个有效的理由让编译器将所有未初始化的变量初始化为0。
#6
4
(It may seem strange to post a new answer so long after the question, but a duplicate came up.)
(问了这么长时间后再发布一个新答案似乎有点奇怪,但出现了一个副本。)
For me, the reason comes down to this this: The purpose of local variables is different than the purpose of instance variables. Local variables are there to be used as part of a calculation; instance variables are there to contain state. If you use a local variable without assigning it a value, that's almost certainly a logic error.
对我来说,原因在于:局部变量的目的不同于实例变量的目的。局部变量将作为计算的一部分使用;实例变量包含状态。如果您使用一个局部变量而不给它赋值,那几乎肯定是一个逻辑错误。
That said, I could totally get behind requiring that instance variables were always explicitly initialized; the error would occur on any constructor where the result allows an uninitialized instance variable (e.g., not initialized at declaration and not in the constructor). But that's not the decision Gosling, et. al., took in the early 90's, so here we are. (And I'm not saying they made the wrong call.)
也就是说,我完全可以支持要求实例变量总是显式初始化;在任何构造函数中,如果结果允许一个未初始化的实例变量(例如,在声明时未初始化,在构造函数中未初始化),都会出现错误。但这并不是高斯林等人在90年代早期做出的决定,所以我们现在就在这里。(我不是说他们打错电话了。)
I could not get behind defaulting local variables, though. Yes, we shouldn't rely on compilers to double-check our logic, and one doesn't, but it's still handy when the compiler catches one out. :-)
但是,我无法理解默认的局部变量。是的,我们不应该依赖编译器来重复检查我们的逻辑,一个也不需要,但是当编译器捕获到一个时,仍然很方便。:-)
#7
3
I think the primary purpose was to maintain similarity with C/C++. However the compiler detects and warns you about using uninitialized variables which will reduce the problem to a minimal point. From a performance perspective, it's a little faster to let you declare uninitialized variables since the compiler will not have to write an assignment statement, even if you overwrite the value of the variable in the next statement.
我认为主要目的是保持与C/ c++的相似性。但是,编译器会检测并警告您不要使用未初始化的变量,这会将问题减少到最小程度。从性能的角度来看,让您声明未初始化的变量要快一些,因为编译器不必编写赋值语句,即使您在下一个语句中重写变量的值。
#8
2
It is more efficient not to initialize variables, and in the case of local variables it is safe to do so, because initialization can be tracked by the compiler.
更有效的方法是不初始化变量,在局部变量的情况下这样做是安全的,因为初始化可以由编译器跟踪。
In cases where you need a variable to be initialized you can always do it yourself, so it is not a problem.
在需要初始化变量的情况下,您可以自己进行初始化,所以这不是问题。
#9
0
Eclipse even gives you warnings of uninitialized variables, so it becomes quite obvious anyway. Personally I think it's a good thing that this is the default behaviour, otherwise your application may use unexpected values, and instead of the compiler throwing an error it won't do anything (but perhaps give a warning) and then you'll be scratching your head as to why certain things don't quite behave the way they should.
Eclipse甚至会对未初始化的变量发出警告,因此它变得非常明显。我个人认为这是一件好事,这是默认的行为,否则您的应用程序可能使用意想不到的价值,而不是编译器抛出错误,它不会做任何事情(但也许给予警告),然后你会挠你的头为什么某些事情不太表现他们应该的方式。
#10
0
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.
本地变量存储在堆栈中,但实例变量存储在堆中,因此有可能会读取堆栈上的前一个值,而不像堆中那样读取默认值。因此,jvm不允许在不初始化本地变量的情况下使用它。
#11
0
Instance variable will have default values but the local variables could not have default values. Since local variables basically are in methods/behavior, its main aim is to do some operations or calculations. Therefore, it is not a good idea to set default values for local variables. Otherwise, it is very hard and time-consuming to check the reasons of unexpected answers.
实例变量将具有默认值,但本地变量不能具有默认值。由于局部变量主要是方法/行为,其主要目的是做一些操作或计算。因此,为局部变量设置默认值不是一个好主意。否则,检查意外答案的原因是非常困难和耗时的。
#12
-1
The answer is instance variables can be initialized in class constructor or any class method, But in case of local variables, once you defined whatever in the method that remains forever in the class.
答案是实例变量可以在类构造函数或任何类方法中初始化,但是对于局部变量,一旦在方法中定义了类中永远存在的东西。
#13
-2
I could think of following 2 reasons
我可以考虑以下两个原因。
- 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.
- 正如大多数回答所说的,通过设置初始化局部变量的约束,可以确保局部变量按照程序员的要求被分配一个值,并确保计算出预期的结果。
- 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)
- 实例变量可以通过声明局部变量(相同的名称)来隐藏——为了确保预期的行为,局部变量被强制包含一个值。(不过会完全避免这种情况)
#1
54
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.
局部变量的声明主要是为了做一些计算。因此,程序员决定设置变量的值,而不应该采用默认值。如果程序员错误地没有初始化一个局部变量,并且它取默认值,那么输出可能是一些意想不到的值。因此,对于局部变量,编译器会要求程序员在访问变量之前初始化一些值,以避免使用未定义的值。
#2
22
The "problem" you link to seems to be describing this situation:
你链接到的“问题”似乎描述了这种情况:
SomeObject so;
try {
// Do some work here ...
so = new SomeObject();
so.DoUsefulThings();
} finally {
so.CleanUp(); // Compiler error here
}
The commenter's complaint is that the compiler balks at the line in the finally
section, claiming that so
might be uninitialized. The comment then mentions another way of writing the code, probably something like this:
commenter的抱怨是,编译器在最后一节的行中不小心,声称这样可能没有初始化。评论接着提到了另一种编写代码的方式,可能是这样的:
// Do some work here ...
SomeObject so = new SomeObject();
try {
so.DoUsefulThings();
} finally {
so.CleanUp();
}
The commenter is unhappy with that solution because the compiler then says that the code "must be within a try." I guess that means some of the code may raise an exception that isn't handled anymore. I'm not sure. Neither version of my code handles any exceptions, so anything exception-related in the first version should work the same in the second.
评论者对这个解决方案不满意,因为编译器会说代码“必须在尝试中”。我想这意味着一些代码可能会引发一个不被处理的异常。我不确定。我的代码的两个版本都不处理任何异常,因此第一个版本中与异常相关的任何异常都应该在第二个版本中工作。
Anyway, this second version of code is the correct way to write it. In the first version, the compiler's error message was correct. The so
variable might be uninitialized. In particular, if the SomeObject
constructor fails, so
will not be initialized, and so it will be an error to attempt to call so.CleanUp
. Always enter the try
section after you have acquired the resource that the finally
section finalizes.
无论如何,这第二个版本的代码是正确的写法。在第一个版本中,编译器的错误消息是正确的。so变量可能没有初始化。特别是,如果SomeObject构造函数失败,则不会初始化,因此尝试调用so. cleanup将是错误的。在获得最后一节最终完成的资源之后,总是要进入try部分。
The try
-finally
block after the so
initialization is there only to protect the SomeObject
instance, to make sure it gets cleaned up no matter what else happens. If there are other things that need to run, but they aren't related to whether the SomeObject
instance was property allocated, then they should go in another try
-finally
block, probably one that wraps the one I've shown.
so初始化后的try-finally块仅用于保护SomeObject实例,以确保无论发生什么情况,它都得到清理。如果还有其他东西需要运行,但它们与是否分配了SomeObject实例无关,那么它们应该进入另一个try-finally块,可能是一个封装了我展示的那个的块。
Requiring variables to be assigned manually before use does not lead to real problems. It only leads to minor hassles, but your code will be better for it. You'll have variables with more limited scope, and try
-finally
blocks that don't try to protect too much.
在使用之前需要手动分配变量不会导致真正的问题。它只会引起小的麻烦,但是您的代码会更好。您将拥有具有更有限范围的变量,并尝试最终阻塞,而不会试图保护太多。
If local variables had default values, then so
in the first example would have been null
. That wouldn't really have solved anything. Instead of getting a compile-time error in the finally
block, you'd have a NullPointerException
lurking there that might hide whatever other exception could occur in the "Do some work here" section of the code. (Or do exceptions in finally
sections automatically chain to the previous exception? I don't remember. Even so, you'd have an extra exception in the way of the real one.)
如果局部变量具有默认值,那么在第一个例子中,它将是空的。这并不能解决任何问题。不是在finally块中获得编译时错误,而是存在一个NullPointerException,它可能隐藏代码的“Do some work here”部分中可能发生的任何其他异常。(还是最后部分中的异常会自动链接到前面的异常?我不记得了。即便如此,你也会有一个真正的例外。
#3
12
Moreover, in the example below, an exception may have been thrown inside the SomeObject construction, in which case the 'so' variable would be null and the call to CleanUp will throw a NullPointerException
此外,在下面的示例中,在SomeObject构造中可能抛出了一个异常,在这种情况下,“so”变量将为null,对CleanUp的调用将抛出一个NullPointerException
SomeObject so;
try {
// Do some work here ...
so = new SomeObject();
so.DoUsefulThings();
} finally {
so.CleanUp(); // Compiler error here
}
What I tend to do is this:
我倾向于这样做:
SomeObject so = null;
try {
// Do some work here ...
so = new SomeObject();
so.DoUsefulThings();
} finally {
if (so != null) {
so.CleanUp(); // safe
}
}
#4
10
Notice that the final instance/member variables don't get initialized by default. Because those are final and can't be changed in the program afterwards. That's the reason that Java doesn't give any default value for them and force the programmer to initialize it.
注意,默认情况下不会初始化最后的实例/成员变量。因为这些都是最终的,以后在程序中不能更改。这就是为什么Java没有为它们提供任何默认值并强制程序员初始化它。
On the other hand, non-final member variables can be changed later. Hence the compiler doesn't let them remain uninitialised, precisely, because those can be changed later. Regarding local variables, the scope of local variables is much narrower. Compiler knows when its getting used. Hence, forcing programmer to initialize the variable makes sense.
另一方面,可以稍后更改非最终成员变量。因此,编译器不会让它们保持未初始化,准确地说,因为稍后可以修改它们。对于局部变量,局部变量的范围要小得多。编译器知道它何时被使用。因此,强迫程序员初始化变量是有意义的。
#5
9
The actual answer to your question is because method variables are instantiated by simply adding a number to the stack pointer. To zero them would be an extra step. For class variables they are put into initialized memory on the heap.
您的问题的实际答案是,方法变量是通过向堆栈指针添加一个数字来实例化的。将它们归零将是额外的一步。对于类变量,它们被放在堆上的初始化内存中。
Why not take the extra step? Take a step back--Nobody mentioned that the "warning" in this case is a Very Good Thing.
为什么不采取额外的步骤呢?退一步说——没有人提到在这种情况下的“警告”是一件好事。
You should never initialize your variable to zero or null on the first pass (when you are first coding it). Either assign it to the actual value or don't assign it at all because if you don't then java can tell you when you really screw up. Take Electric Monk's answer as a great example. In the first case, it's actually amazingly useful that it's telling you that if the try() fails because SomeObject's constructor threw an exception, then you would end up with an NPE in the finally. If the constructor can't throw an exception, it shouldn't be in the try.
您不应该在第一次传递时将变量初始化为0或null(当您第一次编码时)。要么将它赋值给实际值,要么根本不赋值,因为如果不赋值,java就会告诉您什么时候真正出错。以电和尚的回答为例。在第一种情况下,它实际上非常有用,它告诉您,如果try()失败是因为某个对象的构造函数抛出了一个异常,那么您最终将得到一个NPE。如果构造函数不能抛出异常,则不应该抛出异常。
This warning is an awesome multi-path bad programmer checker that has saved me from doing stupid stuff since it checks every path and makes sure that if you used the variable in some path then you had to initialize it in every path that lead up to it. I now never explicitly initialize variables until I determine that it is the correct thing to do.
这个警告是一个非常棒的多路径糟糕的程序员检查器,它避免了我做一些愚蠢的事情,因为它检查了每条路径,并确保如果你在某个路径中使用这个变量,那么你必须在通向它的每条路径中初始化它。我现在从来没有显式地初始化变量,直到我确定它是正确的。
On top of that, isn't it better to explicitly say "int size=0" rather than "int size" and make the next programmer go figure out that you intend it to be zero?
最重要的是,明确地说“int size=0”而不是“int size”,让下一个程序员明白您想让它为0,不是更好吗?
On the flip side I can't come up with a single valid reason to have the compiler initialize all uninitialized variables to 0.
另一方面,我无法找到一个有效的理由让编译器将所有未初始化的变量初始化为0。
#6
4
(It may seem strange to post a new answer so long after the question, but a duplicate came up.)
(问了这么长时间后再发布一个新答案似乎有点奇怪,但出现了一个副本。)
For me, the reason comes down to this this: The purpose of local variables is different than the purpose of instance variables. Local variables are there to be used as part of a calculation; instance variables are there to contain state. If you use a local variable without assigning it a value, that's almost certainly a logic error.
对我来说,原因在于:局部变量的目的不同于实例变量的目的。局部变量将作为计算的一部分使用;实例变量包含状态。如果您使用一个局部变量而不给它赋值,那几乎肯定是一个逻辑错误。
That said, I could totally get behind requiring that instance variables were always explicitly initialized; the error would occur on any constructor where the result allows an uninitialized instance variable (e.g., not initialized at declaration and not in the constructor). But that's not the decision Gosling, et. al., took in the early 90's, so here we are. (And I'm not saying they made the wrong call.)
也就是说,我完全可以支持要求实例变量总是显式初始化;在任何构造函数中,如果结果允许一个未初始化的实例变量(例如,在声明时未初始化,在构造函数中未初始化),都会出现错误。但这并不是高斯林等人在90年代早期做出的决定,所以我们现在就在这里。(我不是说他们打错电话了。)
I could not get behind defaulting local variables, though. Yes, we shouldn't rely on compilers to double-check our logic, and one doesn't, but it's still handy when the compiler catches one out. :-)
但是,我无法理解默认的局部变量。是的,我们不应该依赖编译器来重复检查我们的逻辑,一个也不需要,但是当编译器捕获到一个时,仍然很方便。:-)
#7
3
I think the primary purpose was to maintain similarity with C/C++. However the compiler detects and warns you about using uninitialized variables which will reduce the problem to a minimal point. From a performance perspective, it's a little faster to let you declare uninitialized variables since the compiler will not have to write an assignment statement, even if you overwrite the value of the variable in the next statement.
我认为主要目的是保持与C/ c++的相似性。但是,编译器会检测并警告您不要使用未初始化的变量,这会将问题减少到最小程度。从性能的角度来看,让您声明未初始化的变量要快一些,因为编译器不必编写赋值语句,即使您在下一个语句中重写变量的值。
#8
2
It is more efficient not to initialize variables, and in the case of local variables it is safe to do so, because initialization can be tracked by the compiler.
更有效的方法是不初始化变量,在局部变量的情况下这样做是安全的,因为初始化可以由编译器跟踪。
In cases where you need a variable to be initialized you can always do it yourself, so it is not a problem.
在需要初始化变量的情况下,您可以自己进行初始化,所以这不是问题。
#9
0
Eclipse even gives you warnings of uninitialized variables, so it becomes quite obvious anyway. Personally I think it's a good thing that this is the default behaviour, otherwise your application may use unexpected values, and instead of the compiler throwing an error it won't do anything (but perhaps give a warning) and then you'll be scratching your head as to why certain things don't quite behave the way they should.
Eclipse甚至会对未初始化的变量发出警告,因此它变得非常明显。我个人认为这是一件好事,这是默认的行为,否则您的应用程序可能使用意想不到的价值,而不是编译器抛出错误,它不会做任何事情(但也许给予警告),然后你会挠你的头为什么某些事情不太表现他们应该的方式。
#10
0
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.
本地变量存储在堆栈中,但实例变量存储在堆中,因此有可能会读取堆栈上的前一个值,而不像堆中那样读取默认值。因此,jvm不允许在不初始化本地变量的情况下使用它。
#11
0
Instance variable will have default values but the local variables could not have default values. Since local variables basically are in methods/behavior, its main aim is to do some operations or calculations. Therefore, it is not a good idea to set default values for local variables. Otherwise, it is very hard and time-consuming to check the reasons of unexpected answers.
实例变量将具有默认值,但本地变量不能具有默认值。由于局部变量主要是方法/行为,其主要目的是做一些操作或计算。因此,为局部变量设置默认值不是一个好主意。否则,检查意外答案的原因是非常困难和耗时的。
#12
-1
The answer is instance variables can be initialized in class constructor or any class method, But in case of local variables, once you defined whatever in the method that remains forever in the class.
答案是实例变量可以在类构造函数或任何类方法中初始化,但是对于局部变量,一旦在方法中定义了类中永远存在的东西。
#13
-2
I could think of following 2 reasons
我可以考虑以下两个原因。
- 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.
- 正如大多数回答所说的,通过设置初始化局部变量的约束,可以确保局部变量按照程序员的要求被分配一个值,并确保计算出预期的结果。
- 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)
- 实例变量可以通过声明局部变量(相同的名称)来隐藏——为了确保预期的行为,局部变量被强制包含一个值。(不过会完全避免这种情况)