Java Program to find First and Second Largest Array Elements

Learn how to find first and second largest array elements in java. First, the array elements are sorted using the Arrays.sort() method, and then the first and second largest values are retrieved using their index positions.

Code Explanation (Step-by-Step)

  • Create an integer array containing multiple numbers.
  • Use the Arrays.sort() method to sort the array in ascending order.
  • Access the last index (numbers.length – 1) to get the first largest element.
  • Access the second last index (numbers.length – 2) to get the second largest element.
  • Print first largest and second largest numbers.
				
					import java.util.Arrays;

public class LargestArrayElements {

    public static void main(String[] args) {

        int[] numbers = {1, 34, 56, 78, 23, 52, 98, 60};

        // Sort the array in ascending order
        Arrays.sort(numbers);

        // Find first and second largest elements
        int firstLargest = numbers[numbers.length - 1];
        int secondLargest = numbers[numbers.length - 2];

        // Print the results
        System.out.println("First Largest Element: " + firstLargest);
        System.out.println("Second Largest Element: " + secondLargest);
    }
}
				
			

Output :-
Largest Number value :- 98
Second Largest Number value :- 78

Find Second Largest Elements in Array using Java 8

				
					import java.util.Arrays;
import java.util.Comparator;

public class SecondLargestElement {
    public static void main(String[] args) {

        int[] numbers = {10, 45, 78, 23, 89, 56};

        Integer secondLargest = Arrays.stream(numbers)
                                      .boxed()
                                      .sorted(Comparator.reverseOrder())
                                      .skip(1)
                                      .findFirst()
                                      .get();

        System.out.println("Second Largest Element: " + secondLargest);
    }
}
				
			

Output :-
Second Largest Element: 78

FAQ
What is the largest element in an array?
The largest element is the maximum value present among all elements of the array.
Why use Arrays.sort() to find the largest number?
Sorting places elements in ascending order, making it easy to access the largest value at the last index.
Can we find the largest number without sorting?
Yes. By traversing the array once and comparing elements, the largest value can be found in O(n) time.
What happens if the array contains duplicate values?
The program still returns the largest value. If duplicates exist, the second largest value may be the same as the largest depending on the logic used.