Java Tutorial
🔍
Java ProgramsArraysFind Maximum Element

Find Maximum Element in Java

beginner·  Arrays  ·  Array

Problem

The maximum element of an array is the single largest value it contains.

Given an array of integers, find its maximum element.

Input
[4, 17, 9, 42, 8, 23]
Output
Maximum: 42

Java Program

Java
public class MaxInArray { public static void main(String[] args) { int[] arr = {4, 17, 9, 42, 8, 23}; int max = arr[0]; // assume the first element is the largest so far for (int num : arr) { if (num > max) max = num; // update whenever a bigger value is found } System.out.println("Maximum: " + max); } }

Output

Maximum: 42

Core Logic

A single pass through the array, keeping track of the biggest value seen so far, is all it takes.

How It Works
  1. 1max is initialized to the first element of the array, arr[0].
  2. 2A for-each loop visits every remaining element in turn.
  3. 3Each element is compared against max with if (num > max).
  4. 4Whenever a larger value is found, max is updated to that value.
  5. 5After the full pass, max holds the largest element in the array.
For [4, 17, 9, 42, 8, 23], max updates to 17 then 42, and stays 42 for the rest of the scan.
💡

Key Point: A single pass is enough — no sorting required, so this runs in O(n) time with O(1) extra space.

Key Concepts

for-each looprunning maximum

Approach 2: Java Streams

Java
import java.util.Arrays; public class MaxInArrayStream { public static void main(String[] args) { int[] arr = {4, 17, 9, 42, 8, 23}; // max() reduces the stream to its largest value, wrapped in an OptionalInt int max = Arrays.stream(arr).max().getAsInt(); System.out.println("Maximum: " + max); } }

Output

Maximum: 42

Core Logic

Streams already know how to do this — max() reduces the array down to its largest value in one call.

How It Works
  1. 1Arrays.stream(arr) converts the int[] into an IntStream.
  2. 2.max() reduces the stream down to the largest value, returning it wrapped in an OptionalInt.
  3. 3.getAsInt() unwraps the OptionalInt into a plain int.
Arrays.stream(new int[]{4, 17, 9, 42, 8, 23}).max() reduces the array down to 42.
💡

Key Point: OptionalInt is empty if the array is empty, so calling .getAsInt() without checking .isPresent() first would throw — worth remembering before using this on untrusted input.

Key Concepts

StreamArrays.stream()OptionalInt

Related Programs