Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the design rational for "variable may not have been initialized"? [duplicate]

Tags:

java

It is a well know fact that in Java one needs to initialize a local variable before using it (cf. JLS)

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16).

Otherwise one gets a compiler error:

The local variable result may not have been initialized.

What is the rational for this design decision? Why does the compiler not automatically convert a declaration (e.g. int x, double y, String foo, etc.) to a definition initialized with some default value (0, 0.0, null)? Are there any drawbacks of doing so?

like image 227
Micha Wiedenmann Avatar asked Nov 29 '13 10:11

Micha Wiedenmann


People also ask

What happens if you use a variable that has not been initialized?

Should we declare a local variable without an initial value, we get an error. This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.).

Why variable might not have been initialized?

This is because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. If the compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error.

What type of error is variable not initialized?

In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.


1 Answers

The drawback is that the default value may not be what you want - you may have just forgotten to initialise your local variable, and using a default value could then cause an exception (or worse, just run anyway creating some hard to track down bug.)

Forcing a compiler error in this case makes sure you correct the problem and explicitly assign it to whatever you want it to be.

The same argument could be applied to fields, but it's much harder (and technically impossible in every case) to check that they're assigned a value before that value is read, since they could be accessed or written to from anywhere. Ergo, using defaults in this case rather than enforcing this rule is the only sensible approach.

like image 123
Michael Berry Avatar answered Sep 25 '22 23:09

Michael Berry