Finding the second largest element in an array is a popular Java interview question. Let's solve this without using Arrays.sort()
or any built-in sorting method. This approach improves your understanding of array logic and comparison operations.
🧮 Logic
We maintain two variables: first and second to track the largest and second largest values while looping through the array.
✅ Java Program
public class SecondLargestInArray {
public static void main(String[] args) {
int[] arr = {12, 35, 1, 10, 34, 1};
if (arr.length < 2) {
System.out.println("Array must contain at least two elements.");
return;
}
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num != first) {
second = num;
}
}
if (second == Integer.MIN_VALUE)
System.out.println("No second largest element found (all elements may be equal).");
else
System.out.println("Second largest element is: " + second);
}
}
🧠Interview Tip
Make sure to handle edge cases like arrays with all elements equal or arrays with fewer than 2 elements. Explaining your approach clearly is as important as writing correct code.
✅ Output
Second largest element is: 34
📌 Conclusion
We successfully found the second largest number in an array without using built-in sort functions. This logic is essential for interview prep and helps build strong fundamentals in Java array handling.