Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to find the second largest number in an array in Java

Harsh Jain

In this shot, we are going to discuss on how to find the second largest number in an array in Java. The second largest number in the array is the number that is less than the largest number present in the array and greater than all the other numbers present in the array.

Let’s understand with the help of an example. Suppose the array contains {11, 67, 88, 53, 2, 72} elements. Here the second largest number is 72 which is less than the largest number, 88, in the array and greater than all the other elements present in the array, i.e., 11,67,53, and 2.

Solution approach

We will use the Arrays.sort() method from the java.util package. The Arrays.sort() method sorts the elements of the array in increasing order. This method will accept the array which needs to be sorted and return the sorted array.

Code

Let’s have a look at the code below.

To run the code, the user needs to pass two inputs:

  • The number of elements (N) in the array.
  • The (N) elements of the array.
  • Input format: 5 1 2 3 4 7, where 5 is the number of elements in the array and 1 2 3 4 7 are the elements in that array.
import java.util.*;
class Main
{
  public static void main(String[] args)
  {
    Scanner sc=new Scanner(System.in);

    int n=sc.nextInt();
    int a[]=new int[n];

    for(int i=0;i<n;i++)
      a[i]=sc.nextInt();

    Arrays.sort(a);
    System.out.print("The second largest number: "+a[n-2]);
  }
}

Enter the input below

Explanation

  • In line 1 we imported the required package.

  • In line 2 we made a class Main.

  • In line 6 we make an object of the Scanner class to use the methods available in it.

  • In line 8 we read the input by the user and store it in a variable of int data type. This is basically the number of elements the user wants to pass in the array.

  • In line 9 we declared an integer array of size input by the user.

  • In lines 11 and 12 we use a for loop to get the input of elements for every index of the array.

  • In line 14 we sorted the array by using the Arrays.sort() method so that the array gets arranged in increasing order of numbers. We obtained the array in sorted form now in which the largest number exists at the last index i.e., (n - 1) and the second largest number exists at one index previous to the last index i.e., (n - 2).

  • In line 16 we printed the result by accessing the value of index (n - 2) of the second largest number along with a message.

Note: Arrays have 0-based indexing. So the first element is at index 0 and the last element is at index (n - 1).

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring