user3728000
user3728000

Reputation: 79

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

Upvotes: 6

Views: 29126

Answers (3)

Aarav
Aarav

Reputation: 11

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:)

Upvotes: -1

Rogue
Rogue

Reputation: 11483

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.

Upvotes: 0

rgettman
rgettman

Reputation: 178343

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

Upvotes: 12

Related Questions