To find the second largest number in a Java array, we can employ the approach of sorting the array in ascending order and then returning the second-to-last element as the second largest number.
public class SecondLargestInArrayExample{ public static int getSecondLargest(int[] a, int total){ int temp; for (int i = 0; i < total; i++) { for (int j = i + 1; j < total; j++) { if (a[i] > a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } return a[total-2]; } public static void main(String args[]){ int a[]={1,2,5,6,3,2}; int b[]={44,66,99,77,33,22,55}; System.out.println("Second Largest: "+getSecondLargest(a,6)); System.out.println("Second Largest: "+getSecondLargest(b,7)); }}
Output:
Second Largest: 5 Second Largest: 77
Find the second largest number in the Array using Arrays
import java.util.Arrays; public class SecondLargestInArrayExample1{ public static int getSecondLargest(int[] a, int total){ Arrays.sort(a); return a[total-2]; } public static void main(String args[]){ int a[]={1,2,5,6,3,2}; int b[]={44,66,99,77,33,22,55}; System.out.println("Second Largest: "+getSecondLargest(a,6)); System.out.println("Second Largest: "+getSecondLargest(b,7)); }}
Output:
Second Largest: 5 Second Largest: 77
Find the second largest number in Array using Collections
import java.util.*; public class SecondLargestInArrayExample2{ public static int getSecondLargest(Integer[] a, int total){ List<Integer> list=Arrays.asList(a); Collections.sort(list); int element=list.get(total-2); return element; } public static void main(String args[]){ Integer a[]={1,2,5,6,3,2}; Integer b[]={44,66,99,77,33,22,55}; System.out.println("Second Largest: "+getSecondLargest(a,6)); System.out.println("Second Largest: "+getSecondLargest(b,7)); }}
Output:
Second Largest: 5 Second Largest: 77
In conclusion, the provided Java code effectively finds the second-largest number in an array by sorting the array in ascending order and returning the second-to-last element from the sorted array. Follow tutorials.freshersnow.com to learn more.