Java Program to Find Second Largest Number in an Array

Java program to find second largest number in an array. finding the second largest and smallest elements in an array with 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
34
56
Second Largest34
Smallest34

Array in Java Program

In Java, an array is a collection of variables that are referred to by a single variable name and an index number. An array’s items are all elements. An array’s items must all be of the same type. An int array, for example, may store int values, whereas a String array can include strings.

If Else Statement in Java

When we use an if statement, we only run code if a condition is met. The else statement comes after an if statement and does not have a condition. The else statement is optional, and it will be executed only if the condition in the if statement is false.

Temporary Variable in Java

A temporary variable in computer programming is a variable with a brief lifetime, typically used to retain data that will be deleted quickly or before it can be placed in a more permanent memory location. Because it has a brief lifetime, it is typically stated as a local variable, i.e. a variable having a limited scope.

NextInt Function in Java

The java.util.nextInt(radix) function The Scanner class scans the next token of the input and returns it as an Int. If the translation is successful, the scanner moves beyond the matching input. If the argument radix is not supplied, it functions identically to nextInt(radix), with the radix presumed to be the default radix. Using this program we can execute the Java program to find second largest number in an array.