Find Smallest Element in an Array in Java
Problem
The minimum element of an array is the single smallest value it contains.
Given an array of integers, find its minimum element.
Java Program
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
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.
- 1
minis initialized to the first element of the array,arr[0]. - 2A for-each loop visits every remaining element in turn.
- 3Each element is compared against
minwithif (num < min). - 4Whenever a smaller value is found,
minis updated to that value. - 5After the full pass,
minholds the smallest element in the array.
[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.
Why: The array is scanned once from start to end, and only a single min variable is kept regardless of array size.
Key Concepts
Approach 2: Java 8
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
Core Logic
Streams already know how to do this — min() reduces the array down to its smallest value in one call.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.min()reduces the stream down to the smallest value, returning it wrapped in anOptionalInt. - 3
.getAsInt()unwraps theOptionalIntinto a plainint.
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.
Why: Arrays.stream().min() still visits every element once internally, and reduces down to a single OptionalInt without allocating any extra storage.