views:

6889

answers:

5

If I have an int array structured like this:

private int[][] map = new int[400][400];

And I try to retrieve

map[100][200]

And that element isn't initialized, will i get a compiler/runtime error or will it return null? And is there any function to check if a given element/index exists/has been set?

+1  A: 

No.

Your array elements are only big enough to hold ints, in this case. There is no place to store the information about if the element "exists". It has been allocated, thus it exists. In Java, newly allocated int arrays will be initialized to all elements zero.

unwind
+2  A: 

I won't return null because int is a primitive type. It will return the default int value, which is 0.

There is no way of knowing if any element has been set, short of keeping a separate boolean array.

Martinho Fernandes
If it were an array of a custom class/enum object, would it return null if that item/index wasn't set?
Click Upvote
@Click Upvote: Yes.
Nikhil Chelliah
+7  A: 

As your array declaration is of a primitive type you won't get any compiler or runtime errors - the default value of 0 will be returned.

If your array had been an array of Objects, then the array would hold null for any element not specifically assigned.

Alnitak
+1  A: 

In Java, only reference variables are initialized to null. Primitives are guaranteed to return appropriate default values. For ints, this value is 0.

jcrossley3
A: 

You can use checkstyle, pmd, and findbugs on your source (findbugs on the binary) and they will tell you things like this.

Unfortunately it doesn't look like they catch this particular problem (which makes sense the the array is guaranteed to have each member set to 0, null, or false).

The use of those tools can will catch instance and class members (that are not arrays) that are being used before being given a value though (similar sort of issue).

TofuBeer