Java Program to Find Largest Element of an Array

In this tutorial we will write java program to find largest number in array java . We have different methods to find maximum element in an array java .

Method 1.  Find Largest Number in Array using Iterative Way

In this program we find largest number in array using for loop in java. Firstly we will discuss algorithm to find largest number in an array .

Algorithm

STEP 1: START
STEP 2: INITIALIZE arr[] = {10, 15, 7, 75, 36}
STEP 3: max = arr[0]
STEP 4: REPEAT STEP 5 for(i=1; i< arr.length; i++)
STEP 5: if(arr[i]>max) then max=arr[i]
STEP 6: PRINT max
STEP 7: END

public class LargestElement {
//How to find largest element in an array with index and value ?

public static void main(String[] args) {

int [] arr ={10, 15, 7, 75, 36};
int largest = arr[0];
for(int i = 1 ; i < arr.length; i++){
if( largest < arr[i]){
largest = arr[i];
}
}
System.out.println(" largest element  ="+ largest );

}

}

Output :

largest element  =75

Method 2: Find Largest Number in Array using Java 8 Stream

We can find max value in array using java8 stream .

import java.util.Arrays;
  
public class LargestElement{
    public static void main(String[] args){
        int arr[] = {4,5,10,20,8,6};
        int max = Arrays.stream(arr).max().getAsInt();
        System.out.println("Largest Element in given array is :" +max);
    }
  
}

Output:

Largest Element in given array is :20

Method 3: Find Largest Number in Array using Arrays

Now , we will write java program to find the largest number in an array using Arrays. We sort the array element using sort method of Arrays then return last element from array . In this program we find largest number in array java using sort method of Arrays.
import java.util.Arrays;

public class LargestElementUsingArrays {
	
	public static void main(String[] args) {
		
		int arr[] = {4,5,10,20,8,6};
		int max = getLargestElement(arr);
		System.out.println("Largest Element in Array is :"+ max);
	}
	
	public static int getLargestElement(int [] arr){
		Arrays.sort(arr);
		return arr[arr.length-1];
	}

}
Output :
Largest Element in Array is :20
In this article we have learned different method to find max value in array. You can see more interesting java program question  for interview .

Leave a Reply

Your email address will not be published. Required fields are marked *

− 1 = 2