Java Program to find Second Largest Number in an Array

We can find the second largest number in an array in java by sorting the array and returning the 2nd largest number. Let’s see the full example to find the second largest number in java array.

  1. public class SecondLargestInArrayExample{  
  2. public static int getSecondLargest(int[] a, int total){  
  3. int temp;  
  4. for (int i = 0; i < total; i++)   
  5.         {  
  6.             for (int j = i + 1; j < total; j++)   
  7.             {  
  8.                 if (a[i] > a[j])   
  9.                 {  
  10.                     temp = a[i];  
  11.                     a[i] = a[j];  
  12.                     a[j] = temp;  
  13.                 }  
  14.             }  
  15.         }  
  16.        return a[total-2];  
  17. }  
  18. public static void main(String args[]){  
  19. int a[]={1,2,5,6,3,2};  
  20. int b[]={44,66,99,77,33,22,55};  
  21. System.out.println(“Second Largest: “+getSecondLargest(a,6));  
  22. System.out.println(“Second Largest: “+getSecondLargest(b,7));  
  23. }}  

Output:

Second Largest: 5
Second Largest: 77

Find 2nd Largest Number in Array using Arrays

Let’s see another example to get second largest element or number in java array using collections.

  1. import java.util.Arrays;  
  2. public class SecondLargestInArrayExample1{  
  3. public static int getSecondLargest(int[] a, int total){  
  4. Arrays.sort(a);  
  5. return a[total-2];  
  6. }  
  7. public static void main(String args[]){  
  8. int a[]={1,2,5,6,3,2};  
  9. int b[]={44,66,99,77,33,22,55};  
  10. System.out.println(“Second Largest: “+getSecondLargest(a,6));  
  11. System.out.println(“Second Largest: “+getSecondLargest(b,7));  
  12. }}  

Output:

Second Largest: 5
Second Largest: 77

Find 2nd Largest Number in Array using Collections

Let’s see another example to get second largest number in java array using collections.

  1. import java.util.*;  
  2. public class SecondLargestInArrayExample2{  
  3. public static int getSecondLargest(Integer[] a, int total){  
  4. List<Integer> list=Arrays.asList(a);  
  5. Collections.sort(list);  
  6. int element=list.get(total-2);  
  7. return element;  
  8. }  
  9. public static void main(String args[]){  
  10. Integer a[]={1,2,5,6,3,2};  
  11. Integer b[]={44,66,99,77,33,22,55};  
  12. System.out.println(“Second Largest: “+getSecondLargest(a,6));  
  13. System.out.println(“Second Largest: “+getSecondLargest(b,7));  
  14. }}  

Output:

Second Largest: 5
Second Largest: 77

Leave a Comment