Second Largest and Smallest Number in Java

Second biggest and smallest number in java. 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. 

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

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.

If Else Statement in Java

The if statement in Java is the most basic decision-making statement. It is used to determine if a certain statement or block of statements will be performed or not; that is, if a given condition is true, then a block of statements is executed; otherwise, it is not executed. 

The if/else statement expands on the if statement by stating an action to be taken if the if (true/false expression) is false. The if/else statement instructs the program to execute either the true or false code block, therefore something is always done with an if/else statement.