Note: I am well aware that initializing it fixes the problem; I just assumed the compiler would follow the execution path and see that foo would actually be initialized at the point where it suggests it 'may' not be.
My initial assumption would be that if the length was never over 3, I would never need to allocate memory for it to be used.
This will never be used in production, I am simply curious
See the following example: -
List<String> foo;
int length = 5;
if (length > 3)
{
foo = new ArrayList<String>();
}
if (length > 4)
{
foo.add("bar");
}
Why is this causing the following to be displayed?
The local variable foo may not have been initialized
Surely following the branches, there is never a case whereby foo is not initialized. I know that if I were to do: -
List<String> foo = null;
there would be no compilation problems, but why do I need to do this?
Local variables needs to be initialized before using it anywhere else because it will not be initialized by default .What if the if()
is not true
?
if (length > 3)
{
foo = new ArrayList<String>();
}
The compiler can't tell if the condition will be true.
A local variable (§14.4, §14.13) 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 by the compiler using the rules for definite assignment
As @jlordo pointed out making the length
as final
will resolve the compilation error , because at the compile time itself the compiler knows that the value of length
will always be 5
and hence the condition length>3
is always true
so the local variable will be initialized.
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