EDIT Never mind, solved. See solution at the bottom.
The below example is a test question that I need help understanding, and I know it is not standard practice to declare and initialize the for loop counter variable separately.
int j,k;
for(j=0; j<4; j )
{
for(k = 0; k < 10; k )
{
}
}
System.out.println(k);
This gives a Java compile error "k may not have been initialized", specifically called a definite assignment error. Java has a Oracle doc on this error 16-2: https://docs.oracle.com/javase/specs/jls/se8/html/jls-16.html
However, in those examples the assignment of variables are inside some conditional like an if or while loop.
if(true)
k = 0;
This would also give the same initialization compile error because Java is not 100% certain k will be assigned. However in my original code, the k for loop is not inside an if or while conditional. As written both loops should always run. In addition, if the k loop was written without it being nested it would compile normally.
The issue is clearly that the nesting of the k loop leads to an initialization error. However, my confusion lies in why there would be uncertainty by the compiler with the assignment of "k." What/why exactly about a nested for loop (not qualified by a conditional) would "hide" the assignment of k?
Thank you.
EDIT The outer for loop can also be thought of as an if statement. j is initialized, but it is not a guarantee that it will run its block of code, ie enter the inner k loop. For example if the conditional statement in the j loop was for(j = 0; j < 0; j ) then j will be initialized but it will not enter its block of code and therefore k will not be initialized. Hence, this possibility of uncertainty leads to a compiler error.
CodePudding user response:
You’re right that there’s on uncertainty: k is definitely going to be initialised. But in order to understand this, the compiler would have to actually understand (or alternatively evaluate) your code.
A compiler may be smart enough to do this for very simple constructs, but in general this is impossible, and the Java compiler isn’t smart enough to understand your particular code (the outer loop, to be precise).
To fix the compiler error, you can add an initialisation of k:
int j, k = 0;
CodePudding user response:
I think that it's possible, that k will not be initialized. JVM could check that second loop is empty and will never invoke it. I.e. you could will look like this:
for(j=0; j<4; j ) {}
I am not sure that I have described correct JVM behaviour, but I believe it makes sense.
Anyway, I think it's a good practice (from C ): define a variable and initialize it right there.
