Java Program to Find the Second Largest and Smallest Elements in an Array
In this post, you will learn how to find the second largest and smallest elements in an array using the Java programming language in the easiest way. Firstly, we have declared and initialized an array and sorted the array using Arrays.sort() method. The element at the first and second last index is displayed, which is the second smallest and second largest element, respectively.
import java.util.Arrays;
public class SecondLargestAndSmallest {
public static void main(String[] args) {
int[] arr = {5, 7, 2, 10, 3, 8};
// Sort the array
Arrays.sort(arr);
// Get the second smallest element
int secondSmallest = arr[1];
// Get the second largest element
int secondLargest = arr[arr.length - 2];
System.out.println("Second Smallest Number: " + secondSmallest);
System.out.println("Second Largest Number: " + secondLargest);
}
}
Output of the above code:
Second Smallest Number: 3
Second Largest Number: 8
Code Explanation:
Sorting: The array is first sorted in ascending order using Arrays.sort(arr). This places the smallest element at the beginning and the largest at the end of the array.
Second Smallest Element: The second smallest element is at index 1.
Second Largest Element: The second largest element is at index arr.length - 2.
Related Articles
Number pattern programs in JavaJava program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Fibonacci series program in Java
Java program to check leap year
Java program to find factorial of a number