Arrays: declaring, traversing, passing to methods
Creating one-dimensional arrays, default values, length, index errors, enhanced for, sum/max/average and an array going to a method as a reference. The cornerstone of every exam after the midterm.
An array is a structure that holds many values of the same type, in order, under a single name. Instead of creating 30 variables for the grades of 30 students, you create one array and walk through it with a loop. From the second half of the midterm period on, almost every question involves arrays: tracking indexes, walking with loops and “write a method that takes an array”.
Golden rules:
- The index starts at 0, the last index is
length - 1. a.lengthhas no parentheses (do not confuse it withlength()of a String).- The elements of a new array are filled with the default value: 0 for int.
- Enhanced for is only for reading. To modify, use an indexed for.
- An array goes to a method as a reference: if the method changes the elements, the caller sees it too.
Creating arrays
int[] scores = new int[5]; // 5 elements, all 0
scores[0] = 90;
scores[3] = 75;
System.out.println(scores[0] + " " + scores[1] + " " + scores[3] + " " + scores.length);
90 0 75 5
index: 0 1 2 3 4
scores: [90] [ 0] [ 0] [75] [ 0]
With new int[5] the size of the array is fixed once and cannot change afterwards. If you need a list whose size can change, you use ArrayList (week 7).
Default values
double[] d = new double[2];
boolean[] b = new boolean[2];
String[] s = new String[2];
char[] c = new char[2];
System.out.println(d[0] + " " + b[0] + " " + s[0] + " " + (int) c[0]);
0.0 false null 0
| Element type | Default |
|---|---|
int, long, short, byte | 0 |
double, float | 0.0 |
boolean | false |
char | '\u0000' (the character with code 0) |
String and other objects | null |
The array initializer
If you know the values from the start:
int[] primes = {2, 3, 5, 7, 11};
System.out.println(primes[0] + " " + primes[4] + " " + primes[primes.length - 1] + " " + primes.length);
String[] days = {"Mon", "Tue", "Wed"};
System.out.println(days[1] + " " + days[1].length());
2 11 11 5
Tue 3
The size comes from the number of elements in the curly braces. days[1].length() is the length of the String (3), days.length is the length of the array (3); one is a method, the other is a field.
Traversing an array
The standard pattern is an indexed for:
for (int i = 0; i < primes.length; i++) {
System.out.print(primes[i] + " ");
}
System.out.println();
for (int i = primes.length - 1; i >= 0; i--) System.out.print(primes[i] + " ");
2 3 5 7 11
11 7 5 3 2
PITFALL · going past the last index with
<=.for (int i = 0; i <= a.length; i++)accessesa[a.length]in the last iteration and the program crashes withArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3. This is a runtime error; the compiler does not catch it.
Printing an array
System.out.println(primes) does not print the elements; it prints address-like text starting with [I@ (it may differ on each run). To see it quickly:
import java.util.Arrays;
System.out.println(Arrays.toString(primes));
[2, 3, 5, 7, 11]
If the exam says “print the array”, writing it with a loop is the safe way.
Enhanced for (for-each)
int total = 0;
for (int p : primes) total += p; // "for each p in primes"
System.out.println(total);
int[] nums = {1, 2, 3};
for (int x : nums) x = x * 10; // x is a copy, the array does not change
System.out.println(Arrays.toString(nums));
for (int i = 0; i < nums.length; i++) nums[i] = nums[i] * 10;
System.out.println(Arrays.toString(nums));
28
[1, 2, 3]
[10, 20, 30]
An enhanced for has no index; in each iteration the value of the next element is copied into the variable. It is short and safe for reading; but to change an element, print the index or go backwards, you need an indexed for.
Basic algorithms
public static int sum(int[] arr) {
int total = 0;
for (int x : arr) total += x;
return total;
}
public static int max(int[] arr) {
int m = arr[0]; // start with the first element
for (int i = 1; i < arr.length; i++) {
if (arr[i] > m) m = arr[i];
}
return m;
}
public static int indexOfMax(int[] arr) {
int idx = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[idx]) idx = i;
}
return idx;
}
public static double average(int[] arr) {
return (double) sum(arr) / arr.length;
}
// in main:
int[] data = {4, 9, 2, 9, 7};
System.out.println(sum(data) + " " + max(data) + " " + indexOfMax(data) + " " + average(data));
31 9 1 6.2
indexOfMax returned 1 even though there are two 9s: because we used >, it is not updated on equality, so the first one seen stays. If you had written >= it would have returned 3.
PITFALL · int division in the average.
sum / arr.lengthis two ints; 31 / 5 = 6. Cast to(double)first: 6.2.
Frequency counting
If the values are in a small range (a die 1..6, a grade 0..10), you use the value as an index:
int[] rolls = {3, 1, 3, 6, 2, 3, 6};
int[] freq = new int[7]; // 0..6, we do not use 0
for (int r : rolls) freq[r]++;
for (int face = 1; face <= 6; face++) System.out.print(face + ":" + freq[face] + " ");
1:1 2:1 3:3 4:0 5:0 6:2
Passing an array to a method
An array variable holds not the array itself but its place in memory (a reference). When you pass an array to a method, a copy of this reference goes. Since the copy points to the same array, the method can change the elements.
public static void doubleAll(int[] arr) {
for (int i = 0; i < arr.length; i++) arr[i] *= 2;
}
public static void tryChange(int x) { x = 99; }
public static void reassign(int[] arr) {
arr = new int[]{9, 9, 9}; // the local arr now points to another array
arr[0] = 1;
}
// in main:
int[] arr = {1, 2, 3};
doubleAll(arr);
System.out.println(Arrays.toString(arr));
int single = 5;
tryChange(single);
System.out.println(single);
tryChange(arr[0]); // a single element: the int value goes
System.out.println(arr[0]);
reassign(arr);
System.out.println(Arrays.toString(arr));
[2, 4, 6]
5
2
[2, 4, 6]
main: arr ───────┐
▼
[2, 4, 6] the arr in doubleAll looks here too
▲
doubleAll: arr ────┘
Tell the four cases apart:
| Call | What goes? | Change in the caller? |
|---|---|---|
doubleAll(arr) changes the elements | a copy of the reference | Yes |
tryChange(single) | the int value | No |
tryChange(arr[0]) | the int value of a single element | No |
arr = new ... inside reassign(arr) | a copy of the reference | No, the local copy turned to another array |
Java is still working by pass-by-value; it is just that the thing being copied is a reference.
A method that returns an array
public static int[] makeSquares(int n) {
int[] result = new int[n];
for (int i = 0; i < n; i++) result[i] = i * i;
return result;
}
// main: System.out.println(Arrays.toString(makeSquares(5)));
[0, 1, 4, 9, 16]
The return type is written as int[].
Common mistakes
| Wrong idea | The truth |
|---|---|
The first element is a[1] | a[0] |
The last element is a[a.length] | a[a.length - 1] |
a.length() | An array has no parentheses: a.length |
| A new int array is filled with random values | All 0 |
String[] elements are the empty String "" | null |
for (int x : a) x = 0; zeroes the array | x is a copy; use an indexed for |
int[] b = a; copies the array | It points to the same array |
| A method cannot change the array | It can change its elements |
int m = 0; for max | Wrong for a negative array; m = arr[0] |
System.out.println(a) prints the elements | Address-like text; use a loop or Arrays.toString |
Test yourself
Exam-style questions. Solve them on paper first, then reveal the answer.
What is printed?
int[] a = new int[4];
a[1] = 5;
a[3] = a[1] * 2;
System.out.println(a[0] + a[1] + a[2] + a[3]);Show answer
new int[4] sets all four elements to 0. a = {0, 5, 0, 10}. The sum is 0 + 5 + 0 + 10 = 15 (all are ints, so addition is done).
What is printed?
int[] a = {10, 20, 30, 40, 50};
System.out.println(a[a.length - 2] + " " + a[1 + 2] + " " + a[a[0] / 10]);Show answer
length is 5, a[3] = 40. a[1 + 2] = a[3] = 40. a[0] / 10 = 1, a[1] = 20. What is inside the square brackets is computed first.
What is printed?
int[] a = {3, 8, 1, 6};
int r = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] > 4) r += a[i];
}
System.out.println(r);Show answer
The elements greater than 4 are 8 and 6. 8 + 6 = 14.
What is printed?
int[] a = {1, 2, 3, 4, 5};
for (int i = 1; i < a.length; i++) a[i] = a[i] + a[i - 1];
System.out.println(Arrays.toString(a));Show answer
Each element becomes the sum of itself and the updated previous element: a[1] = 2 + 1 = 3, a[2] = 3 + 3 = 6, a[3] = 4 + 6 = 10, a[4] = 5 + 10 = 15. A cumulative sum (running sum).
What is printed?
int[] a = {5, 5, 5};
for (int v : a) v++;
System.out.println(a[0] + a[1] + a[2]);Show answer
The v in an enhanced for is a copy of each element. v++ increments the copy, the array does not change. The sum is 5 + 5 + 5 = 15.
What is printed?
public static void doubleAll(int[] arr) {
for (int i = 0; i < arr.length; i++) arr[i] *= 2;
}
// in main:
int[] a = {1, 2, 3};
doubleAll(a);
doubleAll(a);
System.out.println(a[2]);Show answer
The reference (address) of the array goes to the method; the method changes the same array. After two calls each element is 4 times bigger: a[2] = 3 * 4 = 12.
What is printed?
int[] a = {2, 4, 6};
int x = a[0];
x = 100;
int[] b = a;
b[1] = 100;
System.out.println(a[0] + " " + a[1]);Show answer
x = a[0] copies an int value; changing x does not affect the array. b = a, however, does not create a new array, b and a point to the same array. b[1] = 100 actually changes a[1].
What is printed?
String[] s = new String[3];
s[0] = "A";
System.out.println(s[0] + s[1]);Show answer
The default value of a String array is null. In String concatenation, null is added as the text "null": "A" + null = "Anull".
What happens when this code runs?
int[] a = {1, 2, 3};
for (int i = 0; i <= a.length; i++) System.out.print(a[i] + " ");Show answer
The valid indexes are 0, 1, 2. The condition i <= a.length also tries i = 3; a[3] does not exist. The program first prints 1 2 3 , then crashes with Index 3 out of bounds for length 3. The correct version is i < a.length.
What is printed?
int[] a = {7, 3, 9, 3, 1};
int idx = 0;
for (int i = 1; i < a.length; i++) if (a[i] < a[idx]) idx = i;
System.out.println(idx + " " + a[idx]);Show answer
It keeps the index of the smallest element. i=1: 3 < 7 → idx 1. i=2: 9 < 3 is false. i=3: 3 < 3 is false (it does not change on equality). i=4: 1 < 3 → idx 4. Result: index 4, value 1.
Write a static method countEven(int[] arr) that returns how many elements of the array are even.
Show answer
The counter pattern over an array. Since we only read, an enhanced for is suitable.public static int countEven(int[] arr) { int c = 0; for (int x : arr) { if (x % 2 == 0) c++; } return c;}Test: {4, 9, 2, 9, 7} → 2.
Write a static method max(int[] arr) that returns the largest element. Assume the array is not empty.
Show answer
The starting value must be the first element of the array. If you write int m = 0;, an array whose elements are all negative gives a wrong result (0).public static int max(int[] arr) { int m = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > m) m = arr[i]; } return m;}Test: {4, 9, 2, 9, 7} → 9.
Verification: All outputs were run with JDK 26 (verify/SEN1001/W06.java). The out-of-bounds array error was caught (catch) in the same file and its message printed.