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
// 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
filter_none
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.
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
filter_none
Output:
Largest in given array is 9808
Method 3 : (Sorting)
// Java program to find maximum in // arr[] of size n import java .io.*; import java.util.*; class GFG { // returns maximum in arr[] of size n static int largest(int []arr, int n) { Arrays.sort(arr); return arr[n - 1]; } // Driver code static public void main (String[] args) { int []arr = {10, 324, 45, 90, 9808}; int n = arr.length; System.out.println(largest(arr, n)); } } |
chevron_right
filter_none
Please refer complete article on Program to find largest element in an array for more details!
Recommended Posts:
- Java Program for Find largest prime factor of a number
- Find smallest and largest element from square matrix diagonals
- Java Program for Largest K digit number divisible by X
- Java Program for Largest Sum Contiguous Subarray
- Java Program for Program to find area of a circle
- Java Program for Program for array rotation
- Java Program to Find remainder of array multiplication divided by n
- Java Program to find sum of array
- Find the last element of a Stream in Java
- Find the first element of a Stream in Java
- Find closest smaller value for every element in array
- First strictly greater element in a sorted array in Java
- First strictly smaller element in a sorted array in Java
- How to Insert an element at a specific position in an Array in Java
- Java Program for Program to calculate area of a Tetrahedron
- Java Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!
- Java Program for Find the perimeter of a cylinder
- Java Program to Find sum of even factors of a number
- Java Program to Find minimum sum of factors of number
- Java Program to Find sum of Series with n-th term as n^2 - (n-1)^2
Improved By : 29AjayKumar

