Array Java Programs

Find top two largest number in Array

In this tutorial you will learn how to write a Java program to find the largest two numbers in a given array.

Below is the procedure we will follow when writing our program:

In this program first we will create an array and take some elements as input from users.Then we will iterate the loop and then we will compare elements up to and while comparing we will find the largest two elements in a given array.You can also find an approach like first short an array in ascending order and then select the first two different elements of an array.

How will our program behave?

As we have already seen above, our logic is to find the first two largest elements of a given array.

Our program takes an array as input and, based on the input, compares the individual elements and, based on the comparison, outputs the two largest elements.

Find two 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] + " and " + arr[i - 1] + " is two maximum elements in array");
				break;
			}
		}
	}
}

Output

Enter the size of array: 
6
Enter 6 array elements 
2
3
54
56
3
7
56 and 54 is two maximum elements in array

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs