Java Program to find the largest number in an Array

To find the largest number in a Java array, one approach is to sort the array in ascending order and then return the last element, as it will be the largest. Here’s an example:

public class LargestInArrayExample{  
public static int getLargest(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-1];  
}  
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("Largest: "+getLargest(a,6));  
System.out.println("Largest: "+getLargest(b,7));  
}}

Output:

Largest: 6
Largest: 99

Java Program to find the largest number in the Array using Arrays

import java.util.Arrays;  
public class LargestInArrayExample1{  
public static int getLargest(int[] a, int total){  
Arrays.sort(a);  
return a[total-1];  
}  
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("Largest: "+getLargest(a,6));  
System.out.println("Largest: "+getLargest(b,7));  
}}

Output:

Largest: 6
Largest: 99

Java Program to find the largest number in Array using Collections

import java.util.*;  
public class LargestInArrayExample2{  
public static int getLargest(Integer[] a, int total){  
List<Integer> list=Arrays.asList(a);  
Collections.sort(list);  
int element=list.get(total-1);  
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("Largest: "+getLargest(a,6));  
System.out.println("Largest: "+getLargest(b,7));  
}}

Output:

Largest: 6
Largest: 99

In conclusion, the provided Java program effectively finds the largest number in an array by sorting the array in ascending order and returning the last element from the sorted array, representing the largest number. Follow tutorials.freshersnow.com to learn more.