Java Program to find second largest number in an array


In this program, You will learn how to find second largest number in an array in Java.


List is: 1 2 3 4 5

Second largest number is : 4


Example: How to find second largest number in an array in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        Scanner s = new Scanner(System.in);
        int a[] = new int[100];
        int n, largest = 0, slargest = -1;

        System.out.print("Enter Size of an Array :");
        n = s.nextInt();

        System.out.print("\nEnter Array Elements :");

        for (int i = 0; i < n; i++) {
            a[i] = s.nextInt();
        }
        for (int i = 0; i < n; i++) {
            if (largest <= a[i]) {
                largest = a[i];
            }
        }

        for (int i = 0; i < n; i++) {
            if (slargest <= a[i] && a[i] < largest) {
                slargest = a[i];
            }
        }

        System.out.print("\nSecond Largest Number :" + slargest);        
    }
}

Output:

Enter Size of an Array :5
Enter Array Elements :44 55 74 8 34
Second Largest Number :55