Why does the Java compiler complain about a local variable not initialized here?

int a = 1, b;
if(a > 0) b = 1;
if(a <= 0) b = 2;
System.out.println(b);

If I run this, I get:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 The local variable b may not have been initialized

 at Broom.main (Broom.java:9)

I know that local variables are not initialized, and it is your responsibility to do this, but in this case the first, if it does not initialize the variable?

+3
source share
7 answers

If you change the second ifto else, then the compiler will be happy.

int a = 1, b;
if(a > 0) b = 1;
else b = 2;
System.out.println(b);

, Java , :

:

void flow(boolean flag) {
        int k;
        if (flag)
                k = 3;
        if (!flag)
                k = 4;
        System.out.println(k);  // k is not "definitely assigned" before here
}

.

( ) , , , .

+14

"IF", ​​ , .

+5

, , .

, IDE "", . , , ​​ , .

- , /IDE, , .

.

+3

Java .

, , - . .

Java docs:

(§14.4, §14.13) (§14.4) (§15.26) , ,

+2

, , IF .

, final, .

+1

The Java compiler cannot detect that the other ifworks as else. Compilers are smart, but not so smart.

+1
source

You can add a keyword finalto your ad ato help your compiler optimize your code.

// this compiles just fine
final int a = 1, b;
if(a > 0) b = 1;
if(a <= 0) b = 2;
System.out.println(b);
0
source

Source: https://habr.com/ru/post/1735012/


All Articles