简体   繁体   中英

Java: Error: variable might not have been initialized

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

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];

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM