Java Program to Find Largest Element in an Array

In this post, we will write a Java program to find the largest element in an Array.
In this post, in 2 ways we can write logic to find the largest element in an Array.

  • Using Iterative Method
  • Using Arrays.sort() Method

Using Iterative Method

public class LargestNumbersInArray {
 public static void main(final String[] args) {
  
  final int[] array = {12,34,56,12,13,454};
        usingIterative(array);
 }
 
 private static int usingIterative(final int[] array){
   // Initialize maximum element
        int max = array[0];
      
        // Traverse array elements from second and
        // compare every element with current max  
        for (int i = 1; i < array.length; i++){
            if (array[i] > max){
             max = array[i];
            }
        }
        
        System.out.println(max);
        return max;
 }
}
Output:
454

Using Arrays.sort() Method

public class LargestNumbersInArray {
 public static void main(final String[] args) {
  
  final int[] array = {12,34,56,12,13,454};
        final int largest = usingLibrary(array);
        System.out.println(largest);
 }
 
 private static int usingLibrary(final int[] array){
  Arrays.sort(array);
  return array[array.length - 1];
  
 }
}
Output:
454


Comments