Memra

Declaring, instantiating & initializing arrays

◈ 4 cards

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 typeDefault
numeric (int, long, …)0
double / float0.0
booleanfalse
reference typesnull

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.

01234scores00000primes235711new int[5] vs {2, 3, 5, 7, 11}
Allocating gives you the default value in every slot; an initialiser fixes length and contents at once. Both arrays have length 5, and neither can ever grow.
NORMAL ~/memra/learn/java-from-zero/declaring-arrays utf-8 LF