7

In Java, why do class variables get initialized to a default value? But local variables are not.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 2
    To prevent you from making mistakes. – SLaks Aug 18 '13 at 15:15
  • To be explicit -- local variables are *always* given an explicit value before they're used. There is no need for a default value. – Andy Thomas Aug 18 '13 at 15:17
  • Check this [question](http://stackoverflow.com/questions/415687/why-are-local-variables-not-initialized-in-java) – Pr0gr4mm3r Aug 18 '13 at 15:21
  • @AndyThomas You could make the same argument for instance variables, the "need" (or lack thereof) id arguably the same. – Dave Newton Aug 18 '13 at 15:57
  • @DaveNewton - Except that the definite assignment constraint is not applied to non-final instance variables. – Andy Thomas Aug 19 '13 at 02:25
  • @AndyThomas Yes, but that doesn't provide reasoning, or change that the same arguments can be applied to surge instance or class variables. – Dave Newton Aug 19 '13 at 11:38
  • @DaveNewton - That would be true if you *could* apply the definite assignment constraint to non-final instance variables. However, I question whether that's feasible. – Andy Thomas Aug 19 '13 at 13:18
  • Possible duplicate of http://stackoverflow.com/questions/415687/why-are-local-variables-not-initialized-in-java – Raedwald Mar 11 '14 at 13:08
  • Better duplicate: *[Why are local variables not initialized in Java?](https://stackoverflow.com/questions/415687)* – Peter Mortensen Jan 07 '21 at 17:50

1 Answers1

-2

The local variables are not initialized to default values, as in the case of class variables. The same applies to primitives and object references.

JavaDoc (Section 4.12.5. Initial Values of Variables):

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126