This is pretty well explained by the Java Language Specification (in particular, §4.12.5):
Each variable in the program must have a value before its value:
- Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
- For all reference types (§4.3), the default value is null.
- A local variable (§14.4, §14.14) must be explicitly set before using it by initialization (§14.4) or assignment (§15.26), in a way that can be verified using rules for a specific purpose (§16).
To expand the bit, §16 goes into the rules for a specific purpose , which is the reason for this:
Each local variable (§14.4) and each empty final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access to its value occurs.
For each access to a local variable or an empty final field x, it is imperative to assign compile-time errors before accessing or occur.
Simply put: Java will assign default values to class / instance variables, but will not assign default values to a local variable. Local variables must be definitely assigned this way (either by initialization or assignment), or a compilation error will occur (as you noticed).
If you think about it from a different angle, when you initialize a class containing certain fields, you may not want to initialize the value first (think JavaBeans ). If you are in a code block and you declare a variable, then instead it is expected that the developer will control this object life cycle right there, in the block.
It does not make sense to simply declare a variable and try to do something with it without assigning a value to it, since the variable does not matter.
source share