Java ProgramsArraysFind Smallest Element in an Array

Find Smallest Element in an Array in Java

beginner·  Arrays  ·  Array

Problem

The minimum element of an array is the single smallest value it contains.

Given an array of integers, find its minimum element.

Input
[12, 45, 3, 68, 22, 7]
Output
Minimum: 3

Java Program

Java
public class MinInArray { public static void main(String[] args) { int[] arr = {12, 45, 3, 68, 22, 7}; int min = arr[0]; // assume the first element is the smallest so far for (int num : arr) { if (num < min) min = num; // update whenever a smaller value is found } System.out.println("Minimum: " + min); } }

Output

Minimum: 3

Core Logic

A single pass through the array, keeping track of the smallest value seen so far, is the mirror image of finding the maximum.

How It Works
  1. 1min 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 min with if (num &lt; min).
  4. 4Whenever a smaller value is found, min is updated to that value.
  5. 5After the full pass, min holds the smallest element in the array.
For [12, 45, 3, 68, 22, 7], min updates to 12 then 3, and stays 3 for the rest of the scan.
💡

Key Point: Just like finding the maximum, a single pass is enough — no sorting required, so this runs in O(n) time with O(1) extra space.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: The array is scanned once from start to end, and only a single min variable is kept regardless of array size.

Key Concepts

for-each looprunning minimum

Approach 2: Java 8

Java
import java.util.Arrays; public class MinInArrayStream { public static void main(String[] args) { int[] arr = {12, 45, 3, 68, 22, 7}; // min() reduces the stream to its smallest value, wrapped in an OptionalInt int min = Arrays.stream(arr).min().getAsInt(); System.out.println("Minimum: " + min); } }

Output

Minimum: 3

Core Logic

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

How It Works
  1. 1Arrays.stream(arr) converts the int[] into an IntStream.
  2. 2.min() reduces the stream down to the smallest value, returning it wrapped in an OptionalInt.
  3. 3.getAsInt() unwraps the OptionalInt into a plain int.
Arrays.stream(new int[]{12, 45, 3, 68, 22, 7}).min() reduces the array down to 3.
💡

Key Point: OptionalInt is empty if the array is empty, so calling .getAsInt() without checking .isPresent() first would throw — the same caveat as finding the maximum this way.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: Arrays.stream().min() still visits every element once internally, and reduces down to a single OptionalInt without allocating any extra storage.

Key Concepts

StreamArrays.stream()OptionalInt

Related Programs