简体   繁体   中英

Java uninitialized variable error

In the code below, the Java compiler gives me an error in the line calling hasAdditionalLiberty , saying that x0 and y0 "may have not been initialized". I do understand the intent of making this an error, but isn't that in this case, x0 and y0 must be initialized because they always go through the for loop?

So what exactly is the rule deciding the uninitialized variable error?

int x0;
int y0;
for (int i = 0; i < 4; ++i) {
    x0 = x + deltaX[i];
    y0 = y + deltaY[i];
    if (isOnBoard(x0, y0) && at(x0, y0) == Color.Empty) {
        break;
    }
}
if (!hasAdditionalLiberty(x, y, x0, y0)) {
    koX = x0;
    koY = y0;
}

Well, the compiler does not know everything about the values of your variables through the program flow.

Then, the compiler does not know if the program will enter the loop at least one time, so in which case x0 and y0 will not have been initialised.

If you have a loop with condition that depends of a variable: who does it know before the runTime if you will enter the loop?

In that case you will have an unexpected error in

if (!hasAdditionalLiberty(x, y, x0, y0)) {
    koX = x0;
    koY = y0;
}

You only have to itialize then with

int x0 = -1;
int y0 = -1;

or

int x0 = 0;
int y0 = 0;

for example.

Yes, I know that in your case you have a "static" loop because of the condition is < 4 , soy may if someone develops a different compiler to recognize this, you won't have that error.

For further information about when you get this type of error, read this .

The loop isn't guaranteed (in the compiler's opinion) to have made one iteration (since the compiler doesn't do sufficient analysis of the for loop expressions).

Refer to JLS, Chapter 16 for the rule deciding the uninitialized variable error:

The analysis takes into account the structure of statements and expressions […, however] values of expressions are not taken into account in the flow analysis. (My emphasis.)

The compiler isn't smart enough to know for sure that the code will enter the loop. Even if you can tell that the code will enter the loop, the code can't. That's not what a compiler is for.

Consider this code:

public static void main(String... args){
   int x;
   if(Math.random() < .5){
      x = 100;
   }
   System.out.println(x);
}

This code will generate the same compiler error, for the same exact reason.

The compiler doesn't know if your for loop will definitely run or not. To prevent the warning, just initialize your variables.

int x0 = 0;
int y0 = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM