Second Largest Element in Java: Explanation & Practice
Find the second largest element
Problem summary
Write a program that finds the second largest element in an array.
Starter code
public class Main {
public static void main(String[] args) {
int[] arr = {12, 35, 1, 10, 34, 1}; // Test case 1
// Find second largest
// Print: Second largest: <result>
}
}Expected output and test cases
- Second largest in array
Second largest: 34
- From [1,2,3,4,5]
Second largest: 4
- From [9,9,9,9]
Second largest: 9
Hints
- Track both largest and second largest
- Update both as you iterate
- Handle duplicates carefully
Related Arrays exercises
Practice all Arrays exercises · Run this idea in the Java compiler