Amby
Amby

Reputation: 462

I initialize local variable, but I still get "variable might not have been initialized"

In:

int i = 10;
int j;
    
if(i == 10) {
    j = 100;
}

System.out.println(j);//error

I get an error:

variable might not have been initialized

The compiler is not smart enough to determine the value of j even though in the above line it's been explicitly defined, as int i = 10;.

I think, i is not given value during compile time, and that's why I get this initialization error.

Does int i get 10 as its value during run-time?

Upvotes: 1

Views: 148

Answers (3)

tylucaskelley
tylucaskelley

Reputation: 131

You have to initialize j before executing the if-statement. All local variables must be defined and initialized.

In your program, because the compiler does not recognize the value of i, i == 10 is meaningless and gives an error.

Upvotes: 1

TieDad
TieDad

Reputation: 9889

Because i is local variable, int i=10 is executed at runtime, so at compile time, compiler doesn't know that's value of i, so that the compiler cannot determine if (i==10) must be true, it can only assume the both condition. If i doesn't equal to 10, then println will use uninitialized j, that's reason why you get the error.

Upvotes: 2

user3103939
user3103939

Reputation: 41

Try to remove the curly braces in your if statement.

Upvotes: -1

Related Questions