Advertisement
Home Data Structure Arrays Find the Largest Element in an Array

Find the Largest Element in an Array

2
Advertisement

Title: Find the Largest Element in an Array

Finding the largest element in an array is one of the first problems every Java learner meets, and it quietly teaches habits that show up again in sorting, searching, and almost every coding interview. In this guide, we’ll build a clean, compilable Java program that scans an array once and returns its maximum value. You’ll learn the thinking behind the loop, see worked examples with positive, negative, and duplicate inputs, and understand the time and space trade-offs.

Understanding the Problem

Given an array of integers such as {12, 45, 7, 89, 23, 67, 4}, we want to find the single element whose value is greater than or equal to every other element. For that array, the answer is 89. The array may contain positive numbers, negative numbers, or duplicates, so our program must handle each of those cases without special-casing them.

We also need a plan for the edge case of an empty or null array. In that situation there is no largest element to return, so the method should refuse the input rather than silently returning 0, which would be a wrong answer for an array of negatives.

Approach

The simplest and most efficient idea is a single linear scan. We assume the first element is the largest, then walk through the rest of the array and update our guess whenever we find a bigger value. Here are the steps:

  1. Validate the input and reject a null or empty array.
  2. Store the first element of the array in a variable called largest.
  3. Loop from index 1 to the last index of the array.
  4. Compare each element with largest.
  5. If the current element is greater than largest, update largest.
  6. After the loop finishes, largest holds the maximum value.
  7. Return largest to the caller.

Java Program

Here is a full, compilable Java program that implements the approach above. The method findLargest is written as a static helper so you can drop it into any class and reuse it.

Java
public class LargestElementFinder {

    public static int findLargest(int[] numbers) {
        if (numbers == null || numbers.length == 0) {
            throw new IllegalArgumentException("Array must contain at least one element");
        }

        int largest = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > largest) {
                largest = numbers[i];
            }
        }
        return largest;
    }

    public static void main(String[] args) {
        int[] numbers = {12, 45, 7, 89, 23, 67, 4};
        int largest = findLargest(numbers);
        System.out.println("The largest element in the array is: " + largest);
    }
}

Explanation of the Program

The class LargestElementFinder contains two methods. The real work happens in findLargest, and main is just a driver that proves the method works.

  • Guard clause. The first if statement rejects a null or empty array by throwing an IllegalArgumentException. This keeps the rest of the method simple because we know numbers[0] is safe to read.
  • Seed value. We set largest = numbers[0]. Starting from the first real element, rather than from Integer.MIN_VALUE, means the code behaves correctly even if every element is negative.
  • Loop from index 1. Index 0 is already in largest, so the for loop starts at i = 1. That saves one redundant comparison on every call.
  • Update when needed. If numbers[i] is strictly greater than largest, we overwrite largest. Using > instead of >= avoids unnecessary writes when there are duplicates of the current maximum.
  • Return. After the loop, largest holds the maximum value in the array, which we return to the caller.

Examples

Example 1: Array with Positive Integers

Using the array from main, {12, 45, 7, 89, 23, 67, 4}, the loop updates largest from 12 to 45, then to 89, and never changes it again. The output is:

Java
The largest element in the array is: 89

Example 2: Array with Negative Integers

If we replace the input with {-5, -17, -3, -42, -8}, the correct answer is -3, the value closest to zero. Because we seeded largest with the first element rather than with 0, the method still returns the right answer:

Java
The largest element in the array is: -3

Example 3: Array with Duplicates

For an input like {7, 7, 7, 7}, every element equals the seed. The condition numbers[i] > largest is never true, so largest keeps its initial value of 7, which is the correct answer:

Java
The largest element in the array is: 7

Additional Considerations

  • Time complexity: O(n). We visit each of the n elements exactly once, so the running time grows linearly with the size of the array.
  • Space complexity: O(1). The method uses a single int variable regardless of how large the array is. No extra arrays, lists, or maps are allocated.
  • Empty and null input: The guard clause throws IllegalArgumentException. If you prefer, you can return a sentinel such as Integer.MIN_VALUE or wrap the result in OptionalInt, but throwing is the most honest choice for a method whose contract requires at least one element.
  • Different numeric types: For a long[], double[], or an array of a wrapper type, change the parameter and the largest variable to match. For double, be aware that Double.NaN can poison comparisons, so you may want to filter it out first.
  • Streams alternative: On Java 8 and later you can write Arrays.stream(numbers).max().getAsInt(). It is one line of code and does the same linear scan under the hood, but the explicit loop is often clearer for learners and plays nicer with debuggers.
  • Index of the largest: If you also need the position of the maximum, keep a second variable largestIndex and update it in the same if block whenever you update largest.

Conclusion

Finding the largest element in an array is a small problem, but it rewards careful thinking. By seeding our tracker with the first element, guarding against an empty array, and walking through the rest with a single for loop, we end up with a method that is linear in time, constant in space, and correct for positive, negative, and duplicate values. Try adapting the code to return the smallest element, the index of the maximum, or the top two values. Those tiny variations are a great way to lock in the pattern.

You can learn more about array problems in Java here: Arrays.