This is a Java Program to Find the Largest Two Numbers in a Given Array.

Enter size of array and then enter all the elements of that array. Now we first sort the array in decreasing order using double for loops and hence get the first two elements as output.

Here is the source code of the Java Program to Find the Largest Two Numbers in a Given Array. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

import java.util.Scanner;

public class Largest_Numbers

`{`

public static void main(String[] args)

`{`

int n, l1, l2, temp;

Scanner s = new Scanner(System.in);

System.out.print("Enter no. of elements you want in array:");

n = s.nextInt();

if(n > 1)

`{`

int a[] = new int[n];

System.out.println("Enter all the elements:");

for(int i = 0; i < n ; i++)

`{`

a[i] = s.nextInt();

`}`

for(int i = 0; i < n; i++)

`{`

for(int j = i + 1; j < n; j++)

`{`

if(a[i] < a[j])

`{`

temp = a[i];

a[i] = a[j];

a[j] = temp;

`}`

`}`

`}`

System.out.println("Largest two numbers are:"+a[0]+" and "+a[1]);

`}`

`else`

`{`

System.out.println("Enter number greater than 1");

`}`

`}`

`}`

Output:

$ javac Largest_Numbers.java $ java Largest_Numbers Enter no. of elements you want in array:8 Enter all the elements: 5 3 7 9 2 3 9 10 Largest two numbers are:10 and 9

**Sanfoundry Global Education & Learning Series – 1000 Java Programs.**

Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms.