In Java, why do some variables need initialization first and others only need a declaration?

I am trying to understand at a deeper level if I am missing something to understand when Java needs variable initialization vs simple declaration. In the following code, the variable 'row' does not need to be assigned a value to compile and run, however the variable 'column' does.

Note. This program has nothing to do - it was cropped to display only what is necessary for this question, so as not to waste peoples' precious time.

Here's a piece of code:

int row;      //row doesn't need initialization
int column=0; //column does need initialization
for (row=0; row<2; row++){
    for (column=0; column<2; column++){
    }
}
System.out.print("Col:" + column + " row:" + row);

      

Why row

does it compile without initializing at the top, but Java thinks column

"may not have been initialized."?

+3


source to share


3 answers


The expression row = 0

(from the outer loop) is guaranteed to be evaluated, so the variable row

will always be initialized before being used. The variable column

will be initialized if and only if the outer loop will loop at least once. In other words, the expression column = 0

(from the inner loop) is not guaranteed .



+5


source


Before using variables row

and column

in System.out.println

, they must be initialized. row

is initialized in the outer loop, so that's fine, but the column is initialized in the inner loop, and the compiler makes no assumptions that it will ever execute (although it will in practice).



+4


source


Java compiler can't follow your code. It sees that it is being column

initialized inside the body of the outer loop for

, but it cannot be sure that this code will ever run. Therefore, it cannot be sure that your variable will always be initialized before it is print

called.

On the other hand, it knows that the outer loop initialization statement is for

guaranteed to work no matter what. Therefore, it can guarantee that it row

will be initialized.

+2


source







All Articles