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++.