I'm learning Java and I'm getting this error. I know this has been asked a few (a lot of) times but none of the answers seems to answer my question. The body of the code is:
String[] number = {"too small", "one", "two", "three", "four", "too large"};
int i;
if(num<1){
i=0;
}
if(num==1){
i=1;
}
if(num==2){
i=2;
}
if(num==3){
i=3;
}
if(num==4){
i=4;
}
if(num>4){
i=5;
}
return number[i];
where the variable 'num' is declared, initialized and given previously. The error I get is: "Variable 'i' might not have been initialized" and pointing to the last line (return number[i];).
The thing is, if I declare 'i' and immediately assign a value (int i=0;) the code runs fine. But if I don't assign a value I get the error EVEN if a possible value is assigned after each 'if'.
I don't get this kind of error with C, for example.
Thanks
3 Answers 3
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];
8 Comments
else where it is more explicit and clear of intent (e.g. the correct solution could also be to return early or throw an exception).If you wanted to clean up the code, you could very easily do this:
String[] number = {"too small", "one", "two", "three", "four", "too large"};
int i = num;
if (i < 1) { i = 0; }
if (i > 4) { i = 5; }
return number[i];
Or if the value of num doesn't even matter:
String[] number = {"too small", "one", "two", "three", "four", "too large"};
if (num < 1) { num = 0; }
if (num > 4) { num = 5; }
return number[num];
Even if the code you had before seemed okay logically, the compiler can't always compete with human intelligence. Giving it that default value will help to satisfy the safety of your method.
Comments
Make the code in line 2 to:
int i = 0.00
As java needs a value beforehand when you create the variable. I hope it works fine after that:)
elseon all the branches, and (2) make the last one anelsewithout anotherif, i.e.else { ...instead ofelse if (num > 4) { .... I think that makes things clearer to a reader as well as avoiding the "definite assignment" problem. In this particular case, I'd just writeint i = (num < 1) ? 0 : (num > 4) ? 5 : num;.else:|