Java Program to Find Smallest Number in an Array

In this article, we are going to understand and implement a simple Java program, in which we are given an array, and we need to find the smallest number in the array. The Java program is very simple to do, provided that you are familiar with how to deal with arrays, and you know a little bit of basics about Java.

Java Program to Find Smallest Number in an Array

Calculating the smallest number in the array is very easy. We will first assume that the zeroth element of the array is the smallest element, and then throughout the array, we will compare and check if we can find a smaller element than the assumed smallest element. If we do so, we will keep on replacing it in the variable, and eventually by the end, we should have the smallest element from the array.

In the given video, you can find a detailed explanation regarding the same, along with the Java program.

Here is the Java program for finding the smallest number in the array –

Note: Please save the given program as Main.java.

public class Main {
public static void main(String[] args) {
int[] numbers = {12, 5, -6, 8, 0, 3, -10, 25, 15};

// We are assuming the first element as smallest
int smallest = numbers[0];

// Iterating through the array to find the smallest element
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
}
}

System.out.println(“The smallest number in the array is: ” + smallest);
}
}

Program Output –
The smallest number in the array is: -10


public class Main {
public static void main(String[] args) {
int[] numbers = {12, 5, -6, 8, 0, 3, -10, 25, 15}; // We are assuming the first element as smallest
int smallest = numbers[0]; // Iterating through the array to find the smallest element
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i];
}
} System.out.println("The smallest number in the array is: " + smallest);
}
}