In this article, we will see how to find the largest number from an array using java. This is one of basic questions in technical interviews. Earlier post we had seen how to find the smallest element from array. Now we will see how to find the largest number from integer array using java.
The logic is very simple here, see the below.
- At first we need to assume any element as largest value. Example - 0th location.
- Then iterate over the array and compare with each element , whether its larger than the assumed larger value or not. If array element is larger then assign the array element value to assumed variable. Repeat the entire until end.
FindLargestNumberInArray.java
package com.techbyteslearn.lab.basic; public class FindLargestNumberInArray { // Find the largest value from an array. public static void main(String[] args) { int[] arr = {200, 3, 4, 24, 33, 24, 22, 55, 90, 103, 150}; // Assume the largest value is at the 0th index. int largest = arr[0]; for (int i = 0; i < arr.length; i++) { if (arr[i] >= largest) { largest = arr[i]; } } System.out.println("Largest Number is ::" + largest); } }Output:
Largest Number is ::200The original
i < arr.length - 1skips the last element. Usingi < arr.lengthchecks the complete array.
Using Java 8
int largest = IntStream.of(arr).boxed().max(Comparator.naturalOrder()).get().intValue() ;
Happy Learning.