Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, why do certain variables need initialization at first and others only need declaration?

I'm trying to understand on a deeper level if I'm missing something as to understanding when Java needs an initialization of a variable vs a simply declaration. In the following code, the variable 'row' doesn't need to be assigned a value to compile and run, however, the variable 'column' does.

Note: This program does nothing of use - it's been trimmed to display only whats necessary for this question as to not waste peoples valuable time.

Here's the code snippet:

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 does row compile w/o initialization at the top, but Java thinks column "might not have been initialized."?

like image 441
Tony DiNitto Avatar asked May 30 '26 11:05

Tony DiNitto


1 Answers

The expression row = 0 (from outer loop) is guaranteed to be evaluated, therefore row variable will always be initialized before being used. The column variable would be initialized if, and only if, outer loop would iterate at least once. In other words the expresion column = 0 (from inner loop) is not guaranteed to be evaluated.

like image 181
Crozin Avatar answered Jun 02 '26 00:06

Crozin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!