Java Program to find Largest Number in an Array

Hello everyone, Today we will learn how to find the largest number in an array in java by sorting the array and returning the largest number. 
Let's see the full example to find the largest number in the java array.

Example 1:

package com.knf;

public class LargestInArrayExample1 {

public static void main(String args[]) {
int a[] = { 2, 1, 2, 5, 6, 3, 2, 9 };
int b[] = { 144, 666, 99, 677, 433, 422, 255 };
System.out.println("Largest: " + getLargest(a));
System.out.println("Largest: " + getLargest(b));
}

public static int getLargest(int[] a) {
int temp;
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 a[a.length - 1];
}
}

Output:

Largest: 9
Largest: 677

Example 2: Using Arrays

Let's see another example to get the largest element in a java array using Arrays.

package com.knf;

import java.util.Arrays;

public class LargestInArrayExample2 {

public static void main(String args[]) {
int a[] = { 2, 1, 2, 5, 6, 3, 2, 9 };
int b[] = { 144, 666, 99, 677, 433, 422, 255 };
System.out.println("Largest: " + getLargest(a));
System.out.println("Largest: " + getLargest(b));
}

public static int getLargest(int[] a) {
Arrays.sort(a);
return a[a.length - 1];

}
}

Output:

Largest: 9
Largest: 677

Example 3: Using Collections

Let's see another example to get the largest number in java array using collections.

package com.knf;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LargestInArrayExample3 {

public static void main(String args[]) {
Integer a[] = { 2, 1, 2, 5, 6, 3, 2, 9 };
Integer b[] = { 144, 666, 99, 677, 433, 422, 255 };
System.out.println("Largest: " + getLargest(a));
System.out.println("Largest: " + getLargest(b));
}

public static int getLargest(Integer[] a) {
List<Integer> list = Arrays.asList(a);
Collections.sort(list);
return a[a.length - 1];

}
}

Output:

Largest: 9
Largest: 677

by sibin
web solution consultant for the startups
+91-8075866854

Comments