Array Java Programs

Find the second largest number in Array

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

Below is the approach we will take to write our program:

  1. In this program first we will create an array and take some items as input from users.
  2. Then we will iterate the loop and then will loop items up to and while comparing we will find the largest and second largest items in a given array and print only second largest number.
  3. You can also use an approach like first short an array in ascending order and then select the second largest number in array.
  4. Program is very similar to find the largest two numbers in a given array. You can refer to it

How will our program behave?

As we have already seen above, our logic is to find the second largest number in an array.

Our program takes an array as input.

And based on the input it will compare each element and based on the comparison it will print the second largest elements from the array.

Print second largest number in Java array

import java.util.*;

public class ArrayExample {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		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();
		}
		Arrays.sort(arr);
		for (int i = n - 1; i > 1; i--) {
			if (arr[i] != arr[i - 1]) {
				System.out.println(arr[i - 1] + " is second largest element");
				break;
			}
		}
	}
}

Output

Enter the size of array: 
7
Enter 7 array elements 
2
5
3
6
8
9
41
9 is second largest element

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs