Here’s a Java program to find the second largest number in an array:
import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args) {
int[] arr = new int[5];
Scanner scanner = new Scanner(System.in);
System.out.println("Enter 5 numbers: ");
for (int i = 0; i < 5; i++) {
arr[i] = scanner.nextInt();
}
int secondLargest = findSecondLargest(arr);
System.out.println("Second largest number in the array: " + secondLargest);
}
public static int findSecondLargest(int[] arr) {
int largest = arr[0];
int secondLargest = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
}
In this program, we first create an integer array of size 5 and take user input for its elements using a for loop. We then call the `findSecondLargest()` method to find the second largest number in the array.
The `findSecondLargest()` method takes an integer array as a parameter and returns the second largest number in the array. We first initialize two variables `largest` and `secondLargest` to the first element of the array. We then use a for loop to iterate over each element of the array. For each element, we check if it is greater than `largest`. If it is, then we update both `largest` and `secondLargest`. If it is not greater than `largest`, then we check if it is greater than `secondLargest` and not equal to `largest`. If it is, then we update `secondLargest`.
At the end of the program, we print out the second largest number in the array using the value returned by the `findSecondLargest()` method.