Java program to find the second biggest and smallest number in the array

Java program to find the second biggest and smallest number in the array. Find the Second Largest and Smallest Elements in an Array with this Java Program. Enter the array’s size, followed by all of the array’s elements. We now sort the array in ascending order using the for loop and temp variable.

As a result, the first and second last elements are returned as output. The Java Program to Find the Second Largest and Smallest Elements in an Array source code is available here.

import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter no of elements you want in array");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Second Largest:"+a[n-2]);
System.out.println("Smallest:"+a[0]);
}
}

 

Output:

Enter no of elements you want in array 2
Enter all the elements
45
67
Second Largest:45
Smallest:45

How to use temp variable in java program

A temporary array persists only for the period of the data step in which it is defined. A temporary array can be used to store constant values used in calculations. There are no comparable variables to identify the array elements in a temporary array.