Java Program to find the second largest number in an array


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


List is: 1 2 3 4 5

The second-largest number is: 4

Example: How to find the second largest number in an array in java.

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("Enter 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("Second Largest number:" + slargest);
    }
}

Output:

Enter size of an array:5
Enter array elements:20 30 40 50 10
Second Largest number:40