David David - 5 months ago 57
Java Question

Variable might not have been initialized error

When i try to compile this:

public static Rand searchCount (int[] x)
{
int a ;
int b ;

...

for (int l= 0; l<x.length; l++)
{
if (x[l] == 0)
a++ ;
else if (x[l] == 1)
b++ ;
}

...

}


I get these errors:

Rand.java:72: variable a might not have been initialized
a++ ;
^
Rand.java:74: variable b might not have been initialized
b++ ;
^
2 errors


it seems to me that i initialized them at the top of the method. Whats going wrong?

Answer

You declared them, but you didn't initialize them. Initializing them is setting them equal to a value:

int a;        // This is a declaration
a = 0;        // This is an initialization
int b = 1;    // This is a declaration and initialization

You get the error because you haven't initialized the variables, but you increment them (e.g., a++) in the for loop.

Comments