views:

319

answers:

9

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?

+1  A: 
int a = 0;
int b = 0;
+2  A: 

You declared them, but didn't initialize them with a value. Add something like this :

int a = 0;
Jerome
+1  A: 

You haven't initialised a and b, only declared them. There is a subtle difference.

int a = 0;
int b = 0;

At least this is for C++, I presume Java is the same concept.

Andy Shellam
yes java is the same (i think)
David
+1  A: 

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:

int a = 0;
int b = 0;
Thomas Owens
+1  A: 

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:

class Clazz {
  int a;
  int b;

  Clazz () {
     super ();
     b = 0;
  }

  public void printA () {
     sout (a + b);
  }

  public static void main (String[] args) {
     new Clazz ().printA ();
  }
}

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 field a will be initialized implicitly, and then line b = 0 will be executed.

Roman
+7  A: 

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

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

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

mipadi
Perhaps "int b = 0;" is "declaration and initialization."
ArunSaha
+1  A: 

You declared them, but not initialized.

int a; // declaration, unknown value
a = 0; // initialization
int a = 0; // declaration with initialization
Konrad Garus
+1  A: 

You declared them but did not provide them with an intial value - thus, they're unintialized. Try something like:

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

and the warnings should go away.

Bob Jarvis
+1  A: 

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.

codymanix