πŸ” Java How-To Examples
Estimated reading: 2 minutes 30 views

πŸ” 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];
    βœ… Initialize smallest 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 stored smallest.
  • smallest = numbers[i];
    βœ… If smaller, update the smallest 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Find Smallest Element

Or Copy Link

CONTENTS
Scroll to Top