Java - Program to Find Largest Element in an Array

In this section, we will show you how to find the largest element in an Array.

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

1. Using Iterative Method

public class Main {

public static void main(final String[] args) {

final int[] array = {1,4,44,5,66,2};
largestElement(array);
}

private static int largestElement(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;
}
}

Console Output:
66

2. Using Arrays.sort() Method

import java.util.Arrays;

public class Main {

public static void main(final String[] args) {

final int[] array = {1,4,44,5,66,2};
final int max = largestElement(array);
System.out.println(max);
}

private static int largestElement(final int[] array){
Arrays.sort(array);
return array[array.length - 1];

}
}


Console Output:
66

More topics,

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example