Home » Java programs » Java basic programs

Java program to find second largest element in an array

In this java program, we are reading an integer array of N elements and finding second largest element among them.
Submitted by Chandra Shekhar, on February 03, 2018

Given an array of N integers and we have to find its second largest element using Java program.


    Enter number of elements: 4
    Input elements: 45, 25, 69, 40

    Second largest element in: 45

Program to find second largest element from an array in java

import java.util.Scanner;

public class ExArraySecondLargest
    public static void main(String[] args) 
    	// intialise here.
        int n, max;
        // create object of scanner class.
        Scanner Sc = new Scanner(System.in);
        // enter total number of elements.
        System.out.print("Enter total number of elements you wants : ");
        n = Sc.nextInt();
        // creating array object.
        int a[] = new int[n];
        // enter the elements here.
        System.out.println("Enter all the elements:");
        for (int i = 0; i < n; i++) 
            a[i] = Sc.nextInt();
        for (int i = 0; i < n; i++) 
            for (int j = i + 1; j < n; j++) 
                if (a[i] > a[j]) 
                    max = a[i];
                    a[i] = a[j];
                    a[j] = max;
        System.out.println("The Second Largest Elements in the Array is :"+a[n-2]);


Enter total number of elements you wants : 4
Enter all the elements:
The Second Largest Elements in the Array is :55

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.