Practice Arrays in Java

Work with arrays including creation, traversal, searching, and sorting algorithms.

Work through 22 exercises with starter code, expected output, test cases, and hints.

How to learn Arrays

An array stores a fixed number of values of one component type. Indices run from zero through length - 1, and Java checks every access at runtime. Most array problems are not about syntax; they are about maintaining useful state while visiting each element once.

Before choosing an algorithm, ask whether order may change, whether extra storage is allowed, and whether the input can be empty. Those three answers distinguish an in-place two-pointer solution from a copy, a frequency map, or a sorting-based approach.

Recommended learning order

  1. Create and traverse: Learn literals, new arrays, default values, length, indexed loops, and enhanced for loops. Use an indexed loop when a position must be read or changed.
  2. Single-pass summaries: Compute sum, minimum, maximum, counts, and search results while keeping only the state needed so far.
  3. In-place transformations: Reverse and partition with left and right indices. Write the loop condition before the swap logic.
  4. Subarrays and matrices: Then learn prefix sums, fixed windows, variable windows, and row-by-row traversal of rectangular or jagged two-dimensional arrays.

Tested example: Reverse an array in place

Each iteration swaps one pair and moves both bounds inward. The loop stops when the bounds meet, so every element is touched at most once and no second array is needed.

import java.util.Arrays;

public class Main {
    static void reverse(int[] values) {
        for (int left = 0, right = values.length - 1; left < right; left++, right--) {
            int temporary = values[left];
            values[left] = values[right];
            values[right] = temporary;
        }
    }

    public static void main(String[] args) {
        int[] values = {2, 4, 6, 8};
        reverse(values);
        System.out.println(Arrays.toString(values));
    }
}

Expected output

[8, 6, 4, 2]

Change and run this example in the Java compiler

Common mistakes

  • Using index <= array.length; the last valid index is array.length - 1.
  • Assuming an empty array has a first element when initializing a minimum or maximum.
  • Changing an enhanced-for variable and expecting the corresponding array element to change.
  • Calling Arrays.asList on a primitive array and expecting a List<Integer>; it creates a one-element list containing the int[] object.

How to practice

Master traversal, aggregation, and linear search before attempting windows or prefix sums. State the time and extra-space cost after each solution. The longer arrays tutorial adds diagrams and variations; use the compiler page to test your own edge cases.

Exercises to do first

  • Array sum — Build the simplest single-pass accumulator and define the empty-array result.
  • Reverse array — Implement the two-pointer invariant used in the example.
  • Second largest — Track two distinct values without sorting the entire input.

Arrays exercises

  1. Declare and Print Array Java exercise — Create and display array elements
  2. Sum of Array Java exercise — Calculate the sum of array elements
  3. Find Maximum Java exercise — Find the largest element in an array
  4. Calculate Average Java exercise — Find the average of array elements
  5. Count Even Numbers Java exercise — Count even numbers in an array
  6. Linear Search Java exercise — Find an element in an array
  7. Reverse Array Java exercise — Reverse an array in place
  8. Second Largest Element Java exercise — Find the second largest element
  9. Remove Duplicates Java exercise — Remove duplicate elements from array
  10. Rotate Array Java exercise — Rotate array elements to the right
  11. Merge Sorted Arrays Java exercise — Merge two sorted arrays into one sorted array
  12. Bubble Sort Java exercise — Implement bubble sort algorithm
  13. Selection Sort Java exercise — Implement selection sort algorithm
  14. Binary Search Java exercise — Implement binary search on sorted array
  15. Find Pair with Sum Java exercise — Find two numbers that add up to target
  16. Maximum Subarray Sum Java exercise — Find the maximum sum of a contiguous subarray
  17. Leaders in Array Java exercise — Find all leaders in an array
  18. Equilibrium Index Java exercise — Find index where left sum equals right sum
  19. Wave Array Java exercise — Convert array to wave form
  20. Majority Element Java exercise — Find element appearing more than n/2 times
  21. Left Rotate Array Java exercise — Rotate array elements to the left by k positions
  22. Find Leaders Java exercise — Find elements greater than all elements to their right

Browse the complete Java practice path · Open the online Java compiler