Java: "The local variable may not have been initialized" is not intelligent enough?

Consider the following method:

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

In x++I get the error "The local variable may not have been initialized." Clearly, x will never be used without initialization. Is there any way to suppress a warning except initializing x? Thank.

+5
source share
3 answers

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

No, you have to initialize your variable to get rid of this.

+5

:

void a () {
    if (Math.random() < 0.5) {
        int x = 1;
    }
}

. .

, , . , .

+2

void a ()
{
    int x;
    boolean b = false;
    if (Math.random() < 0.5)
    {
        x = 0;
        b = true;
        x++;
    }
    if (b) {
        //do something else which does not use x
    }
}

, x if, x if, , , x.

EDIT: :

void a ()
{
    int x;
    boolean b = (Math.random() < 0.5);
    if (b) {
         x=1
        //do something 
    }
}
+1

All Articles