Do I have to initilize a variable in the same scope I declare it in Java?
<p>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:</p>

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

        for (int i = 0; i &lt; 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
    }
}
</code></pre>

<p>The above code produces this error:</p>

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

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

<p>As a side note, very similar code works as I expected in C++</p>

<pre><code>#include&lt;iostream&gt;

using namespace::std;

int main()
{
    int x;

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

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

    return 0;
}
</code></pre>

<p>I am using eclipse for java and Code::Blocks for C++.</p>
