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.
๐ฅ Master Maximum & Comparison Logic in Java Arrays
Finding the second largest element in an array is a classic Java interview problem that tests your understanding of array traversal, comparisons, and edge-case handling. Strengthen your array problem-solving skills by exploring these closely related Java programs and interview resources.
๐ง Java Coding Round Questions
Practice array-based logic problems frequently asked in coding rounds.
✅ Check if Array Is Sorted
Verify array order before applying sorting-based approaches.
๐ Find Duplicates in Array
Handle duplicate values while finding unique maximums.
๐ซ Remove Duplicates from Array
Remove repeated elements before applying max-value logic.
๐ Reverse Array
Strengthen array traversal and index manipulation skills.
๐ Sort Array Without Built-ins
Sorting is one approach to find second-largest values.
๐ฆ Java Collections Interview Questions
Understand how collections simplify max-value problems.
๐ฏ Java Interview Questions (Freshers)
Common interview questions involving array comparisons.
๐งช Advanced Java Programs (Real-World)
Apply max and comparison logic in real-world Java scenarios.