Java Program to Find the Second Largest Number in an Array

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

Introduction

Finding the second largest number in an array is a common task in programming, particularly in data analysis and algorithm development. This guide will show you how to create a Java program that finds the second-largest number in a given array of integers.

Problem Statement

Create a Java program that:

  • Takes an array of integers as input.
  • Finds and returns the second largest number in the array.
  • Handles arrays with duplicate values appropriately.

Example 1:

  • Input: [3, 5, 7, 1, 4]
  • Output: The second largest number is 5

Example 2:

  • Input: [10, 20, 20, 5, 8]
  • Output: The second largest number is 10

Solution Steps

  1. Initialize Two Variables: Use two variables to keep track of the largest and second largest numbers.
  2. Iterate Through the Array: Loop through the array to update the largest and second-largest values.
  3. Handle Edge Cases: Ensure that the program correctly handles arrays with less than two elements.
  4. Display the Result: Print the second largest number.

Java Program

Java Program to Find the Second Largest Number in an Array

import java.util.Scanner; /** * Java Program to Find the Second Largest Number in an Array * Author: https://www.javaguides.net/ */ public class SecondLargestNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Prompt the user for input System.out.print("Enter the number of elements in the array: "); int n = scanner.nextInt(); if (n < 2) { System.out.println("Array must contain at least two elements."); return; } int[] array = new int[n]; System.out.println("Enter the elements of the array:"); for (int i = 0; i < n; i++) { array[i] = scanner.nextInt(); } // Step 2: Find the second largest number int largest = Integer.MIN_VALUE; int secondLargest = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { if (array[i] > largest) { secondLargest = largest; largest = array[i]; } else if (array[i] > secondLargest && array[i] != largest) { secondLargest = array[i]; } } // Step 3: Display the result if (secondLargest == Integer.MIN_VALUE) { System.out.println("No second largest element found."); } else { System.out.println("The second largest number is " + secondLargest); } } } 

Explanation

  • Input: The program prompts the user to enter the number of elements in the array and the elements themselves.

  • Finding the Second Largest:

    • Two variables, largest and secondLargest, are initialized to the smallest possible integer value (Integer.MIN_VALUE).
    • As the program iterates through the array:
      • If the current element is greater than largest, secondLargest is updated to largest, and largest is updated to the current element.
      • If the current element is greater than secondLargest but not equal to largest, secondLargest is updated to the current element.
  • Edge Case Handling: If the array has fewer than two elements, the program immediately informs the user and terminates. If there is no second-largest number (e.g., all elements are the same), the program outputs an appropriate message.

  • Output: The program prints the second-largest number found in the array.

Output Example

Example 1:

Enter the number of elements in the array: 5 Enter the elements of the array: 3 5 7 1 4 The second largest number is 5 

Example 2:

Enter the number of elements in the array: 5 Enter the elements of the array: 10 20 20 5 8 The second largest number is 10 

Example 3:

Enter the number of elements in the array: 2 Enter the elements of the array: 5 5 No second largest element found. 

Explanation of Edge Cases:

  • Example 1: The array has distinct elements, and the second largest is correctly identified as 5.
  • Example 2: The array has duplicate elements, but the program correctly identifies the second largest as 10.
  • Example 3: The array has duplicate elements only, so no second largest is found.

Conclusion

This Java program efficiently finds the second-largest number in an array by maintaining two variables for the largest and second-largest values. The program handles arrays with duplicate elements and correctly outputs the second-largest number or an appropriate message if no such number exists. This approach is robust and can be applied to various scenarios where identifying the second-largest element is required.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare