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?
You declared them, but didn't initialize them with a value. Add something like this :
You declared them at the start of the method, but you never initialized them. Initializing would be setting them equal to a value, such as:
Set variable "a" to some value like this,
Declaring and initialzing are both different.
Good Luck
If they were declared as fields of the class then they would be really initialized with 0.
You're a bit confused because if you write:
Then this code will print "0". It's because a special constructor will be called when you create new instance of Clazz. At first
super ()
will be called, then fielda
will be initialized implicitly, and then lineb = 0
will be executed.You declared them, but you didn't initialize them. Initializing them is setting them equal to a value:
You get the error because you haven't initialized the variables, but you increment them (e.g.,
a++
) in thefor
loop.Java primitives have default values but as one user commented below
Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.
There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.
If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.