Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Error: variable might not have been initialized

Tags:

java

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

like image 200
user3728000 Avatar asked Jun 10 '14 23:06

user3728000


People also ask

What does it mean if a variable has not been initialized in Java?

Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

How do you initialize a variable in Java?

The syntax for an initializer is the type, followed by the variable name, followed by an equal sign, followed by an expression. That expression can be anything, provided it has the same type as the variable. In this case, the expression is 10, which is an int literal.


1 Answers

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];
like image 99
rgettman Avatar answered Nov 15 '22 11:11

rgettman