Learning outcome: Declare, create, initialise, and traverse Java arrays, including one-dimensional, multidimensional, and jagged arrays.
An array is a collection of elements of the same type. In Java, an array is an object, and it is a reference type. Arrays are useful when a program needs to store several related values under one name.
Important properties:
| Property | Meaning |
|---|---|
| Same element type | One array stores values of one declared type, such as int or String. |
| Fixed length | The size is decided when the array is created and does not grow automatically. |
| Zero-based index | The first element is at index 0. |
| Reference type | An array variable stores a reference to an array object. |
| Default element values | A newly created array is filled with the element type's default value. |
One-Dimensional Array
In simple terms: An array is a row of numbered lockers, all built to hold the same kind of item. The length of the row is fixed the moment it is built, and every locker already holds a default value rather than nothing at all.
The common declaration styles are:
int[] marks;
int marks2[];
The first style, int[] marks, is generally preferred because it makes the type clearer.
Declaration, creation, and initialisation can be written separately:
int[] numbers; // declaration
numbers = new int[5]; // creation
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 70;
numbers[3] = 40;
numbers[4] = 50;
Immediately after new int[5], all five elements are 0. A new boolean[] contains false, and a new array of reference types contains null. Array elements receive defaults even when the array variable itself is local; an uninitialised local array variable still cannot be read.
Or all at once:
int[] numbers = {10, 20, 70, 40, 50};
Traversing an Array
In simple terms: Use the indexed for loop when the locker number matters, such as when printing “position 3”. Use the enhanced for-each loop when only the contents matter and the numbering is just noise.
Use a normal for loop when the index matters.
public class ArrayDemo {
public static void main(String[] args) {
int[] values = {10, 20, 70, 40, 50};
for (int i = 0; i < values.length; i++) {
System.out.println(values[i]);
}
}
}
Use an enhanced for loop when only the value is needed.
public class ForEachDemo {
public static void main(String[] args) {
int[] values = {33, 3, 4, 5};
for (int value : values) {
System.out.println(value);
}
}
}
The length property gives the number of elements in the array.
System.out.println(values.length);
Multidimensional Array
Java models a two-dimensional array as an array whose elements are references to row arrays. It can represent rows and columns, but the rows are separate arrays and need not all have the same length.
In simple terms: A two-dimensional array in Java is not a grid drawn on a single sheet. It is a column of pointers, each pointing at a separate row stored elsewhere, which is why the rows can be replaced and sized independently.
int[][] matrix = {
{1, 2, 3},
{2, 4, 5},
{4, 4, 5}
};
Traversing a 2D array:
public class MatrixDemo {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{2, 4, 5},
{4, 4, 5}
};
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
Jagged Array
A jagged array is a two-dimensional array where rows can have different lengths.
In simple terms: A jagged array is a class register in which each row holds one student’s marks and the students have sat different numbers of tests. Row 1 may hold three marks and row 2 five; nothing forces the rows to match.
Example:
public class JaggedArrayDemo {
public static void main(String[] args) {
int[][] arr = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = count++;
}
}
}
}
Advantages and Limitations
| Advantage | Explanation |
|---|---|
| Organized storage | Related values are stored under one name. |
| Random access | Any element can be accessed directly by index. |
| Efficient traversal | Loops can process all elements cleanly. |
| Limitation | Explanation |
|---|---|
| Fixed size | An array cannot grow after creation. |
| Same declared element type | Each element must be compatible with the array's declared element type. |
| Index failures | An index below 0 or at least length throws ArrayIndexOutOfBoundsException. |
Common Mistakes
| Problem | Fix |
|---|---|
Using index 1 for the first element |
Use index 0. |
Accessing arr[arr.length] |
Last valid index is arr.length - 1. |
| Forgetting to create the array before use | Use new or an initializer. |
| Assuming arrays grow automatically | Use collections later when resizable storage is needed. |
Calling an invalid index an Error |
It is an unchecked ArrayIndexOutOfBoundsException, not a subclass of java.lang.Error. |
Practice
- Create an array of five marks and print all values.
- Find the sum of all values in an integer array.
- Print a 3 by 3 matrix using nested loops.
- Create a jagged array with row sizes 2, 3, and 4.
Quick Check
1. What is the index of the first element in a Java array?
The first element is at index 0.
2. Can a Java array grow automatically after it is created?
No. A Java array has a fixed length. For resizable storage, Java collections are used later in the course.
3. What does arr.length return?
It returns the number of elements in the array.
4. What is a jagged array?
A jagged array is a multidimensional array whose rows can have different lengths.
5. Is an array a primitive type or a reference type?
An array is a reference type because the array variable refers to an array object.
6. What values does new int[3] initially contain?
It initially contains three zero values: {0, 0, 0}.
Summary
Arrays store multiple values compatible with one declared element type. They are zero-indexed objects with fixed lengths, and newly created elements receive default values. One-dimensional arrays store a sequence; Java's multidimensional arrays are arrays of arrays, so their rows may be rectangular or jagged.