Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does javac complain about not initialized variable?

For this Java code:

String var;
clazz.doSomething(var);

Why does the compiler report this error:

Variable 'var' might not have been initialized

I thought all variables or references were initialized to null. Why do you need to do:

String var = null;

??

like image 370
Marcus Leon Avatar asked Feb 02 '10 20:02

Marcus Leon


People also ask

What happens if a variable is not initialized in Java?

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.).

What happens if variable is not initialised?

If a variable is declared but not initialized or uninitialized and if those variables are trying to print, then, it will return 0 or some garbage value. Whenever we declare a variable, a location is allocated to that variable.


1 Answers

Instance and class variables are initialized to null (or 0), but local variables are not.

See §4.12.5 of the JLS for a very detailed explanation which says basically the same thing:

Every variable in a program must have a value before its value is used:

  • Each class variable, instance variable, or array component is initialized with a default value when it is created:
    • [snipped out list of all default values]
  • Each method parameter is initialized to the corresponding argument value provided by the invoker of the method.
  • Each constructor parameter is initialized to the corresponding argument value provided by a class instance creation expression or explicit constructor invocation.
  • An exception-handler parameter is initialized to the thrown object representing the exception.
  • 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 by the compiler using the rules for definite assignment.
like image 62
Michael Myers Avatar answered Oct 04 '22 21:10

Michael Myers