Why are local variables not initialized in Java?

Shivasubramanian A picture Shivasubramanian A · Jan 6, 2009 · Viewed 68.9k times · Source

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?

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.

Very frustrating.

Answer

Warrior picture Warrior · Jan 6, 2009

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.