Flow analysis in javac - variable a may not have been initialized

In the following code, I would expect that for the initialization of variables a, bthe last block should not be there , but he does not like the compiler.

import java.util.Random;

public class Foo {

    private void foo () {

    double a,b;
    boolean c;

    double r = (new Random()).nextDouble();

    if(r < 0.25) {
        a = 1;
        b = 2;
        c = true;
    } else if(r >= 0.25 && r < 0.75) {
        a = 3;
        b = 3;
        c = true;
    } else {
        // why is it necessary to init a and b here?
        // given that c is set to false
        c = false;
    }

    if(c) {
        double k = a + b;
    }

  }

}

With the above code, the compiler complains.

bash-3.2$ javac Foo.java
Foo.java:25: variable a might not have been initialized
        double k = a + b;
                   ^
Foo.java:25: variable b might not have been initialized
        double k = a + b;
                       ^
2 errors

I would think that the compiler could do a static analysis to find out what kwould not be evaluated if the parameter is cset to false. So my question is, why does the compiler require me to initialize aand b?

+3
source share
1 answer

, , else c false, if, , . , , /

, , , else if , .

+7

All Articles