0

I came across this very simple code, and it seems to me that we have to initialize a variable in the same scope we declare it, if so I am confused to as to why. Here is an example:

class Test
{
    public static void main (String[] args)
    {
        int x; // if initialize x to anything everything works fine

        for (int i = 0; i < 3; i++)
        {
            x = 3;
            System.out.println("in loop : " + x);
        }

        System.out.println("out of loop " + x); // expect x = 3 here, but get an error
    }
}

The above code produces this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The local variable x may not have been initialized

I am confused as to why this is happening. I expected int x to tell Java compiler that I will create a int variable x in the scope that declared x, then I initialized x to the value of 3 in the for loop. What causes the error? What am I missing?

As a side note, very similar code works as I expected in C++

#include<iostream>

using namespace::std;

int main()
{
    int x;

    for(int i = 0; i < 3; i++)
    {
        x = 3;
        cout<<"in loop : "<<x<<endl;
    }

    cout<<"out of loop : "<<x<<endl; //expect x = 3 here

    return 0;
}

I am using eclipse for java and Code::Blocks for C++.

Akavall
  • 82,592
  • 51
  • 207
  • 251

2 Answers2

4

The compiler doesn't know for sure you're going to enter the loop. So x may never get initialized.

Consider:

class Test
{
    public static void main (String[] args)
    {
        int x;                        // x has no value

        for (int i = 0; i < 0; i++)   // Bogus bounds -> never enters loop.
        {
            x = 3;                    // Never happens
            System.out.println("in loop : " + x);
        }

        System.out.println("out of loop " + x); // x has no value here!!
    }
}

Go ahead and initialize x to something. If you are certain the loop will be entered, and a value assigned, then don't worry what the initialization value is. Otherwise, you now see why that initialization is required.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
3

As per JLS 16 (Definite Assignment)

For every access of a local variable or blank final field x, x must be definitely assigned before the access, or a compile-time error occurs.

In this case compiler is not sure about for loop, which is why you seeing compile time error.

kosa
  • 65,990
  • 13
  • 130
  • 167