Find Second Largest Number in Array
Java program to find the second largest element in an array.
Last updated: 11 January 2026
Method 1: One Pass Iteration
Efficient O(n) approach.
Main.javaRun in Compiler →
public class SecondLargest {
public static void main(String[] args) {
int[] arr = {12, 35, 1, 10, 34, 1};
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}
if (secondLargest == Integer.MIN_VALUE)
System.out.println("There is no second largest element");
else
System.out.println("Second largest: " + secondLargest);
}
}Output:
Second largest: 34
Explanation
Maintain two variables: largest and secondLargest. Update them as we iterate.
Frequently Asked Questions
Try This Program
Copy this code and run it in our free online Java compiler.
Open Java Compiler