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?
It's a good practice to initialize the local variables inside the method block before using it. Here is a mistake that a beginner may commit.
You may expect the console will show '5' but instead the compiler will throw 'variable a might not be initialized' error. Though one may think variable a is 'initialized' inside the for loop, the compiler does not think in that way. What if
arr.length
is 0? The for loop will not be run at all. Hence, the compiler will givevariable a might not have been initialized
to point out the potential danger and require you to initialize the variable.To prevent this kind of error, just initialize the variable when you declare it.
You haven't initialised
a
andb
, only declared them. There is a subtle difference.At least this is for C++, I presume Java is the same concept.
You declared them but did not provide them with an intial value - thus, they're unintialized. Try something like:
and the warnings should go away.
You declared them, but not initialized.
Imagine what happens if x[l] is neither 0 nor 1 in the loop. In that case a and b will never be assigned to and have an undefined value. You must initialize them both with some value, for example 0.