An array is declared with type[] and created with new, an array
initializer { ... }, or both. The brackets can sit on the type or the
variable, but type[] is the convention.
int[] a = new int[3]; // size only — defaults {0,0,0}
int[] b = new int[]{1, 2, 3}; // size + values
int[] c = {1, 2, 3}; // shorthand initializer (declaration only)
int d[] = {1, 2, 3}; // legal but discouraged (C-style)
The bare { ... } shorthand works only at declaration — you can't write
c = {4,5,6}; later; you'd need c = new int[]{4,5,6};. Either form fixes the
length at creation.
An array is always an object on the heap, even an array of primitives. The
variable holds a reference to it, the array has a runtime class
(int[].class), and it inherits from Object — so you can call
clone(), read .length, and store it in an Object variable.
int[] a = {1, 2, 3};
Object o = a; // arrays are Objects
System.out.println(a.getClass().getName()); // "[I" — int array
int[] copy = a.clone(); // inherited (overridden) clone
Because it's an object, an array variable can be null, and elements of a
primitive array are stored inline (contiguously) while elements of an object
array are references.
Allocating an array with new zero-initializes every element — you never get
garbage. The default depends on the element type:
| Element type | Default |
|---|---|
numeric (int, double, …) |
0 / 0.0 |
boolean |
false |
char |
' |