Java Program to Find Largest Element of an Array

In this program, you’ll learn to find the largest element in an array using a for loop in Java.

 

Example: Find largest element in an array

  1. public class Largest {
  2. public static void main(String[] args) {
  3. double[] numArray = { 23.4, -34.5, 50.0, 33.5, 55.5, 43.7, 5.7, -66.5 };
  4. double largest = numArray[0];
  5. for (double num: numArray) {
  6. if(largest < num)
  7. largest = num;
  8. }
  9. System.out.format("Largest element = %.2f", largest);
  10. }
  11. }

When you run the program, the output will be:

Largest element = 55.50

In the above program, we store the first element of the array in the variable largest.

Then, largest is used to compare other elements in the array. If any number is greater than largest, largest is assigned the number.

In this way, the largest number is stored in largest when it is printed.