Here we are find the largest number from an Array in java.
- First we sort the given Array from Arrays.sort() method.
- Now we find the largest value index from numbers.length-1 and pass to declare numbers array.
- For second largest value we find the second largest numbers index from numbers.length-2 and pass to that index in numbers arrays.
- Print largest and second largest numbers.
Syntax :- public static void sort(int[] a);
import java.util.Arrays;
public class LargestNumberDemo {
public static void main(String args[]) {
int numbers[] = { 1, 34, 56, 78, 23, 52, 98, 60 };
Arrays.sort(numbers);
System.out.println("Largest Number value :- " + numbers[numbers.length - 1]);
System.out.println("Second Largest Number value :- " + numbers[numbers.length - 2]);
}
}
Output :-
Largest Number value :- 98
Second Largest Number value :- 78