π Find the Smallest Element in a Java Array
π§² Introduction
Finding the smallest element in an array is a basic yet essential problem in Java programming. This technique is commonly used in sorting algorithms, analytics applications, and system monitoring tools.
By the end of this guide, you’ll be able to:
- β Traverse an array in Java
- β Compare and store minimum values
- β Build efficient logic using simple loops
π» Java Program to Find the Smallest Element in an Array
public class SmallestElement {
public static void main(String[] args) {
int[] numbers = {45, 12, 78, 3, 89, 21};
int smallest = numbers[0]; // Assume first element is smallest
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < smallest) {
smallest = numbers[i]; // Update if smaller value found
}
}
System.out.println("Smallest element in the array is: " + smallest);
}
}
β Explanation Line-by-Line
int[] numbers = {45, 12, 78, 3, 89, 21};
π Defines an integer array with sample values.int smallest = numbers[0];
β Initializesmallest
with the first element of the array.for (int i = 1; i < numbers.length; i++)
β Start iterating from the second element (index 1).if (numbers[i] < smallest)
β Compare current element with the storedsmallest
.smallest = numbers[i];
β If smaller, update thesmallest
variable.System.out.println(...)
π Print the result to the console.
π‘ Tips
- Always initialize with
arr[0]
, not 0, to handle negative numbers. - Use
Arrays.sort()
if you’re allowed to modify the array.
π Summary
In this article, you learned how to:
- Traverse a Java array using a
for
loop - Compare elements to find the minimum value
- Use both manual and Java Stream methods
This logic is a foundation for many algorithms like sorting, searching, and data processing.
βFAQ
βCan I use Java Streams to find the smallest element?
Yes! Hereβs how:
int smallest = Arrays.stream(numbers).min().getAsInt();
This is concise and functional, available from Java 8 onward.
Share Now :