Java program to find the second largest element in an array

Finding the second largest element in an array is a common programming problem that helps to deepen your understanding of array manipulation and traversal. Below is a detailed Java program to find the second largest element in an array.

Java Program to Find the Second Largest Element in an Array

import java.util.Scanner;

public class SecondLargestElementInArray {
    public static void main(String[] args) {
        // Create a Scanner object to read input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter the size of the array
        System.out.print("Enter the size of the array: ");
        int size = scanner.nextInt();

        // Create an array of the given size
        int[] array = new int[size];

        // Prompt the user to enter the elements of the array
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < size; i++) {
            array[i] = scanner.nextInt();
        }

        // Find the second largest element in the array
        int secondLargest = findSecondLargestElement(array);

        // Print the second largest element
        if (secondLargest != Integer.MIN_VALUE) {
            System.out.println("The second largest element in the array is: " + secondLargest);
        } else {
            System.out.println("There is no second largest element in the array.");
        }
    }

    // Method to find the second largest element in an array
    public static int findSecondLargestElement(int[] array) {
        // Initialize the largest and second largest to minimum possible values
        int largest = Integer.MIN_VALUE;
        int secondLargest = Integer.MIN_VALUE;

        // Traverse through the array to find the largest and second largest elements
        for (int i = 0; i < array.length; i++) {
            if (array[i] > largest) {
                secondLargest = largest;
                largest = array[i];
            } else if (array[i] > secondLargest && array[i] != largest) {
                secondLargest = array[i];
            }
        }

        return secondLargest;
    }
}
Java program to find the second largest element in an array
Java program to find the second largest element in an array

Explanation of the Code

Let’s break down the program step-by-step to understand how it works.

  1. Importing the Scanner Class: We import the Scanner class from the java.util package to read input from the user.
import java.util.Scanner;

2. Creating the Main Class: We create a public class named SecondLargestElementInArray. In Java, the class name should match the filename.

public class SecondLargestElementInArray {

3. Main Method: The main method is the entry point of the program. Inside this method, we will write the code to find the second largest element in an array.

public static void main(String[] args) {

4. Creating a Scanner Object: We create a Scanner object to read input from the user.

Scanner scanner = new Scanner(System.in);

5. Reading the Size of the Array: We prompt the user to enter the size of the array and store this value in a variable.

System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();

6. Creating an Array: We create an array of the given size.

int[] array = new int[size];

7. Reading the Elements of the Array: We prompt the user to enter the elements of the array and store these values in the array.

System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
    array[i] = scanner.nextInt();
}

8. Finding the Second Largest Element: We call the findSecondLargestElement method to find the second largest element in the array. The result is stored in a variable secondLargest.

int secondLargest = findSecondLargestElement(array);

9. Printing the Second Largest Element: We print the second largest element in the array. If no second largest element is found (all elements are the same), we print a corresponding message.

if (secondLargest != Integer.MIN_VALUE) {
    System.out.println("The second largest element in the array is: " + secondLargest);
} else {
    System.out.println("There is no second largest element in the array.");
}

10. Method to Find the Second Largest Element in an Array: The findSecondLargestElement method finds the second largest element in the given array. This method works by maintaining two variables to keep track of the largest and second largest elements as it traverses the array.

public static int findSecondLargestElement(int[] array) {
    // Initialize the largest and second largest to minimum possible values
    int largest = Integer.MIN_VALUE;
    int secondLargest = Integer.MIN_VALUE;

    // Traverse through the array to find the largest and second largest elements
    for (int i = 0; i < array.length; i++) {
        if (array[i] > largest) {
            secondLargest = largest;
            largest = array[i];
        } else if (array[i] > secondLargest && array[i] != largest) {
            secondLargest = array[i];
        }
    }

    return secondLargest;
}

Explanation of the findSecondLargestElement Method

  1. Initializing the Largest and Second Largest Elements: We initialize two variables, largest and secondLargest, to Integer.MIN_VALUE to ensure they are updated correctly when we start comparing elements in the array.
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;

2. Traversing the Array: The for loop iterates through each element of the array. In each iteration, we compare the current element with largest and secondLargest.

for (int i = 0; i < array.length; i++) {

3. Updating the Largest and Second Largest Elements: If the current element is greater than largest, we update secondLargest to be largest and then update largest to be the current element. If the current element is not equal to largest but is greater than secondLargest, we update secondLargest to be the current element.

if (array[i] > largest) {
    secondLargest = largest;
    largest = array[i];
} else if (array[i] > secondLargest && array[i] != largest) {
    secondLargest = array[i];
}

4. Returning the Second Largest Element: After the loop finishes, we return the secondLargest variable, which now holds the second largest element in the array.

return secondLargest;

Running the Program

To run the program, follow these steps:

  1. Save the code in a file named SecondLargestElementInArray.java.
  2. Open a command prompt or terminal and navigate to the directory where you saved the file.
  3. Compile the program using the following command:
javac SecondLargestElementInArray.java

4. Run the compiled program using the following command:

java SecondLargestElementInArray

5. Follow the prompts to enter the size and elements of the array. The program will display the second largest element in the array.

Example Output

If you run the program and enter the following input:

Enter the size of the array: 5
Enter the elements of the array:
10
45
32
67
29

The output will be:

The second largest element in the array is: 45

What did we learn from this article?

Finding the second largest element in an array is a useful exercise for understanding array manipulation and traversal in Java. This Java program demonstrates how to find the second-largest element by maintaining two variables to keep track of the largest and second-largest elements as it iterates through the array. By practicing such basic programs, you can enhance your problem-solving skills and gain confidence in your ability to write efficient Java code. Keep practicing and exploring more problems to further improve your programming skills.

Leave a Comment