Java – Find Largest Number of an Array

To find the largest number in a Java array, scan the array and keep track of the greatest value seen so far. Whenever the current element is greater than the stored value, update the stored value.

This is a linear search for the maximum element. It works with integer and floating-point arrays and requires only one pass through the array. The examples below show the logic with a while loop, a regular for loop, and an enhanced for loop.

How to Find the Largest Number in a Java Array

For an array such as {25, 86, 41, 97, 22, 34}, the maximum-finding process is:

  1. Choose an initial value for largest.
  2. Visit each element of the array.
  3. Compare the current element with largest.
  4. If the current element is greater, assign it to largest.
  5. After the final comparison, largest contains the maximum value.

For a non-empty array, a reliable general pattern is to initialize largest with the first element and start comparing from the second element. This works correctly even when every number in the array is negative.

</>
Copy
int largest = arr[0];

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

Example 1 – Find Largest Number of Array using While Loop

In this example, we shall use Java While Loop, to find largest number of given integer array.

How the While Loop Tracks the Largest Integer

  1. Take an integer array with some elements.
  2. Initialize a variable largest with the lowest of the integer value, Integer.MIN_VALUE. This ensures that the largest picks the first element of the given array, in first iteration of the loop.
  3. Take a variable index. We shall use it to access elements of the array. Initialize index with zero. We shall start from the left of array.
  4. Write a while loop that executes when index is less than length of the integer array. Increment index during each iteration.
    1. Inside while loop, check if largest is less than this element. If so, then update the largest with this element. If largest is not less than this element, we are happy with existing value of largest, nothing to do, so no else block required.
  5. After the while loop execution is done, we end with the largest element of array, in the variable largest.

Java Program

</>
Copy
/**
 * Java Program - Find Largest Number of an Array
 */

public class LargestNumberArray {
	public static void main(String[] args) {
		//an array
		int[] arr = {25, 86, 41, 97, 22, 34};
		
		//initialize with smallest possible value
		int largest = Integer.MIN_VALUE;
		
		//find largest element of array
		int index = 0;
		while( index < arr.length ) {
			//check if largest is smaller than element
			if( largest < arr[index] ) {
				//update largest
				largest = arr[index];
			}
			index++;
		}
		
		System.out.println("The largest number is : "+ largest);
	}
}

Output

Run the above Java program in your IDE or using Java command in command prompt.

The largest number is : 97

The loop checks all six integers. The value 97 is greater than every other element, so it remains in largest after the loop ends.

Example 2 – Find Largest Number of Array using For Loop

In our previous example, we have taken an integer array. So, In this example, we shall take a float array and find largest floating point number using Java For Loop.

How the For Loop Finds the Maximum Float Value

  1. Take a floating-point array with some elements.
  2. The existing program initializes largest with Float.MIN_VALUE. This works for the positive sample values shown here, but Float.MIN_VALUE is the smallest positive non-zero float, not the most negative float. For an array that may contain only negative values, initialize largest with the first array element instead.
  3. Use index to access each element, beginning at index 0.
  4. Continue the for loop while index is less than arr.length. During each iteration, compare arr[index] with largest and update largest when the current element is greater.
  5. After the loop, largest contains the maximum for the positive sample array.

Java Program

</>
Copy
/**
 * Java Program - Find Largest Number of an Array
 */

public class LargestNumberArray {
	public static void main(String[] args) {
		//an array
		float[] arr = {2.5f, 6.9f, 4.1f, 9.7f, 2.2f, 3.4f};
		//initialize with smallest possible value
		float largest = Float.MIN_VALUE;
		
		//find largest element of array
		for(int index = 0; index < arr.length; index++) {
			//check if largest is smaller than element
			if( largest < arr[index] ) {
				//update largest
				largest = arr[index];
			}
		}
		System.out.println("The largest number is : "+ largest);
	}
}

Output

Run the above Java Program in your IDE or command prompt using Java command.

The largest number is : 9.7

For the positive values used in this example, the maximum is 9.7f. One detail is important when adapting this code: Float.MIN_VALUE is the smallest positive non-zero float, not the most negative float. Therefore, initializing with Float.MIN_VALUE is not suitable for an array that may contain only negative values.

For a general-purpose float[], initialize the maximum from the first array element, after checking that the array is not empty:

</>
Copy
float[] arr = {-7.5f, -2.4f, -9.1f, -3.8f};

if (arr.length == 0) {
    throw new IllegalArgumentException("Array must not be empty");
}

float largest = arr[0];

for (int index = 1; index < arr.length; index++) {
    if (arr[index] > largest) {
        largest = arr[index];
    }
}

System.out.println("The largest number is : " + largest);

Output

The largest number is : -2.4

Example 3 – Find Largest Number of Array using Advanced For Loop

In this example, we shall take a double array and find largest number using Java Advanced For Loop.

How the Enhanced For Loop Compares Each Double Value

  1. Take a double array with some elements.
  2. The existing program initializes the double variable largest with Integer.MIN_VALUE. That value is below every number in this sample, so the example produces the expected result. For a general double[], initialize from arr[0] so values lower than Integer.MIN_VALUE are handled correctly.
  3. Use an enhanced for loop to visit each double value.
  4. When the current element is greater than largest, assign it to largest.
  5. After the loop, largest contains the maximum value for the sample array.

Java Program

</>
Copy
/**
 * Java Program - Find Largest Number of an Array
 */

public class LargestNumberArray {
	public static void main(String[] args) {
		//an array
		double[] arr = {2.5, 6.9, 4.1, 9.7, 2.2, 3.4};	
		//initialize with smallest possible value
		double largest = Integer.MIN_VALUE;
		
		//find largest element of array
		for(double element : arr) {
			//check if largest is smaller than element
			if( largest < element ) {
				//update largest
				largest = element;
			}
		}
		System.out.println("The largest number is : "+ largest);
	}
}

Output

Run the above Java Program in your IDE or command prompt using Java command.

The largest number is : 9.7

The enhanced for loop is useful when the index is not needed. In this particular example, Integer.MIN_VALUE is lower than every array value, so the result is 9.7. For a general double[], however, values can be lower than Integer.MIN_VALUE, so initializing from the first array element is safer.

Find the Maximum Value in a Java int Array with Arrays.stream()

Java streams provide a concise way to get the maximum value from an int[]. Calling Arrays.stream(arr).max() returns an OptionalInt because an empty array has no maximum.

</>
Copy
import java.util.Arrays;

public class LargestNumberArray {
    public static void main(String[] args) {
        int[] arr = {25, 86, 41, 97, 22, 34};

        int largest = Arrays.stream(arr)
                .max()
                .orElseThrow(() -> new IllegalArgumentException("Array must not be empty"));

        System.out.println("The largest number is : " + largest);
    }
}

Output

The largest number is : 97

The loop-based approach is useful when you want to understand or customize the comparison process. The stream form is shorter when the task is simply to obtain the maximum value.

Math.max() vs Finding the Largest Element in an Array

Math.max() compares two numeric values at a time. It does not accept an entire primitive array as a single argument. You can use it inside a loop to update the running maximum:

</>
Copy
int largest = arr[0];

for (int i = 1; i < arr.length; i++) {
    largest = Math.max(largest, arr[i]);
}

This has the same O(n) time complexity as an explicit if comparison because each array element still has to be examined.

Find the Largest Number in an ArrayList with Collections.max()

If the numbers are stored in an ArrayList rather than a primitive array, Collections.max() can return the largest element of a non-empty list.

</>
Copy
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

public class LargestNumberArray {
    public static void main(String[] args) {
        ArrayList<Integer> numbers =
                new ArrayList<>(Arrays.asList(25, 86, 41, 97, 22, 34));

        int largest = Collections.max(numbers);

        System.out.println("The largest number is : " + largest);
    }
}

Output

The largest number is : 97

Handling Empty Arrays Before Finding the Largest Number

An empty array has no largest element. If you use arr[0] as the initial maximum, check the array length before reading the first element. If the array reference itself may be null, check that condition first as well.

</>
Copy
if (arr == null || arr.length == 0) {
    throw new IllegalArgumentException("Array must not be null or empty");
}

int largest = arr[0];

Without the length check, reading arr[0] from an empty array causes an ArrayIndexOutOfBoundsException.

Time and Space Complexity of Finding the Largest Array Element

For an unsorted array of n elements, finding the largest value by scanning the array takes O(n) time because every element must be considered. The loop-based solution uses O(1) extra space.

Sorting the whole array just to obtain its maximum performs unnecessary work. A single pass is the direct approach when only the largest value is needed.

Largest Value vs Second Largest Value in a Java Array

The largest value and the second largest value are different tasks. The examples on this page track only one variable for the maximum. To find the second largest distinct value, you need to track at least two candidates and decide how duplicate maximum values should be handled.

For example, in {5, 9, 9, 7}, the largest value is 9. If the requirement is the second largest distinct value, the answer is 7, not the second occurrence of 9.

Choosing a Java Approach for the Maximum Array Value

  • Use a while loop when you want explicit control over the array index.
  • Use a regular for loop when the index is useful in the surrounding logic.
  • Use an enhanced for loop when you only need each value.
  • Use Arrays.stream(arr).max() for a concise maximum operation on supported primitive arrays.
  • Use Collections.max() when the values are in a non-empty collection such as an ArrayList<Integer>.

In this Java Tutorial, we learned how to find the largest number of a given array, using different looping statements in Java.