Arrays in Java
2166 words
11 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Arrays in Java ## 🎯 Learning Objectives By the end of this topic, you will be able to: - Declare, create, and initialize one-dimensional and multi-dimensional arrays - Iterate over arrays using both indexed and enhanced for loops - Understand the `length` property and array bounds - Use `java.util.Arrays` utility...

Arrays in Java
🎯 Learning Objectives
By the end of this topic, you will be able to:
- Declare, create, and initialize one-dimensional and multi-dimensional arrays
- Iterate over arrays using both indexed and enhanced for loops
- Understand the
lengthproperty and array bounds - Use
java.util.Arraysutility methods for sorting, searching, and filling - Use variable-length argument lists (varargs)
- Recognize and avoid
ArrayIndexOutOfBoundsException
📋 Prerequisites
- Data Types & Operators (week01/02-data-types-operators.md): Type system
- Control Flow (week01/04-control-flow.md): Loops
- Memory Model (week01/03-memory-model.md): Heap vs stack
1. Intuition: What Problem Do Arrays Solve?
1.1 The Problem
Without arrays, storing 100 test scores would require 100 separate variables:
javaint score1, score2, score3, ..., score100; // Impossible!
An array lets you store many values of the same type under a single name, accessed by index:
javaint[] scores = new int[100]; // One variable, 100 values scores[0] = 85; // First score scores[99] = 92; // Last score
1.2 Mental Model: A Row of Lockers
An array is like a row of numbered lockers in a school hallway:
- Each locker holds one item (all the same type)
- Each locker has a unique number (index), starting at 0
- You know how many lockers there are (
length) - Opening a non-existent locker (index -1 or 100 for 100 lockers) gets you in trouble
pseudoIndex: 0 1 2 3 4 ┌────┬────┬────┬────┬────┐ Values │ 10 │ 20 │ 30 │ 40 │ 50 │ └────┴────┴────┴────┴────┘ Length: 5
2. Array Declaration and Creation
2.1 Two-Step Process
In Java, arrays are objects on the heap. Creating them has two steps:
javaint[] numbers; // 1. DECLARE: reference variable (on stack) numbers = new int[5]; // 2. CREATE: array object (on heap)
Or combined:
javaint[] numbers = new int[5]; // All elements default to 0
2.2 Declaration Styles
javaint[] numbers; // Preferred style — type brackets with type int numbers[]; // C-style — works but less readable int []numbers; // Legal but unusual
Recommended: Always put
[] next to the type (int[]).2.3 Initialization with Literals
javaint[] numbers = {10, 20, 30, 40, 50}; // Size inferred: 5 String[] names = {"Alice", "Bob", "Charlie"}; // Size inferred: 3
This shorthand can only be used in the declaration line:
javaint[] numbers; numbers = {10, 20, 30}; // Compile error!
Use
new for re-assignment:javaint[] numbers; numbers = new int[]{10, 20, 30}; // OK
2.4 Default Values
When created with
new, array elements get default values:| Type | Default Value |
|---|---|
byte, short, int, long | 0 |
float, double | 0.0 |
char | '\u0000' (null char) |
boolean | false |
| Reference types (String, Object) | null |
3. Accessing Array Elements
3.1 Indexing
javaint[] numbers = new int[5]; numbers[0] = 10; // First element (index 0) numbers[1] = 20; // Second element numbers[4] = 50; // Last element (index length-1) int x = numbers[2]; // Read element
3.2 The length Property
javaint[] arr = {10, 20, 30, 40, 50}; System.out.println(arr.length); // 5 — note: no parentheses!
length is a field (not a method like String.length()).3.3 Iterating Over Arrays
Using indexed
for loop:javaint[] numbers = {10, 20, 30, 40, 50}; for (int i = 0; i < numbers.length; i++) { System.out.println("Index " + i + ": " + numbers[i]); }
Using enhanced
for-each loop:javafor (int num : numbers) { System.out.println(num); }
4. Arrays Are Objects — Reference Semantics
javaint[] a = {1, 2, 3}; int[] b = a; // b references the SAME array b[0] = 99; System.out.println(a[0]); // 99 — a and b share the same array!
(Diagram)
To copy an array:
javaint[] original = {1, 2, 3}; int[] copy = original.clone(); // Method 1: clone() int[] copy2 = Arrays.copyOf(original, 3); // Method 2: Arrays.copyOf int[] copy3 = new int[3]; System.arraycopy(original, 0, copy3, 0, 3); // Method 3: System.arraycopy
5. Multi-Dimensional Arrays
5.1 Rectangular Arrays (Regular)
javaint[][] matrix = new int[3][4]; // 3 rows × 4 columns matrix[0][0] = 1; // Row 0, Column 0 matrix[2][3] = 12; // Last row, last column
Initialization:
javaint[][] matrix = { {1, 2, 3, 4}, // Row 0 {5, 6, 7, 8}, // Row 1 {9, 10, 11, 12} // Row 2 };
Iteration (nested loops):
javafor (int i = 0; i < matrix.length; i++) { // Rows for (int j = 0; j < matrix[i].length; j++) { // Columns System.out.print(matrix[i][j] + " "); } System.out.println(); }
5.2 Ragged Arrays (Irregular)
Each row can have a different length:
javaint[][] ragged = new int[3][]; ragged[0] = new int[5]; // Row 0: 5 columns ragged[1] = new int[3]; // Row 1: 3 columns ragged[2] = new int[7]; // Row 2: 7 columns
(Diagram)
6. Variable-Length Arguments (Varargs)
Varargs allow a method to accept a variable number of arguments:
javapublic static int sum(int... numbers) { // ... means varargs int total = 0; for (int n : numbers) { total += n; } return total; } // Usage System.out.println(sum(1, 2)); // 3 System.out.println(sum(1, 2, 3, 4, 5)); // 15 System.out.println(sum()); // 0 (zero arguments is OK)
Rules:
- Only one varargs parameter per method
- It must be the last parameter
- Inside the method, it's treated as an array
javapublic static void printList(String prefix, String... items) { for (String item : items) { System.out.println(prefix + " " + item); } }
7. java.util.Arrays Utility Class
| Method | Description | Example |
|---|---|---|
sort(arr) | Sorts array in ascending order | Arrays.sort(numbers) |
binarySearch(arr, key) | Searches sorted array (returns index) | Arrays.binarySearch(arr, 42) |
fill(arr, value) | Fills array with a value | Arrays.fill(arr, 0) |
copyOf(arr, length) | Copies array (new length) | Arrays.copyOf(arr, 10) |
equals(arr1, arr2) | Checks element-by-element equality | Arrays.equals(a, b) |
toString(arr) | Returns readable representation | Arrays.toString(arr) |
deepToString(arr) | For multi-dimensional arrays | Arrays.deepToString(matrix) |
Examples:
javaint[] numbers = {42, 7, 15, 3, 99}; Arrays.sort(numbers); System.out.println(Arrays.toString(numbers)); // [3, 7, 15, 42, 99] int index = Arrays.binarySearch(numbers, 42); System.out.println(index); // 3 (0-based index) int[] copy = Arrays.copyOf(numbers, 7); // Extends with zeros System.out.println(Arrays.toString(copy)); // [3, 7, 15, 42, 99, 0, 0]
8. Java vs Python: Arrays
| Feature | Java | Python |
|---|---|---|
| Type | Fixed-type (all elements same type) | Dynamic (can mix types) |
| Size | Fixed after creation | Dynamic (list grows/shrinks) |
| Syntax | int[] arr = new int[5]; | arr = [0] * 5 or arr = [] |
| Length | arr.length (field) | len(arr) (function) |
| Slicing | Arrays.copyOfRange(arr, 1, 4) | arr[1:4] |
| Resizing | Not possible (new array needed) | arr.append(), arr.pop() |
| Default values | 0, 0.0, false, null | Nothing (list created empty) |
| Multi-dimensional | int[][] (array of arrays) | Nested lists |
| Utility | java.util.Arrays | Built-in list methods |
9. Common Pitfalls
Pitfall 1: ArrayIndexOutOfBoundsException
javaint[] arr = {1, 2, 3}; System.out.println(arr[3]); // Index 3 out of bounds for length 3
Why: Valid indices are 0, 1, 2 (length-1). Index 3 is beyond the array. Fix: Always check
index >= 0 && index < arr.length.Pitfall 2: Confusing length with length()
javaint[] arr = {1, 2, 3}; String s = "Hello"; System.out.println(arr.length()); // Compile error! length is a field System.out.println(s.length); // Compile error! length() is a method
Why: Arrays use
length (field), Strings use length() (method). Fix: Remember: arr.length (no parens), str.length() (with parens).Pitfall 3: Treating == on Arrays as Content Comparison
javaint[] a = {1, 2, 3}; int[] b = {1, 2, 3}; System.out.println(a == b); // false — different references System.out.println(a.equals(b)); // false — arrays don't override equals() System.out.println(Arrays.equals(a, b)); // true — element-by-element
Why: Arrays inherit
equals() from Object, which compares references. Fix: Use Arrays.equals().Pitfall 4: Assuming Default Values for Local Array Variables
javaint[] arr; System.out.println(arr[0]); // Compile error: arr not initialized!
Why: Local variables (including array references) must be initialized before use. Fix:
int[] arr = new int[5]; or int[] arr = {1, 2, 3};Pitfall 5: Modifying Array Through For-Each
javaint[] arr = {1, 2, 3}; for (int x : arr) { x = 99; // Only changes local variable x, NOT arr[0], arr[1], arr[2] } System.out.println(Arrays.toString(arr)); // [1, 2, 3]
Why: For-each creates a copy of each element for primitives. Fix: Use indexed for loop to modify elements.
10. Practice Questions
Q1: What is the output?javaint[] arr = new int[5]; arr[0] = 10; arr[2] = 30; for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); }Answer:10 0 30 0 0The array is initialized with default values (0 for int). Only indices 0 and 2 are explicitly set; indices 1, 3, 4 retain the default 0. Q2: What happens with this code?javaint[] arr = {1, 2, 3, 4, 5}; System.out.println(arr[-1]);Answer:ArrayIndexOutOfBoundsExceptionat runtime. Java does not support negative indexing (unlike Python). Valid indices are 0 toarr.length - 1. Q3: Write a method that reverses an array in place.Answer:javapublic static void reverse(int[] arr) { int left = 0; int right = arr.length - 1; while (left < right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } // Usage: int[] nums = {1, 2, 3, 4, 5}; reverse(nums); System.out.println(Arrays.toString(nums)); // [5, 4, 3, 2, 1]Q4: What is the output?javaint[][] grid = new int[2][]; grid[0] = new int[]{1, 2}; grid[1] = new int[]{3, 4, 5}; System.out.println(grid[0].length); System.out.println(grid[1].length);Answer:2then3This is a ragged array. Row 0 has length 2, row 1 has length 3.grid.lengthwould be 2 (two rows). Q5: Fix this code to copy array content correctlyjavaint[] a = {1, 2, 3}; int[] b = a; // Bug: b references same array b[0] = 99;Answer: Use one of these copying methods:javaint[] b = a.clone(); // Method 1 int[] b = Arrays.copyOf(a, a.length); // Method 2 int[] b = new int[a.length]; // Method 3 System.arraycopy(a, 0, b, 0, a.length);Nowb[0] = 99;doesn't affecta. Q6: What does varargs allow you to do?Answer: Varargs (type... name) allows a method to accept zero or more arguments of that type, packed into an array inside the method:javapublic static double average(double... values) { if (values.length == 0) return 0; double sum = 0; for (double v : values) sum += v; return sum / values.length; } System.out.println(average(1, 2, 3)); // 2.0 System.out.println(average()); // 0.0 System.out.println(average(5.0, 10.0)); // 7.5Q7: What is the output of this search?javaint[] arr = {10, 20, 30, 40, 50}; int index = Arrays.binarySearch(arr, 25); System.out.println(index);Answer: A negative number, specifically-3(the insertion point is index 2, returned as-(insertion_point) - 1 = -(2) - 1 = -3).binarySearchrequires a SORTED array (this one is). For a missing element, it returns-(insertion_point) - 1whereinsertion_pointis where the element would be inserted to maintain sorted order. Q8: Write a method to find the maximum value in an int array.Answer:javapublic static int findMax(int[] arr) { if (arr == null || arr.length == 0) { throw new IllegalArgumentException("Array cannot be null or empty"); } int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; }Q9: What does Arrays.deepToString() do?Answer: It converts multi-dimensional arrays to a readable string, showing nested content recursively:javaint[][] matrix = {{1, 2}, {3, 4}}; System.out.println(Arrays.toString(matrix)); // [[I@..., [I@...] (junk!) System.out.println(Arrays.deepToString(matrix)); // [1, 2], [3, 4](/courses/bscs2005/notes/1%2C%202%5D%2C%20%5B3%2C%204)UsedeepToStringfor nested arrays;toStringonly shows reference addresses for the top-level. Q10: What is the output?javaint[] a = {1, 2, 3}; int[] b = {1, 2, 3}; System.out.println(a.equals(b)); System.out.println(Arrays.equals(a, b));Answer:falsethentrue
a.equals(b)uses Object's equals, which compares references (not content) → falseArrays.equals(a, b)compares elements one by one → true
📐 Key Concepts
| Concept | Syntax | Example |
|---|---|---|
| Declaration | type[] name | int[] arr |
| Creation | new type[size] | new int[10] |
| Literal | {val1, val2, ...} | {1, 2, 3} |
| Length | arr.length | arr.length |
| Access | arr[index] | arr[0] |
| 2D creation | new type[rows][cols] | new int[3][4] |
| Varargs | type... name | int... numbers |
| Copy | Arrays.copyOf(arr, newLen) | Arrays.copyOf(arr, 5) |
🔗 Cross-References
- Next: Strings — strings as character arrays
- Related: Collections Framework — dynamic alternatives to arrays
- Python Comparison: BSCS1002 — Lists and Arrays in Python Join Discord Previous1.5 OOP ConceptsNext2.2 Strings