Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are local variables not initialized in 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?

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.

like image 901
Shivasubramanian A Avatar asked Jan 06 '09 07:01

Shivasubramanian A


People also ask

Should local variables be initialized in Java?

Local variables must be initialized before use, as they don't have a default value and the compiler won't let us use an uninitialized value.

Why is my variable not initialized?

Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value. If the variable has been declared but not initialized, we can use an assignment statement to assign it a value.

Why does Java compiler forces you to initialize local variables before using them but not for member variables?

It is necessary to initialize local variables (only when we use them) because they don't get any default value like instance variables.


1 Answers

Local variables are declared mostly to do some calculation. So it's 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 takes a default value, then the output could be some unexpected value. So in case of local variables, the compiler will ask the programmer to initialize it with some value before they access the variable to avoid the usage of undefined values.

like image 164
Warrior Avatar answered Oct 05 '22 13:10

Warrior