Skip to content
Java arrays 7 min read

Array Programs

The best way to master arrays is to write real programs. This page walks you through the most important and commonly asked array problems in Java — each one builds your intuition and prepares you for interviews and day-to-day coding.

1. Find the Maximum and Minimum Element

Scan through the array once, tracking the largest and smallest values you’ve seen.

public class MinMax {
    public static void main(String[] args) {
        int[] nums = {4, 17, 2, 9, 31, 6};

        int max = nums[0];
        int min = nums[0];

        for (int n : nums) {
            if (n > max) max = n;
            if (n < min) min = n;
        }

        System.out.println("Max: " + max);
        System.out.println("Min: " + min);
    }
}

Output:

Max: 31
Min: 2

Tip: Always initialize max and min to the first element — not 0 or Integer.MIN_VALUE — so the logic works correctly for arrays that contain only negative numbers.


2. Calculate the Sum and Average

public class SumAverage {
    public static void main(String[] args) {
        int[] marks = {72, 85, 91, 68, 79};

        int sum = 0;
        for (int m : marks) {
            sum += m;
        }

        double average = (double) sum / marks.length;
        System.out.println("Sum: " + sum);
        System.out.printf("Average: %.2f%n", average);
    }
}

Output:

Sum: 395
Average: 79.00

The cast to double before the division is important — without it, Java performs integer division and truncates the decimal part.


3. Reverse an Array (In-Place)

You can reverse an array without creating a second one by swapping elements from both ends toward the middle. See the dedicated Reverse an Array page for more approaches.

public class ReverseArray {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};

        int left = 0, right = arr.length - 1;
        while (left < right) {
            int temp = arr[left];
            arr[left]  = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }

        for (int x : arr) System.out.print(x + " ");
    }
}

Output:

50 40 30 20 10

4. Check Whether an Array Is Sorted

public class IsSorted {
    public static void main(String[] args) {
        int[] a = {1, 3, 5, 7, 9};
        int[] b = {1, 3, 2, 7, 9};

        System.out.println("a sorted: " + isSorted(a));
        System.out.println("b sorted: " + isSorted(b));
    }

    static boolean isSorted(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1]) return false;
        }
        return true;
    }
}

Output:

a sorted: true
b sorted: false

Scan every element until you find the target. Works on unsorted arrays.

public class LinearSearch {
    public static void main(String[] args) {
        int[] data = {5, 13, 7, 22, 3, 18};
        int target = 22;

        int index = -1;
        for (int i = 0; i < data.length; i++) {
            if (data[i] == target) {
                index = i;
                break;
            }
        }

        if (index != -1) {
            System.out.println("Found at index: " + index);
        } else {
            System.out.println("Not found");
        }
    }
}

Output:

Found at index: 3

Note: Linear search is O(n). If your array is sorted and large, use Arrays.binarySearch() for O(log n) performance.


6. Binary Search (on a Sorted Array)

Binary search repeatedly halves the search range. The array must be sorted first.

public class BinarySearch {
    public static void main(String[] args) {
        int[] sorted = {2, 5, 9, 14, 21, 38, 55};
        int target = 21;

        int low = 0, high = sorted.length - 1, result = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2; // avoids integer overflow
            if (sorted[mid] == target) {
                result = mid;
                break;
            } else if (sorted[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        System.out.println(target + " found at index: " + result);
    }
}

Output:

21 found at index: 4

Tip: Use mid = low + (high - low) / 2 instead of (low + high) / 2 to prevent integer overflow when low and high are both large.


7. Remove Duplicates from a Sorted Array

When the array is sorted, duplicates are adjacent. Walk through once and copy only new values.

import java.util.Arrays;

public class RemoveDuplicates {
    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 3, 3, 4, 5, 5};

        int writeIndex = 1;
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] != arr[i - 1]) {
                arr[writeIndex++] = arr[i];
            }
        }

        System.out.println(Arrays.toString(Arrays.copyOf(arr, writeIndex)));
    }
}

Output:

[1, 2, 3, 4, 5]

8. Bubble Sort

Bubble sort is simple to understand and a classic for learning. It’s O(n²) so not suitable for large datasets, but perfect for building intuition about sorting algorithms.

import java.util.Arrays;

public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};

        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < n - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j]   = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) break; // already sorted — early exit
        }

        System.out.println(Arrays.toString(arr));
    }
}

Output:

[11, 12, 22, 25, 34, 64, 90]

Note: The swapped flag makes this an adaptive sort — if no swaps occurred during a pass, the array is already sorted and you can exit early.


9. Count Even and Odd Numbers

public class EvenOddCount {
    public static void main(String[] args) {
        int[] nums = {3, 8, 12, 7, 5, 20, 1, 16};

        int even = 0, odd = 0;
        for (int n : nums) {
            if (n % 2 == 0) even++;
            else odd++;
        }

        System.out.println("Even: " + even);
        System.out.println("Odd:  " + odd);
    }
}

Output:

Even: 4
Odd:  4

10. Merge Two Sorted Arrays

Merging two sorted arrays into one sorted array is the key step inside Merge Sort.

import java.util.Arrays;

public class MergeSorted {
    public static void main(String[] args) {
        int[] a = {1, 3, 5, 7};
        int[] b = {2, 4, 6, 8};
        int[] merged = new int[a.length + b.length];

        int i = 0, j = 0, k = 0;
        while (i < a.length && j < b.length) {
            if (a[i] <= b[j]) merged[k++] = a[i++];
            else               merged[k++] = b[j++];
        }
        while (i < a.length) merged[k++] = a[i++];
        while (j < b.length) merged[k++] = b[j++];

        System.out.println(Arrays.toString(merged));
    }
}

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

11. Find Second Largest Element

Avoid sorting (O(n log n)) — do it in a single O(n) pass.

public class SecondLargest {
    public static void main(String[] args) {
        int[] arr = {12, 35, 1, 10, 34, 1};

        int first = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;

        for (int n : arr) {
            if (n > first) {
                second = first;
                first = n;
            } else if (n > second && n != first) {
                second = n;
            }
        }

        if (second == Integer.MIN_VALUE) {
            System.out.println("No second largest element");
        } else {
            System.out.println("Second largest: " + second);
        }
    }
}

Output:

Second largest: 34

12. Rotate an Array Left by k Positions

import java.util.Arrays;

public class RotateLeft {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        int k = 3;
        int n = arr.length;
        k = k % n; // handle k >= n

        int[] result = new int[n];
        for (int i = 0; i < n; i++) {
            result[i] = arr[(i + k) % n];
        }

        System.out.println(Arrays.toString(result));
    }
}

Output:

[4, 5, 6, 7, 1, 2, 3]

Under the Hood

Understanding what happens at the JVM level helps you write faster code:

  • Arrays are objects. Every Java array is a heap-allocated object with a length field. The JVM represents primitive arrays (like int[]) as contiguous blocks of memory — extremely cache-friendly.
  • ArrayIndexOutOfBoundsException is thrown by the JVM itself at the bytecode level whenever an index is negative or >= length. There is no performance penalty for normal in-bounds access on modern HotSpot because the JIT eliminates redundant bounds checks in tight loops.
  • Time complexity recap:
OperationUnsorted ArraySorted Array
Access by indexO(1)O(1)
Linear searchO(n)O(n)
Binary searchN/AO(log n)
Bubble sortO(n²)O(n) best
Arrays.sort()O(n log n)
  • Arrays.sort() uses a Dual-Pivot Quicksort for primitives and TimSort for objects — both are significantly faster than the hand-rolled bubble sort shown above. Prefer the library method in production; roll your own only to learn or when you have specific constraints. See the Arrays Utility Class page for the full API.

  • Arrays — foundations: declaration, initialization, and indexing
  • Arrays Utility Classsort(), binarySearch(), copyOf() and more built-in helpers
  • Reverse an Array — in-place and extra-array approaches explained in depth
  • for-each Loop — the clean way to iterate over arrays used throughout these examples
  • Sorting Collections — sorting Lists and custom objects with Comparator
  • Array of Objects — apply these same patterns to arrays of custom class instances
Last updated June 13, 2026
Was this helpful?