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,

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete