Java program to find largest number of an array


Consider below is the input array, where you want to find the largest number of an array.

arr[5] = {1, 1000, 100, 10000, 10}

You should get output as 10000 which is the largest number.

1. Java program to find the largest number of an array

public class LargestNumber {
    public static void main(String[] args) {
    int i;
    int arr[] = {1, 1000, 100, 10000, 10}; // initialize array
    
    for (i = 1; i < arr.length; i++) { // iterate forloop  for the length of the array
        if (arr[0] < arr[i]) // compare first element of the array with every other element
            arr[0] = arr[i]; // assign the largest number to arr[0]
    }
        System.out.println("Largest number of the array: "+ arr[0]);
    }
}

Run here

In the above program,

  • we have initialized the array with input.
  • Using for loop we are traversing array from second element till the last element of the array
  • Then we are comparing every element present in the array with the first element and then assigning the larger value to arr[0] variable
  • Printing the arr[0] which gives the largest value

Results

Largest number of the array:  10000

2. Java program to find the largest number of an array using max function

import java.util.Arrays; 

public class LargestNum {
    public static void main(String[] args) {
      int i;
      int arr[] = {1, 1000, 100, 10000, 10}; // initialize array
    
      int max = Arrays.stream(arr).max().getAsInt(); // using max function to find the largest number
      
      System.out.println("Largest number of the array: "+ max);
    }
}

Try yourself here by providing input in the stdin section

In the above program, we are using Array methods max function to find the largest number of the array and then getting the result as Integer and assigning the value to max variable.

Results

Largest number of the array:  10000