Java Program to Find Largest Number in an Array

Java program to find largest number in an array. Find the largest two numbers in an array with a Java program. Enter the array’s size, followed by all of the array’s elements. Using double for loops, we first sort the array in decreasing order, yielding the first two elements as output. 

import java.util.Scanner;
public class Main
public static void main (String[] args)
Scanner scn = new Scanner (;
System.out.print("Enter no f elements you want in array");
int n = scn.nextInt();

int array[] = new int[n];
System.out.println("Enter all the elements");
for (int i = 0; i < array.length; i++)
array[i] = scn.nextInt();

int high1, high2, temp;

high1 = array[0];
high2 = array[1];

if (high1 < high2)
temp = high1;
high1 = high2;
high2 = temp;

for (int i = 2; i < array.length; i++)
if (array[i] > high1)
high2 = high1;
high1 = array[i];
else if (array[i] > high2 && array[i] != high1)
high2 = array[i];

System.out.println ("The highest number"+high1);
System.out.println ("The lowest number"+ high2);




Enter no f elements you want in array2
Enter all the elements
The highest number565
The lowest number45

array.length in Java

length: length is a final variable that applies to arrays. We may find out the size of the array by using the length variable. string. length(): The length() function is a final variable that applies to string objects. The length() function calculates the amount of characters in a string.

Array in Java

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

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.

Temp 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. Using this keyword we can execute java program to find largest number in an array.