Largest number in java

Hey guys!!! Welcome to flower brackets blog. Today you will learn largest number in java.

Largest Number In Java

To find largest of three numbers, comparison operator (>) is used. Comparison operator compares two numbers.

Also read Рfind largest using ternary operator

public class LargestOfThree 
{
   public static int findLargest(int arr[], int sum)
   { 
      int temp; 
      for(int a = 0; a < sum; a++) 
      { 
         for(int b = a + 1; b < sum; b++) 
         { 
            if(arr[a] > arr[b]) 
            { 
               temp = arr[a]; 
               arr[a] = arr[b]; 
               arr[b] = temp; 
            } 
         } 
      } 
      return arr[sum - 1]; 
   }

   public static void main(String[] args) 
   {
      int arrNumber[] = {15, 26, 56, 65, 36, 29}; 
      System.out.println("Largest : " + findLargest(arrNumber, 6));
   }
}

Output:

Largest : 65


Java program to find largest element in an array

Here’s the java program to find largest number in an array,

import java.util.Arrays;

public class LargestUsingArray 
{
   public static int findLargest(int arrNum[], int sum)
   { 
      Arrays.sort(arrNum);
      return arrNum[sum - 1]; 
   }

   public static void main(String[] args) 
   {
      int arrNumber[] = {61, 91, 55, 86, 63, 92}; 
      System.out.println("Largest number : " + findLargest(arrNumber, 6));
   }
}

Output:

Largest number : 92


Find the largest number in an array

Let’s learn java program to find largest element in an array using collections,

Also read – find largest using nested if

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LargestUsingCollections 
{
   public static int findLargest(Integer arr[], int sum)
   { 
      List<Integer> li = Arrays.asList(arr); 
      Collections.sort(li); 
      int number = li.get(sum - 1); 
      return number; 
   }

   public static void main(String[] args) 
   {
      Integer arrNum[] = {156, 266, 556, 666, 389, 268}; 
      System.out.println("Largest number : " + findLargest(arrNum, 6));
   }
}

Output:

Largest number : 666

Related Posts