Java Program to Find Smallest and Largest Element in an Array

In this post, we will see how to find smallest and largest element in an array.


You are given an array of numbers. You need to find smallest and largest numbers in the array.


  • Initialise two variable largest and smallest with arr[0]
  • Iterate over array
    • If current element is greater than largest, then assign current element to largest.
    • If current element is smaller than smallest, then assign current element to smallest.
  • You will get smallest and largest element in the end.

Java code to find Smallest and Largest Element in an Array :

package org.arpit.java2blog;
Java program to Find Largest and Smallest Number in an Array 
public class FindLargestSmallestNumberMain {

      public static void main(String[] args) {
              //array of 10 numbers
              int arr[] = new int[]{12,56,76,89,100,343,21,234};
              //assign first element of an array to largest and smallest
              int smallest = arr[0];
              int largest = arr[0];
              for(int i=1; i< arr.length; i++)
                      if(arr[i] > largest)
                              largest = arr[i];
                      else if (arr[i] < smallest)
                              smallest = arr[i];
              System.out.println("Smallest Number is : " + smallest);
              System.out.println("Largest Number is : " + largest);            
When you run above program, you will get below output:
Largest Number is : 343
Smallest Number is : 12

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012