Java Program to find largest element in an array

Given an array, find the largest element in it.

Input : arr[] = {10, 20, 4}
Output : 20

Input : arr[] = {20, 10, 20, 4, 100}
Output : 100

Method 1: Iterative Way

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to find maximum in arr[] 
class Test
{
     static int arr[] = {10, 324, 45, 90, 9808};
       
     // Method to find maximum in arr[]
     static int largest()
     {
         int i;
           
         // Initialize maximum element
         int max = arr[0];
        
         // Traverse array elements from second and
         // compare every element with current max  
         for (i = 1; i < arr.length; i++)
             if (arr[i] > max)
                 max = arr[i];
        
         return max;
     }
       
     // Driver method
     public static void main(String[] args) 
     {
         System.out.println("Largest in given array is " + largest());
        }
 }

chevron_right


Output:



Largest in given array is 9808

Method 2: Java 8 Stream
You can simply use the new Java 8 Streams but you have to work with int.

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.util.Arrays;
  
public class GFG {
    public static void main(String[] args){
        int arr[] = {10, 324, 45, 90, 9808};
        int max = Arrays.stream(arr).max().getAsInt();
        System.out.println("Largest in given array is " +max);
    }
  
}

chevron_right


Output:

Largest in given array is 9808

Please refer complete article on Program to find largest element in an array for more details!



My Personal Notes arrow_drop_up

Improved By : 29AjayKumar

Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.