Java course menu
Java Arrays: Creating, Looping, Sorting and the Arrays Class
Learn Java arrays: declaring and creating arrays, default values, indexing and length, ArrayIndexOutOfBoundsException, looping, printing with Arrays.toString, sorting, searching, copying and comparing arrays, and when to use ArrayList instead.
On this page
An array stores a fixed number of values of the same type. Each value is an element, reached by its index, counting from 0. Arrays are the most basic way to hold a collection in Java; for collections that grow and shrink, you will use ArrayList.
Creating arrays#
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] scores = {72, 88, 95, 64, 81}; // with values
double[] prices = new double[3]; // 3 elements, all 0.0
String[] names = new String[2]; // 2 elements, all null
System.out.println(scores[0] + " " + scores[2]);
System.out.println(scores.length);
System.out.println(Arrays.toString(prices));
System.out.println(Arrays.toString(names));
}
}72 95
5
[0.0, 0.0, 0.0]
[null, null]Type[] namedeclares an array;new Type[n]creates one withnelements.- New arrays are filled with default values:
0,0.0,false,'\u0000'ornull. lengthis a field (no parentheses), and it never changes after creation.Arrays.toString(fromjava.util.Arrays) formats an array for printing. Printing an array directly shows something like[I@1b6d3586, which is not useful.
Reading and changing elements#
public class Main {
public static void main(String[] args) {
String[] days = {"Mon", "Tue", "Wed"};
days[1] = "Tuesday";
System.out.println(days[1]);
System.out.println(days[days.length - 1]); // last element
}
}Tuesday
WedOut of bounds#
Java checks every index. Using an invalid one throws an exception instead of silently reading other memory:
public class Main {
public static void main(String[] args) {
int[] values = {10, 20, 30};
try {
System.out.println(values[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Error: Index 3 out of bounds for length 3Valid indexes are 0 to length - 1.
Looping over an array#
public class Main {
public static void main(String[] args) {
double[] temps = {31.5, 29.0, 33.5, 30.0};
double sum = 0;
for (double t : temps) {
sum += t;
}
System.out.println("Average: " + sum / temps.length);
for (int i = 0; i < temps.length; i++) {
System.out.println("Day " + (i + 1) + ": " + temps[i]);
}
}
}Average: 31.0
Day 1: 31.5
Day 2: 29.0
Day 3: 33.5
Day 4: 30.0The Arrays utility class#
java.util.Arrays has ready-made methods for common tasks:
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));
int index = Arrays.binarySearch(nums, 19); // array must be sorted
System.out.println("19 is at index " + index);
int[] copy = Arrays.copyOf(nums, 3); // first 3 elements
int[] part = Arrays.copyOfRange(nums, 1, 4); // indexes 1 to 3
System.out.println(Arrays.toString(copy) + " " + Arrays.toString(part));
int[] filled = new int[4];
Arrays.fill(filled, 7);
System.out.println(Arrays.toString(filled));
System.out.println(Arrays.stream(nums).sum() + " " + Arrays.stream(nums).max().getAsInt());
}
}[3, 7, 19, 25, 42]
19 is at index 2
[3, 7, 19] [7, 19, 25]
[7, 7, 7, 7]
96 42Arrays are objects: copying and comparing#
An array variable holds a reference. Assigning it to another variable does not copy the array; both names refer to the same one. And == compares references, so use Arrays.equals to compare contents:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = a; // same array
int[] c = a.clone(); // a real copy
b[0] = 100;
System.out.println(a[0] + " " + c[0]);
int[] d = {100, 2, 3};
System.out.println((a == d) + " " + Arrays.equals(a, d));
}
}100 1
false trueFinding the best element#
public class Main {
public static void main(String[] args) {
int[] sales = {340, 120, 560, 410, 90, 560};
int best = 0;
for (int i = 1; i < sales.length; i++) {
if (sales[i] > sales[best]) {
best = i;
}
}
System.out.println("Best day: " + (best + 1) + " with " + sales[best]);
}
}Best day: 3 with 560Using > (not >=) keeps the first best day when there is a tie.
Arrays or ArrayList?#
Use arrays when the size is fixed and known, or for primitive data where performance matters. Use ArrayList for most everyday collections.
Common mistakes#
Practice#
Practice exercise
Given int[] steps = {4200, 8100, 6700, 10200, 3900, 12000, 7600};, print the total, the average as a decimal, and how many days reached at least 8000 steps.
Show solution
public class Steps {
public static void main(String[] args) {
int[] steps = {4200, 8100, 6700, 10200, 3900, 12000, 7600};
int total = 0;
int goalDays = 0;
for (int s : steps) {
total += s;
if (s >= 8000) goalDays++;
}
System.out.println("Total: " + total);
System.out.printf("Average: %.2f%n", (double) total / steps.length);
System.out.println("Goal reached on " + goalDays + " days");
}
}Total: 52700
Average: 7528.57
Goal reached on 3 daysPractice exercise
Reverse int[] a = {1, 2, 3, 4, 5, 6}; in place by swapping elements from both ends, then print it with Arrays.toString.
Show solution
import java.util.Arrays;
public class Reverse {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6};
for (int left = 0, right = a.length - 1; left < right; left++, right--) {
int temp = a[left];
a[left] = a[right];
a[right] = temp;
}
System.out.println(Arrays.toString(a));
}
}[6, 5, 4, 3, 2, 1]Key takeaway#
Finished this lesson?