Latest :

Java : Find the Largest Number in an Array | Java Programs

Java code to find the largest number in an array – the following program has been written in multiple ways along with sample outputs as well. Two methods using scanner & general program.

Our problem statement is, to find the largest element in the given integer array. For this, we require the total number of elements in the array along with the values of each element.

Our expected output will be one element from the array which is the largest among the given set of elements.

To read our required inputs at runtime, we can make use of the Scanner class. Scanner class in Java is well known for reading inputs of any primitive datatype from the console screen at runtime. To make use of this class, we first create an object instantiating this class and call our desired method using this object.

Here, since all our inputs are of integer type, we will invoke the nextInt() method as follows and read the number of elements or size of array along with value of elements in the array:

Scanner sc=new Scanner(System.in);

System.out.println(“Enter number of elements “);

n=sc.nextInt();

int a[]=new int[n];

System.out.println(“Enter ” +n+” elements”);

for(int i=0;i<n;i++) {

a[i]=sc.nextInt();

}

Then, we make a call for a static method (largest) and pass the number of elements and the array as arguments. This part of the code can be written within main method too but, to make it reusable we make use of a separate static method.

Also, static method does not require instantiating object because despite being outside main method, it belongs to the class and not instance.

In this method, we initially take the element at zeroth index as maximum variable or largest number and store it in a variable (max).

Then, we traverse through the array from index one to the end and for every index, we check whether the value is greater than the value at max variable. If it is greater, then we replace the value of max with the value at that index.

As we reach the end of the array, the value in the max index will be our desired output which is, the largest element in the given array. This value is returned to the main method where it is displayed in the console screen using the println() method.

int max =a[0];

for(int i=1;i<n;i++) {

if(a[i]>=max) max=a[i];

}

return max;

Output:

Size of array is 6 and the 6 elements are [23, 45, 12, 344, 124, 50].

First max= a[0]  //23

45>max so, max=45

12<max so, max remains 45

344>max so, max=344

124<max so, max remains 344

50<max so, max remains 344

Therefore, 344 is our output.

x

Check Also

Java Program To Display Transpose Matrix | 3 Ways

Java Program to display/print the transpose of a given matrix.  The following program to print ...