In this tutorial, you will learn how to write Java program to find second largest number in an array. This challenge appears frequently in coding interviews and practical applications: finding the second largest number in an array using Java. This task not only tests your understanding of array manipulation but also your ability to think algorithmically. Whether you’re a novice eager to learn Java or an experienced programmer brushing up on your skills, this tutorial will guide you through the process with a clear, step-by-step approach. By the end of this post, you’ll have a solid grasp of how to efficiently solve this common problem using Java.
Below are the approach which we will be follow to write our program:
- In this program first we will take an array and take some elements as an input from users.
- Then we will iterate the loop and then will compare elements till the and during comparison we will find the greatest and second greatest elements in a given array and print only second greatest number.
- You can also follow a approach like first short an array in ascending order and then select the second greatest number in array.
- Program is very similar to the find the largest two numbers in a given array. You may refer it
How our program will behave?
As we have already seen above our logic to find the second maximum number of an array.
Our program will take an array as an input.
And on the basis of inputs it will compare each elements and on the basis of comparison it will print second greatest elements from the array.
Example:
For the array elements 4 3 2 6 5 3,
The output should be 5 as 5 is a second largest number.
Java Program to print Second Largest number in an Array
Program 1: Using For loop and Array.sort()
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter " +n+ " array elements ");
for(int i=0; i<n; i++) {
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
for(int i=n-1;i>1;i--){
if(arr[i]!=arr[i-1]){
System.out.println(arr[i-1]+" is second largest element");
break;
}
}
}
}
Output:
Enter the size of array: 8 Enter 8 array elements 4 3 2 3 4 2 1 2 3 is second largest element
Program Explanations
- Input Collection: The program starts by prompting the user to enter the size of the array,
n
, using aScanner
object. It then initializes an array,arr
, of this size. - Filling the Array: The user is asked to enter
n
elements to populate the array. These elements are read from the standard input and stored sequentially inarr
. - Sorting the Array: The
Arrays.sort()
method is used to sort the array in ascending order. This ensures that the largest number is at the end of the array, and the second largest is just before it, provided all numbers are unique. - Finding the Second Largest: After sorting, the program iterates from the last element towards the beginning. It checks each element to see if it is different from the one that follows. When it finds the first element that is different from its successor, it prints this element as the second largest. The iteration starts from the second to last element and stops as soon as a unique element is found, using a
break
to exit the loop.
Program 2: One-pass Scan
This method uses a single traversal of the array. By maintaining two variables, one for the largest and one for the second largest, we can determine the second largest number in just one pass.
import java.util.*;
public class SecondLargestArrayElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of array: ");
int n = sc.nextInt();
if (n < 2) {
throw new IllegalArgumentException("Array must have at least two elements.");
}
int arr[] = new int[n];
System.out.println("Enter " +n+ " array elements ");
for(int i=0; i<n; i++) {
arr[i] = sc.nextInt();
}
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int number : arr) {
if (number > largest) {
secondLargest = largest;
largest = number;
} else if (number > secondLargest && number != largest) {
secondLargest = number;
}
}
System.out.println("The second largest number is: " + secondLargest);
}
}
Output
Enter the size of array: 6 Enter 6 array elements 4 3 2 6 5 3 The second largest number is: 5
Program Explanation
- Imports and Setup:
import java.util.*;
imports the Java Utilities package, which includes the Scanner class for reading user input.public class SecondLargestArrayElement
defines the class that contains the program.
- Main Method:
public static void main(String[] args)
is the entry point where the program starts execution.
- Input Handling:
- A
Scanner
object is instantiated to read input from the console. - The user is prompted to enter the size of the array
n
, and the program reads this integer.
- A
- Validation:
- The program checks if
n
is less than 2. If true, it throws anIllegalArgumentException
because you need at least two numbers to find the second largest.
- The program checks if
- Array Initialization:
- An integer array
arr
of sizen
is created. - The user is asked to enter
n
numbers to fill the array.
- An integer array
- Finding the Second Largest Number:
- Two variables,
largest
andsecondLargest
, are initialized toInteger.MIN_VALUE
. - The program iterates through each number in the array:
- If a number is greater than
largest
, thenlargest
is updated to this number, and the oldlargest
value is assigned tosecondLargest
. - If a number is between the current
largest
andsecondLargest
, thensecondLargest
is updated to this number.
- If a number is greater than
- Two variables,
- Output:
- After the loop, the value of
secondLargest
is printed, representing the second largest number in the array.
- After the loop, the value of