OneCompiler

[Java] How to find the max number from an array?

I want to find the maximum number from an array, how can I do that in Java?

1 Answer

4 years ago by

1. Simplest way to find the largest number

We have Arrays.sort() utility available to sort the elements from an array, using this we can sort the array first, then we can pick the last element to find the largest element.
Following code shows that

import java.util.Arrays;

public class JavaArrays {

	public static void main(String[] args) {

		int[] numbers = { 22, 456, 97, 4 };
		Arrays.sort(numbers);
		System.out.println("Largest number from the array: " + numbers[numbers.length -1]);

	}

}

Try online here: https://onecompiler.com/java/3xmstquxw

2. Efficient way to find largest number

In Java you can iterate though an array to find the largest number of an array.

Following program shows how to do that

public class JavaArrays {

	public static void main(String[] args) {

		int[] numbers = { 22, 456, 97, 4 };

		System.out.println("Largest number from the array: " + maxMumber(numbers));

	}

	static int maxMumber(int[] numbers) {
		int max = numbers[0];

		for (int ele : numbers) {
			if (ele > max) {
				max = ele;
			}
		}
		return max;
	}

}

Try online here: https://onecompiler.com/java/3xmsttn7u

4 years ago by Karthik Divi