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?