Arrays · Lesson 13 of 42
Arrays in Java
An array holds a fixed number of values of the same type, side by side in memory. Marks of a class, prices in a cart, days in a month – whenever you have "many of the same thing" and know how many, an array is the fastest structure Java offers. Arrays are also the foundation of most coding-round problems.
In this lesson
- Creating arrays and accessing elements by index
- Default values, length and bounds checking
- Arrays are objects: references, copying and comparing
- The
Arraysutility class and classic array programs
Creating an array
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] marks = {78, 92, 65, 88, 71}; // with values
String[] names = new String[3]; // 3 empty slots
names[0] = "Asha";
names[1] = "Ben";
System.out.println(marks[0] + " " + marks[4]);
System.out.println("length = " + marks.length);
System.out.println(Arrays.toString(names));
double[] prices = new double[2];
boolean[] flags = new boolean[2];
System.out.println(Arrays.toString(prices) + " " + Arrays.toString(flags));
}
}
78 71 length = 5 [Asha, Ben, null] [0.0, 0.0] [false, false]
int[] marks = {78, 92, 65, 88, 71}
- 78[0]
- 92[1]
- 65[2]
- 88[3]
- 71[4]
Indexes run from 0 to length − 1. length is a field, not a method: marks.length
New arrays are filled with default values: 0 for numbers, false for booleans, '\u0000' for chars and null for objects. The size is fixed once created – for a list that grows, use ArrayList (chapter 12).
Common mistake: off-by-one indexes
marks[marks.length] throws ArrayIndexOutOfBoundsException – the last valid index is length - 1. Loops should be i < marks.length, not i <= marks.length.
public class Main {
public static void main(String[] args) {
int[] a = {10, 20, 30};
System.out.println(a[3]);
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Looping over arrays
public class Main {
public static void main(String[] args) {
int[] marks = {78, 92, 65, 88, 71};
int sum = 0, max = marks[0], maxAt = 0;
for (int i = 0; i < marks.length; i++) {
sum += marks[i];
if (marks[i] > max) { max = marks[i]; maxAt = i; }
}
System.out.printf("Average %.1f, highest %d at index %d%n", (double) sum / marks.length, max, maxAt);
for (int i = marks.length - 1; i >= 0; i--) System.out.print(marks[i] + " ");
}
}
Average 78.8, highest 92 at index 1 71 88 65 92 78
Arrays are objects (references)
An array variable holds a reference. Assigning it to another variable does not copy the elements – both names point at the same array.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] original = {1, 2, 3};
int[] alias = original; // same array
int[] copy = Arrays.copyOf(original, original.length);
int[] clone = original.clone(); // also a copy
alias[0] = 99;
System.out.println(Arrays.toString(original));
System.out.println(Arrays.toString(copy) + " " + Arrays.toString(clone));
System.out.println(original == copy); // different objects
System.out.println(Arrays.equals(copy, clone)); // same contents
}
}
[99, 2, 3] [1, 2, 3] [1, 2, 3] false true
Two names, one array
original→ [99, 2, 3]array object #1alias→ same object #1no copy madecopy→ [1, 2, 3]array object #2
This also means a method that receives an array can change the caller's elements – an important point when you reach chapter 7.
The Arrays class
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {42, 7, 19, 3, 25};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
System.out.println("index of 19: " + Arrays.binarySearch(nums, 19)); // needs a sorted array
int[] firstThree = Arrays.copyOfRange(nums, 0, 3);
System.out.println(Arrays.toString(firstThree));
int[] zeros = new int[5];
Arrays.fill(zeros, -1);
System.out.println(Arrays.toString(zeros));
System.out.println("sum: " + Arrays.stream(nums).sum() + ", max: " + Arrays.stream(nums).max().getAsInt());
String[] words = {"pear", "Apple", "mango"};
Arrays.sort(words, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(words));
}
}
[3, 7, 19, 25, 42] index of 19: 2 [3, 7, 19] [-1, -1, -1, -1, -1] sum: 96, max: 42 [Apple, mango, pear]
Tip
Printing an array directly (System.out.println(nums)) shows something like [I@6d06d69c – the type and a hash, not the contents. Always use Arrays.toString() (or Arrays.deepToString() for 2-D arrays).
Classic array programs
Reverse in place (two pointers)
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
int t = a[i]; a[i] = a[j]; a[j] = t;
}
System.out.println(Arrays.toString(a));
}
}
[5, 4, 3, 2, 1]
Second largest without sorting
public class Main {
public static void main(String[] args) {
int[] a = {12, 45, 7, 45, 30};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int x : a) {
if (x > first) { second = first; first = x; }
else if (x > second && x != first) second = x;
}
System.out.println("largest " + first + ", second " + second);
}
}
largest 45, second 30
Count frequencies with a counting array
public class Main {
public static void main(String[] args) {
int[] rolls = {3, 6, 1, 6, 2, 6, 3};
int[] count = new int[7]; // index = dice face
for (int r : rolls) count[r]++;
for (int face = 1; face <= 6; face++) {
if (count[face] > 0) System.out.println(face + " → " + count[face]);
}
}
}
1 → 1 2 → 1 3 → 2 6 → 3
Practice
Try it yourself
Find the missing number in an array containing 1 to 6 with one number missing: {1, 2, 4, 5, 6}.
Show solution
public class Main { public static void main(String[] args) { int[] a = {1, 2, 4, 5, 6}; int n = a.length + 1; int expected = n * (n + 1) / 2, actual = 0; for (int x : a) actual += x; System.out.println(expected - actual); } }3
Rotate {1, 2, 3, 4, 5} left by 2 positions into a new array.
Show solution
import java.util.Arrays; public class Main { public static void main(String[] args) { int[] a = {1, 2, 3, 4, 5}; int k = 2; int[] r = new int[a.length]; for (int i = 0; i < a.length; i++) r[i] = a[(i + k) % a.length]; System.out.println(Arrays.toString(r)); } }[3, 4, 5, 1, 2]
Quick check
What is the default value of elements in new String[3]?
null.
Does int[] b = a; copy the array?
No – both variables refer to the same array. Use a.clone() or Arrays.copyOf.
What must be true before calling Arrays.binarySearch?
The array must be sorted.
Summary
- Arrays have fixed size, zero-based indexes and a
lengthfield. - Array variables are references; copy with
clone()/Arrays.copyOf, compare withArrays.equals. Arraysprovides sort, binarySearch, fill, copyOfRange, toString and stream.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.