Java Program to Find the Largest Element in the Array - The Coding Shala

Home >> Java Programs >> Find Largest Element in the Array

 In this post, we will learn how to Find the Largest Element in the given Array using Java.

Java Program to Find the Largest Element in the Array

In the given array, we need to print the maximum element of the array. The array can have negative and positive numbers.

Example 1:
Input: arr = {3, 5, 2, 5, -1, -33, 11}
Output: 11

Java Program: 

/**
 * https://www.thecodingshala.com/
 */


public class Main {

    public static void printLargest(int[] arr) {
        if (arr.length < 1) {
            System.out.println("Given array is empty");
        } else {
            int max = arr[0];
            for (int i=1; i<arr.length; i++) {
                if(arr[i] > max) {
                    max = arr[i];
                }
            }
            System.out.println("Largest element in the array is: " + max);
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 4, -6, 2, 7, -9, 11, -44, 22, 3, 6};
        printLargest(arr);
    }
}

Output: 

Largest element in the array is: 22


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala