Java Fundamentals

Arrays.

01

What is an Array?

An array is a fixed-size, ordered block of values of the same type, stored one after another in memory and reached by position rather than by name.

02

Declaring & Creating Arrays

Declaring an array just creates a reference. The array itself doesn't exist in memory until you create it with new or an initializer.

Declare, then create

int[] scores; or  int scores[];                 // reference only, no array yet
scores = new int[5];        // now: 5 slots, all default to 0

Declare and initialize together

int[] scores = { 90, 85, 77, 100, 62 };
String[] names  = new String[]{ "Rina", "Sam" };
04

Iterating an Array

Two everyday patterns cover almost every case: the counted loop, when you need the index, and the enhanced for-loop, when you only need the values.

Classic for — index available

for (int i = 0; i < scores.length; i++) {
    System.out.println("index " + i + " = " + scores[i]);
}

Enhanced for — values only

for (int score : scores) {
    System.out.println(score);
}
Rule of thumb Reach for the enhanced for-loop by default — it's shorter and can't go out of bounds. Fall back to the counted loop only when you actually need the index, or when you need to modify elements in place.
05

Multi-Dimensional Arrays

Java doesn't have true multi-dimensional arrays — a 2D array is simply an array of arrays. Each row is its own independent array object.

int[][] grid = {
    { 1, 2, 3 },
    { 4, 5, 6 }
};

grid[1][2];   // 6 — row 1, column 2
grid.length;      // 2  — number of rows
grid[0].length;   // 3  — length of row 0
1
2
3
·
4
5
6
·

grid[1][2] highlighted — row 1, column 2.

Because rows are independent arrays Rows in a 2D array don't have to be the same length — this is often called a jagged array. int[][] jagged = { {1}, {1,2,3}, {1,2} }; is completely valid.