Java – Find Smallest Number of an Array
To find the smallest number in a Java array, scan the array from left to right and keep track of the smallest value seen so far. Whenever the current element is smaller than the stored value, update the stored value.
This approach works for integer and floating-point arrays, and it requires only one pass through the array. The examples below show the same minimum-value logic with a while loop, a regular for loop, and an enhanced for loop.
How to Find the Smallest Number in a Java Array
For an array such as {25, 86, 41, 97, 22, 34}, the minimum-finding process is simple:
- Start with a value that can safely be replaced by an array element.
- Visit each element in the array.
- Compare the current element with the value stored in
smallest. - If the current element is smaller, assign it to
smallest. - After the final comparison,
smallestcontains the minimum array value.
For an int array, one option is to initialize smallest with Integer.MAX_VALUE. Another common option, when the array is known to be non-empty, is to initialize it with the first element and begin checking from the second element.
int smallest = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < smallest) {
smallest = arr[i];
}
}
Initializing from arr[0] is useful because it also works naturally when every value is negative. It does, however, require the array to contain at least one element.
Example 1 – Find Smallest Number of Array using While Loop
In this example, we shall use Java While Loop, to find smallest number of given integer array.
How the While Loop Tracks the Smallest Integer
- Take an integer array with some elements.
- Initialize a variable
smallestwith the greatest value an integer variable can hold,Integer.MAX_VALUE. This ensures that thesmallestpicks the first element of the given array, in first iteration of the loop. - Take a variable
index. We shall use it to access elements of the array. Initializeindexwith zero. We shall start from the left of array. - Write a while loop that executes when
indexis less than length of the integer array. Incrementindexduring each iteration. - Inside while loop, check if
smallestis greater than this element. If so, then update thesmallestwith this element. Ifsmallestis not greater than this element, we are happy with existing value ofsmallest, nothing to do, so no else block required. - After the while loop execution is done, we end with the smallest element of array, in the variable
smallest.
Example.java
/**
* Java Program - Find Smallest Number of an Array
*/
public class Example {
public static void main(String[] args) {
//an array
int[] arr = {25, 86, 41, 97, 22, 34};
//initialize with largest possible value
int smallest = Integer.MAX_VALUE;
//find smallest element of array
int index=0;
while(index<arr.length) {
//check if smallest is greater than element
if(smallest>arr[index]) {
//update smallest
smallest=arr[index];
}
index++;
}
System.out.println("The smallest number is : "+ smallest);
}
}
Run the above Java program in your IDE or using Java command in command prompt. You shall get the following output in console.
Output
The smallest number is : 22
The program compares all six integers and leaves 22 in smallest. The same logic also works when the array contains duplicate values or negative integers.
Example 2 – Find Smallest 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 smallest floating point number using Java For Loop.
How the For Loop Finds the Minimum Float Value
- Take a floating point array with some elements.
- Initialize a variable
smallestwith the largest of the Float value,Float.MAX_VALUE. This ensures that thesmallestpicks the first element of the given array, in first iteration of the loop. - Take a variable
index. We shall use it to access elements of the array. Initializeindexwith zero in For Loop initialization part. We shall start from the left of array. - Write a for loop that executes when
indexis less than length of the integer array. Incrementindexduring each iteration. - Inside for loop, check if
smallestis greater than this element. If so, then update thesmallestwith this element. Ifsmallestis not greater than this element, we are happy with existing value ofsmallest, nothing to do, so no else block required. - After the for loop execution is done, we end with the smallest element of array, in the variable
smallest.
Example.java
/**
* Java Program - Find Smallest Number of an Array
*/
public class Example {
public static void main(String[] args) {
//an array
float[] arr = {2.5f, 6.9f, 4.1f, 9.7f, 2.2f, 3.4f};
//initialize with largest possible value
float smallest = Float.MAX_VALUE;
//find smallest element of array
for(int index=0; index<arr.length; index++) {
//check if smallest is greater than element
if(smallest>arr[index]) {
//update smallest
smallest=arr[index];
}
}
System.out.println("The smallest number is : "+ smallest);
}
}
Output
Run the above Java Program in your IDE or command prompt using Java command.
The smallest number is : 2.2
The for loop checks each float value once. The smallest value in the array is 2.2f, which is printed as 2.2.
Example 3 – Find Smallest Number of Array using Advanced For Loop
In this example, we shall take a double array and find the smallest number using Java Advanced For Loop.
How the Enhanced For Loop Compares Each Double Value
- Take a double array with some elements.
- Initialize a variable
smallestwith the largest of the Double value,Double.MAX_VALUE. This ensures that thesmallestpicks the first element of the given array, in first iteration of the loop. - Write an advanced for loop that iterates over each element of the double array.
- Inside for loop, check if
smallestis greater than this element. If so, then update thesmallestwith this element. Ifsmallestis not greater than this element, we are happy with existing value ofsmallest, nothing to do, so no else block required. - After the advanced for loop execution is done, we end with the smallest element of array, in the variable
smallest.
Example.java
/**
* Java Program - Find Smallest Number of an Array
*/
public class Example {
public static void main(String[] args) {
//an array
double[] arr = {2.5, 6.9, 4.1, 9.7, 2.2, 3.4};
//initialize with largest possible value
double smallest = Double.MAX_VALUE;
//find smallest element of array
for(double element : arr) {
//check if smallest is greater than element
if(smallest>element) {
//update smallest
smallest=element;
}
}
System.out.println("The smallest number is : "+ smallest);
}
}
Output
Run the above Java Program in your IDE or command prompt using Java command.
The smallest number is : 2.2
The enhanced for loop is convenient when the index itself is not needed. Each element is assigned to element, compared with smallest, and the minimum value remains after the loop ends.
Find the Smallest Value in a Java int Array with Arrays.stream()
For an int[], Java also provides a stream-based way to obtain the minimum. The min() operation returns an OptionalInt because an array may be empty.
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
int[] arr = {25, 86, 41, 97, 22, 34};
int smallest = Arrays.stream(arr)
.min()
.orElseThrow(() -> new IllegalArgumentException("Array must not be empty"));
System.out.println("The smallest number is : " + smallest);
}
}
Output
The smallest number is : 22
The loop-based versions are useful when learning the comparison logic or when more processing is needed during the scan. The stream version is concise when the task is simply to obtain the minimum value.
Handling Empty Arrays Before Finding the Minimum
An empty array has no smallest element. If your code initializes the minimum from arr[0], check the array length first; otherwise, accessing the first element causes an ArrayIndexOutOfBoundsException.
if (arr.length == 0) {
throw new IllegalArgumentException("Array must not be empty");
}
int smallest = arr[0];
When the array may also be null, check for null before reading arr.length.
if (arr == null || arr.length == 0) {
throw new IllegalArgumentException("Array must not be null or empty");
}
Time and Space Complexity of Finding the Minimum Array Element
To guarantee the smallest value in an unsorted array, every element must be examined. Therefore, the loop-based approach takes O(n) time for an array of n elements. It uses only a few variables in addition to the array, so the extra space requirement is O(1).
Sorting the entire array just to obtain the first element performs more work than necessary. A single linear scan is the direct approach when only the minimum value is required.
Choosing a Java Loop for the Smallest Array Element
- Use a
whileloop when you want explicit control over the index update. - Use a regular
forloop when the element index is useful. - Use an enhanced
forloop when you only need each value and do not need its position. - Use
Arrays.stream(...).min()when a concise minimum operation fits the surrounding code.
In this Java Tutorial, we learned how to find the smallest number of a given array, using different looping statements in Java.
TutorialKart.com