3

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."?

1
  • 1
    As Crozin mentions below, both vars need initialization. You just happen to be initializing row at line 3, but potentially never (according to the compiler) initializing column if you don't do it at line 2. Commented Apr 9, 2012 at 2:26

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

Before both The row and column variables are used in the System.out.println, they need to be initialized,. row is initialized in the outer loop so it is fine, but column is initialized in the inner loop and the compiler makes no assumption that this will ever run (even though it will in practice).

Comments

2

The Java compiler can't follow your code. It sees that column gets initialized inside the body of the outer for loop, but has no way of being sure that that code will ever run. So it can't be sure that your variable will always be initialized before it's accessed in the call to print.

On the other hand, it knows that the initialization statement of the outer for loop is guaranteed to run no matter what. So it can guarantee that row will be initialized.

3 Comments

This seems backwards. The compiler can follow your code, and it can see that under certain conditions column will not be initialized.
In this particular example, column will always be initialized. What I was trying to say is that the compiler doesn't know that.
I understand what you mean now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.