0

I think I'm missing something quite rudimentary, but in the following code I get the error The local variable array may not have been initialized at the line where I test for its nullity:

int [] array; 
outerloop:
for(int x = xMin;x <= xMax;x++){
    for(int y = yMin;y <= yMax;y++){
        if(condition(x,y)){
            array = new int[2];
            array[0] = x;
            array[1] = y;
            break outerloop;
        }
    }
}

if(array != null){
    //do something
}

Why is this? Shouldn't the test just return false in the case that the variable is uninitialized? I've been away from Java for a little while but I didn't think I'd forgotten that much ....

Thanks in advance :)

Rookatu
  • 1,407
  • 3
  • 20
  • 42
  • 2
    I dont know the long answer but the short answer is that you need to declare it as int[] array = null; – ivarni Nov 29 '13 at 08:22

2 Answers2

6

If the condition x <= xMax is false, your loop will never execute and thus if(array != null){ //do something } will be executed, which will be accessing an uninitialized variable.

Just change:

int [] array;

to

int [] array = null;
Yury Tarabanko
  • 42,049
  • 9
  • 81
  • 96
swinefeaster
  • 2,505
  • 2
  • 29
  • 46
2

Even though primitives and objects may be automatically initialized (objects to null) it is a good habit to initialize them.

Note Local variables must be explicitly initialized. Java will not initialize them for you.

Scary Wombat
  • 43,525
  • 5
  • 33
  • 63
  • So a global declaration of `int [] array;` would permit a test via `if(array == null)` but not a local declaration? – Rookatu Nov 29 '13 at 08:28
  • I found that this post answers the question, and your response is closest to getting at the core problem: http://stackoverflow.com/questions/16699593/uninitialized-object-vs-object-initialized-to-null – Rookatu Nov 29 '13 at 08:36