Find Second Largest Element in Array in Java Without Built-in Methods

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.