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;
??
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.).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With