tags:

views:

115

answers:

4

If I use a statement in my code like

int[] a = new int[42];

Will it initialize the array to anything in particular? (e.g. 0) I seem to remember this is documented somewhere but I am not sure what to search for.

+4  A: 

When created, arrays are automatically initialized with the default value of their type - in your case that would be 0. The default is false for boolean and null for all reference types.

Bozhidar Batsov
+11  A: 

At 15.10 Array Creation Expressions the JLS says

[...] a single-dimensional array is created of the specified length, and each component of the array is initialized to its default value

and at 4.12.5 Initial Values of Variables it says:

For type int, the default value is zero, that is, 0.

p00ya
A: 

All elements in the array are initialized to zero. I haven't been able to find evidence of that in the Java documentation but I just ran this to confirm:

int[] arrayTest = new int[10];
System.out.println(arrayTest[5]) // prints zero
haldean
Testing a specific implementation is not a good way to verify that every implementation behaves this way. It's better to check the documentation/specification, because if it isn't specified/documented then other implementations could handle it differently. That's more of problem in other languages, because Java has very few places with undefined/implementation-specific behaviour, but it's still true.
Joachim Sauer
Further more - if it's ain't in the spec - behavior can be changed on a newer version of the same implementation.
duduamar
A: 

The array would be initialized with 42 0's

For other data types it would be initialized with the default value ie.

new boolean[42]; // would have 42 false 's
new double[42]; // would have 42 0.0 ( or 0.0D )
new float[42];// 42  0.0f 's
new long[42]; // 42  0L 's 

And so on.

For objects in general it would be null:

String [] sa = new String[42]; // 42 null's 

Date [] da = new Date[42]; // 42 null's
OscarRyz