Write a program to find second largest number in an array in java

Write a program to find second largest number in an array in java. 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. The Java Program to Find the Second Largest and Smallest Elements in an Array source code

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