Memra

Declaring, instantiating & initializing arrays

Three ways to create a 1D array, default values, and the fixed-length rule.

Arrays: fixed-size, typed containers

An array holds a fixed number of values of the same type. There are three ways to create one:

// 1 — declare + allocate (elements get default values)
int[] scores = new int[5];         // [0, 0, 0, 0, 0]

// 2 — declare + initialise with an array initialiser
int[] primes = {2, 3, 5, 7, 11};  // length inferred as 5

// 3 — anonymous array (useful in method calls)
System.out.println(Arrays.toString(new int[]{1, 2, 3}));

Default values when you allocate without an initialiser:

| Element type | Default | |---|---| | numeric (int, long, …) | 0 | | double / float | 0.0 | | boolean | false | | reference types | null |

The length is fixed at creation — you cannot resize an array. If you need a growable container, use ArrayList (covered in the Collections module).

Style note: put the [] on the type, not the variable name — int[] a not int a[]. Both compile, but int[] a is idiomatic Java.

NORMAL ~/memra/learn/java-from-zero/declaring-arrays utf-8 LF