Reputation: 462
In:
int i = 10;
int j;
if(i == 10) {
j = 100;
}
System.out.println(j);//error
I get an error:
variable might not have been initialized
The compiler is not smart enough to determine the value of j
even though in the above line it's been explicitly defined, as int i = 10;
.
I think, i
is not given value during compile time, and that's why I get this initialization error.
Does int i
get 10
as its value during run-time?
Upvotes: 1
Views: 148
Reputation: 131
You have to initialize j before executing the if-statement. All local variables must be defined and initialized.
In your program, because the compiler does not recognize the value of i, i == 10 is meaningless and gives an error.
Upvotes: 1
Reputation: 9889
Because i
is local variable, int i=10
is executed at runtime, so at compile time, compiler doesn't know that's value of i
, so that the compiler cannot determine if (i==10)
must be true, it can only assume the both condition. If i
doesn't equal to 10, then println
will use uninitialized j
, that's reason why you get the error.
Upvotes: 2