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:
- Validate the input and reject a
nullor empty array. - Store the first element of the array in a variable called
largest. - Loop from index
1to the last index of the array. - Compare each element with
largest. - If the current element is greater than
largest, updatelargest. - After the loop finishes,
largestholds the maximum value. - Return
largestto 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.
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
ifstatement rejects anullor empty array by throwing anIllegalArgumentException. This keeps the rest of the method simple because we knownumbers[0]is safe to read. - Seed value. We set
largest = numbers[0]. Starting from the first real element, rather than fromInteger.MIN_VALUE, means the code behaves correctly even if every element is negative. - Loop from index 1. Index
0is already inlargest, so theforloop starts ati = 1. That saves one redundant comparison on every call. - Update when needed. If
numbers[i]is strictly greater thanlargest, we overwritelargest. Using>instead of>=avoids unnecessary writes when there are duplicates of the current maximum. - Return. After the loop,
largestholds 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:
The largest element in the array is: 89Example 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:
The largest element in the array is: -3Example 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:
The largest element in the array is: 7Additional Considerations
- Time complexity:
O(n). We visit each of thenelements exactly once, so the running time grows linearly with the size of the array. - Space complexity:
O(1). The method uses a singleintvariable 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 asInteger.MIN_VALUEor wrap the result inOptionalInt, 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 thelargestvariable to match. Fordouble, be aware thatDouble.NaNcan 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
largestIndexand update it in the sameifblock whenever you updatelargest.
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.



