In this tutorial, I am going to show you how to find smallest and largest element in a given array using Java Program.

Finding smallest and largest element in array :

Take an Array : {10,20,5,15,22,30,45,30,0,1}

Expected Output :

Smallest is : 0 and Largest is : 45


package com.onlinetutorialspoint.javaprograms;

public class FindSmallestAndLargestElementInArray {
    public static void main(String[] args) {
        int[] data = {10,20,5,15,22,30,45,30,0,1};
        findSmallestAndLargestElementInArray(data);
    }
    
    public static void findSmallestAndLargestElementInArray(int[] data) {
        if (data != null && data.length > 0) {
            int smallest = data[0];
            int largest = data[0];
            for (Integer element : data) {
                if (element < smallest) {
                    smallest = element;
                }

                if (element > largest) {
                    largest = element;
                }
            }

            System.out.println("Smallest: " + smallest + " largest: " + largest);
        }
    }
}

[box type=”success” align=”alignleft” class=”” width=”100%”]
Smallest: 0 largest: 45
[/box]
Happy Learning 🙂