Java program to find the second largest number in Array

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

Below are the approach which we will be follow to write our program:

  • In this program first we will take an array and take some elements as an input from users.
  • Then we will iterate the loop and then will compare elements till the and during comparison we will find the greatest and second greatest elements in a given array and print only second greatest number.
  • You can also follow a approach like first short an array in ascending order and then select the second greatest number in array.
  • Program is very similar to the find the largest two numbers in a given array. You may refer it

How our program will behave?

As we have already seen above our logic to find the second maximum number of an array.

Our program will take an array as an input.

And on the basis of inputs it will compare each elements and on the basis of comparison it will print second greatest elements from the array.

Java Program to print second largest number in an array

import java.util.*;  
public class Main {  
    public static void main(String[] args) {  
      Scanner sc = new Scanner(;
      System.out.println("Enter the size of array: ");
      int n = sc.nextInt();
      int arr[] = new int[n];
      System.out.println("Enter " +n+ " array elements ");
      for(int i=0; i<n; i++) {
         arr[i] = sc.nextInt();
      for(int i=n-1;i>1;i--){
            System.out.println(arr[i-1]+" is second largest element");


second largest number in an array java

Leave a Comment