Java: “Local variable may not have been initialized” not intelligent enough?

Tags: , , , ,



Consider the following method:

void a ()
{
    int x;
    boolean b = false;
    if (Math.random() < 0.5)
    {
        x = 0;
        b = true;
    }
    if (b)
        x++;
}

On x++ I get the “Local variable may not have been initialized” error. Clearly x will never be used uninitialized. Is there any way to suppress the warning except by initializing x? Thanks.

Answer

No, there is no way Java can examine all possible code paths for a program to determine if a variable has been initialized or not, so it takes the safe route and warns you.

So no, you will have to initialize your variable to get rid of this.



Source: stackoverflow