Java: Error: variable might not have been initialized
Java doesn't analyze the logic of your if
blocks determine that one of your if
statements will run and assign a value to i
. It is simple and it sees the possibility of none of the if
statements running. In that case, no value is assigned to i
before it's used.
Java will not give a default value to a local variable, even if it gives default values to class variables and instance variables. Section 4.12.5 of the JLS covers this:
Every variable in a program must have a value before its value is used:
and
A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26)
Assign some kind of default value to i
, when you declare it, to satisfy the compiler.
int i = 0;
// Your if statements are here.
return number[i];