Common Java Array Programs with Examples
Introduction
The best way to become comfortable with arrays is to write programs with them. This tutorial goes through the common Java array programs that every beginner should be able to write - and which come up again and again in coding tests and interviews. We will start with finding the largest and smallest values, and the second largest. We will then reverse an array in place, and search it with a linear search. Next we will remove duplicates, count how often each value occurs, and rotate an array. Lastly, we will merge two sorted arrays, and find a missing number. For each program, we will look at the idea behind it before the code.
(Note - These programs use arrays from Java ArraysClick to read tutorial: Java Arrays Tutorial: Declare, Create and Initialize and loops from the for loop tutorialClick to read tutorial: Java for Loop Tutorial with Examples. For simplicity, each one is a
OUTPUT of the above code
Explanation of the code
OUTPUT of the above code
The loop stops when the indexes meet, so it works for both odd and even lengths - in an odd-length array, the middle element stays where it is.
3. Linear search
Idea: check each element in turn until the value is found, and return its index - or -1 if it is not there. Unlike binarySearch()Click to read tutorial: Java Arrays Class: sort, binarySearch, fill, copyOf, a linear search works on unsorted arrays.
OUTPUT of the above code
Note that strings are compared with
OUTPUT of the above code
Explanation of the code
OUTPUT of the above code
For values without a small fixed range, such as words, count with a
6. Rotating an array
Idea: rotating left by
OUTPUT of the above code
Rotating by 9 gives the same result as rotating by 2, because rotating a 7-element array by 7 brings it back to where it started.
7. Merging two sorted arrays
Idea: keep an index into each array. Repeatedly copy the smaller of the two current elements into the result, and move that array's index on. When one array runs out, copy the rest of the other. This is the heart of the merge sort algorithm.
OUTPUT of the above code
8. Finding the missing number
Idea: an array holds the numbers 1 to
OUTPUT of the above code
The sums are calculated as
(Note - These programs use arrays from Java ArraysClick to read tutorial: Java Arrays Tutorial: Declare, Create and Initialize and loops from the for loop tutorialClick to read tutorial: Java for Loop Tutorial with Examples. For simplicity, each one is a
static method called from main().)
1. Largest, smallest and second largest
Idea: keep the best value seen so far, starting with the first element, and compare every other element with it. For the second largest, keep two values, and push the old largest down to second place whenever a new largest is found.
Finding the largest, smallest and second largest values
//MinMax.java
public class MinMax {
static int[] minMax(int[] a) {
int min = a[0], max = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < min) min = a[i];
if (a[i] > max) max = a[i];
}
return new int[] {min, max};
}
static int secondLargest(int[] a) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int value : a) {
if (value > first) {
second = first;
first = value;
} else if (value > second && value != first) {
second = value;
}
}
return second;
}
public static void main(String[] args) {
int[] marks = {67, 92, 45, 92, 78, 88};
int[] result = minMax(marks);
System.out.println("Smallest = " + result[0] + ", largest = " + result[1]);
System.out.println("Second largest = " + secondLargest(marks));
}
}
Smallest = 45, largest = 92 Second largest = 88
- Starting with
a[0], rather than 0, makesminMax()work for arrays of negative numbers too. - The check
value != firstskips the duplicate 92, so the second largest is 88 - the largest distinct value below the maximum. - Each method looks at every element once, so it runs in time proportional to the array's length. Sorting the array first would also work, but does more work than needed.
Reversing an array in place
//ReverseArray.java
import java.util.Arrays;
public class ReverseArray {
static void reverse(int[] a) {
for (int left = 0, right = a.length - 1; left < right; left++, right--) {
int temp = a[left];
a[left] = a[right];
a[right] = temp;
}
}
public static void main(String[] args) {
int[] odd = {1, 2, 3, 4, 5};
int[] even = {10, 20, 30, 40};
reverse(odd);
reverse(even);
System.out.println(Arrays.toString(odd));
System.out.println(Arrays.toString(even));
}
}
[5, 4, 3, 2, 1] [40, 30, 20, 10]
Linear search
//LinearSearch.java
public class LinearSearch {
static int indexOf(String[] a, String target) {
for (int i = 0; i < a.length; i++) {
if (a[i].equals(target)) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
String[] fruits = {"mango", "apple", "kiwi", "banana"};
System.out.println("kiwi -> " + indexOf(fruits, "kiwi"));
System.out.println("cherry -> " + indexOf(fruits, "cherry"));
}
}
kiwi -> 2 cherry -> -1
equals(), not == - see == vs equals() vs compareTo()Click to read tutorial: Java String Comparison: == vs equals() vs compareTo().
4. Removing duplicates
Idea: in a sorted array, duplicates sit next to each other. Walk through the array, and copy each element forward only if it differs from the last one kept. The kept elements end up at the front of the array.
Removing duplicates from an array
//RemoveDuplicates.java
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
public class RemoveDuplicates {
static int[] unique(int[] input) {
int[] a = input.clone();
Arrays.sort(a);
if (a.length == 0) return a;
int kept = 1;
for (int i = 1; i < a.length; i++) {
if (a[i] != a[kept - 1]) {
a[kept++] = a[i];
}
}
return Arrays.copyOf(a, kept);
}
public static void main(String[] args) {
int[] values = {4, 2, 7, 2, 9, 4, 4, 1};
System.out.println("Unique, sorted : " + Arrays.toString(unique(values)));
List<Integer> boxed = List.of(4, 2, 7, 2, 9, 4, 4, 1);
System.out.println("Unique, in order seen : " + new LinkedHashSet<>(boxed));
}
}
Unique, sorted : [1, 2, 4, 7, 9] Unique, in order seen : [4, 2, 7, 9, 1]
keptcounts the unique values so far, and is also the position where the next unique value goes.a[kept++] = a[i]stores the value and then moveskepton.Arrays.copyOf(a, kept)trims the result to the unique values.- The method clones its input first, so the caller's array is not sorted as a side effect.
- When the original order must be kept, a
LinkedHashSetremoves duplicates in one step - it keeps only the first of each value, in the order they appeared.
Counting occurrences with a count array
//FrequencyCount.java
public class FrequencyCount {
public static void main(String[] args) {
int[] rolls = {3, 6, 1, 3, 3, 5, 6, 2, 3, 6};
int[] counts = new int[7]; // index 1 to 6; index 0 unused
for (int roll : rolls) {
counts[roll]++;
}
for (int face = 1; face <= 6; face++) {
System.out.println(face + ": " + "*".repeat(counts[face]) + " (" + counts[face] + ")");
}
}
}
1: * (1) 2: * (1) 3: **** (4) 4: (0) 5: * (1) 6: *** (3)
HashMap instead.
k moves each element k places towards the start, and the first k elements wrap around to the end. The element at index i of the result comes from index (i + k) % length of the original - the % operator does the wrapping.
Rotating an array to the left
//RotateArray.java
import java.util.Arrays;
public class RotateArray {
static int[] rotateLeft(int[] a, int k) {
int n = a.length;
int[] result = new int[n];
k = k % n; // rotating by n gives the same array
for (int i = 0; i < n; i++) {
result[i] = a[(i + k) % n];
}
return result;
}
public static void main(String[] args) {
int[] days = {1, 2, 3, 4, 5, 6, 7};
System.out.println("Left by 2 : " + Arrays.toString(rotateLeft(days, 2)));
System.out.println("Left by 9 : " + Arrays.toString(rotateLeft(days, 9)));
}
}
Left by 2 : [3, 4, 5, 6, 7, 1, 2] Left by 9 : [3, 4, 5, 6, 7, 1, 2]
Merging two sorted arrays
//MergeSorted.java
import java.util.Arrays;
public class MergeSorted {
static int[] merge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
result[k++] = (a[i] <= b[j]) ? a[i++] : b[j++];
}
while (i < a.length) result[k++] = a[i++];
while (j < b.length) result[k++] = b[j++];
return result;
}
public static void main(String[] args) {
int[] morning = {2, 5, 9, 14};
int[] evening = {1, 5, 6, 20, 25};
System.out.println(Arrays.toString(merge(morning, evening)));
}
}
[1, 2, 5, 5, 6, 9, 14, 20, 25]
n with one missing. The sum of 1 to n is n × (n + 1) / 2, so the missing number is that total minus the sum of the array. No sorting or searching is needed.
Finding the missing number in 1 to n
//MissingNumber.java
public class MissingNumber {
static int missing(int[] a) {
int n = a.length + 1;
long expected = (long) n * (n + 1) / 2;
long actual = 0;
for (int value : a) {
actual += value;
}
return (int) (expected - actual);
}
public static void main(String[] args) {
int[] tickets = {3, 7, 1, 2, 8, 4, 5};
System.out.println("Missing ticket: " + missing(tickets));
}
}
Missing ticket: 6
longs, so the method still works for very large n, where an int sum would overflow.
Summary
In this tutorial we wrote eight common array programs. We first found the largest, smallest and second largest values in a single pass, and reversed an array in place by swapping from both ends. We then searched an unsorted array with a linear search, removed duplicates from a sorted array and with a LinkedHashSet, and counted occurrences with a count array. Next we rotated an array using % to wrap around, and merged two sorted arrays. Lastly, we found a missing number with a sum formula. This completes the arrays module. In the next tutorial, we start on strings with Java String basics and immutabilityClick to read tutorial: Java String Basics and Why Strings Are Immutable.Java Fundamentals Tutorials
Java Arrays Class: sort, binarySearch, fill, copyOfClick to read tutorial: Java Arrays Class: sort, binarySearch, fill, copyOf Java String Basics and Why Strings Are ImmutableClick to read tutorial: Java String Basics and Why Strings Are Immutable Java Arrays Tutorial: Declare, Create and InitializeClick to read tutorial: Java Arrays Tutorial: Declare, Create and Initialize Multi-Dimensional and Jagged Arrays in JavaClick to read tutorial: Multi-Dimensional and Jagged Arrays in Java What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses
Java Arrays Class: sort, binarySearch, fill, copyOfClick to read tutorial: Java Arrays Class: sort, binarySearch, fill, copyOf Java String Basics and Why Strings Are ImmutableClick to read tutorial: Java String Basics and Why Strings Are Immutable Java Arrays Tutorial: Declare, Create and InitializeClick to read tutorial: Java Arrays Tutorial: Declare, Create and Initialize Multi-Dimensional and Jagged Arrays in JavaClick to read tutorial: Multi-Dimensional and Jagged Arrays in Java What is Java? History, Features, Editions and UsesClick to read tutorial: What is Java? History, Features, Editions and Uses