1. Introduction

Finding the second-largest number in an array is a common programming task. This Java program will guide you through finding the second-largest number in a given array of integers.

2. Program Steps

1. Define a class named SecondLargest.

2. In the main method, initialize an array of integers.

3. Initialize two variables, firstMax and secondMax, to hold the largest and second largest numbers.

4. Iterate through the array to find the largest and second largest numbers.

5. Print the second largest number.

3. Code Program

public class SecondLargest { // Step 1: Define a class named SecondLargest

    public static void main(String[] args) { // Main method

        // Step 2: Initialize an array of integers
        int[] array = {10, 4, 3, 5, 7};

        // Step 3: Initialize firstMax and secondMax
        int firstMax = Integer.MIN_VALUE;
        int secondMax = Integer.MIN_VALUE;

        // Step 4: Iterate through the array
        for(int num : array) {
            if(num > firstMax) {
                secondMax = firstMax;
                firstMax = num;
            } else if(num > secondMax) {
                secondMax = num;
            }
        }

        // Step 5: Print the second largest number
        System.out.println("The second largest number is: " + secondMax);
    }
}

Output:

The second largest number is: 7

4. Step By Step Explanation

Step 1: A class named SecondLargest is defined.

Step 2: An array of integers is initialized with some values.

Step 3: Two integer variables firstMax and secondMax are initialized with the smallest integer value.

Step 4: The program iterates through the array. If the current number is greater than firstMax, secondMax is updated to the value of firstMax, and firstMax is updated to the current number. If the current number is greater than secondMax but not greater than firstMax, secondMax is updated to the current number.

Step 5: The value of secondMax, which holds the second largest number in the array, is printed.