Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: "Local variable may not have been initialized" 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++;
}

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.

like image 452
Ivan Avatar asked Sep 30 '12 12:09

Ivan


3 Answers

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.

like image 185
Keppil Avatar answered Sep 20 '22 19:09

Keppil


There is one :

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

The compiler isn't responsible for devising and testing the algorithm. You are.

But maybe you should propose a more practical use case. Your example doesn't really show what's your goal.

like image 45
Denys Séguret Avatar answered Sep 20 '22 19:09

Denys Séguret


Why don't you simply use

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
    }
}

In the code why do you want to use x outside the first if block, all the logic involving x can be implemented in the first if block only, i don't see a case where you would need to use the other if block to use x.

EDIT: or You can also use:

void a ()
{
    int x;
    boolean b = (Math.random() < 0.5);
    if (b) {
         x=1
        //do something 
    }
}
like image 20
Ankur Avatar answered Sep 19 '22 19:09

Ankur