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

java

Solution

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.

Problem

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?

Original source

Related problems