Find the largest number in a Java array.


Example

Following is the required program.

Live Demo

public class Tester {
   public static int getLargest(int[] a) {
      int temp;
      //sort the array
      for (int i = 0; i < a.length; i++) {
         for (int j = i + 1; j < a.length; j++) {
            if (a[i] > a[j]) {
               temp = a[i];
               a[i] = a[j];
               a[j] = temp;
            }
         }
      }
      //return largest element
      return a[a.length - 1];
   }
   public static void main(String args[]) {
      int a[] = { 11,10,4, 15, 16, 13, 2 };
      System.out.println("Largest: " + getLargest(a));
   }
}

Output

Largest: 16

Updated on: 12-Mar-2020

621 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements