# Java Program to Find the Largest Number in an Array

(Last Updated On: 04/09/2023)

In this blog, we will explore various methods to achieve this task in Java. By the end of this journey, you’ll have a solid grasp of different techniques to find the largest number, not only in an array but also the second and third largest numbers.

When it comes to programming, the ability to find the largest number in an array is a fundamental skill. Whether you’re a beginner taking your first steps into the world of coding or an experienced developer optimizing algorithms, knowing how to efficiently identify the largest element in an array is crucial.

## What do you mean by finding the largest number in an array?

In Java programming, finding the largest number in an array involves iterating through the elements of the array and comparing each element to determine the maximum value. The largest number is the element that is greater than or equal to all other elements in the array.

## Methods to Find the Largest Number in an Array

1. By sorting the array

2. Using Arrays

3. Using Collections

### Method 1: by sorting the array

The given Java program is designed to find the largest number in an array using a sorting approach. Let’s check out the code and how it works:

```//Java Program to Find the Largest Number in an Array
public class LargestInArrayEx{
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};
System.out.println("Largest: "+getLargest(a,6));
}
}  ```

Explanation of the code:

1. The `LargestInArrayEx` class is defined with the `main` method as the entry point of the program.

2. The `getLargest` method takes an integer array `a` and an integer `total` as parameters. It aims to find the largest number in the array using a sorting approach.

3. Inside the `getLargest` method:

– A variable `temp` is declared to facilitate swapping elements.

– Two nested `for` loops iterate through the array to compare and sort the elements.

– The outer loop iterates from the first element to the second-to-last element (`total – 1`).

– The inner loop iterates from the next element to the last element (`i + 1` to `total – 1`).

– If the current element `a[i]` is greater than the element `a[j]` being compared, their positions are swapped.

– This sorting process ensures that the largest element moves towards the end of the array.

4. After sorting, the method returns the largest element, which is now at the last position in the sorted array (`a[total – 1]`).

5. In the `main` method:

– An integer array `a` containing elements `{1, 2, 5, 6, 3, 2}` is declared and initialized.

– The `getLargest` method is called with the array `a` and the total number of elements (`6` in this case).

– The largest element is printed using the `System.out.println` statement.

#### Output:

``Largest: 6``

### Method 2: Using Arrays

Check out below Java program is designed to find the largest number in an array using a more efficient approach by utilizing the `Arrays.sort()` method:

```//Java Program to Find the Largest Number in an Array
import java.util.Arrays;
public class LargestInArrayEx{
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};
System.out.println("Largest: "+getLargest(a,6));
}
} ```

This Java program efficiently finds the largest number in an array using the built-in `Arrays.sort()` method. The key components are:

1. Method Definition (`getLargest`):

– Parameters: `a` (array of integers), `total` (number of elements).

– The `Arrays.sort(a)` method sorts the array in ascending order.

– The largest element is then accessed using `a[total-1]` and returned.

2. Main Method:

– Array `a` contains input elements.

– The `getLargest` method is called with the array and its size (`6`).

– The largest element is printed using `System.out.println`.

#### Output:

``Largest: 6``

### Method 3: Using Collections

Check the Java program is designed to find the largest number in an array using a more efficient approach by utilizing Java’s built-in libraries given below:

```//Java Program to Find the Largest Number in an Array
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));
}} ```

This Java program finds the largest number in an array using Collections. It follows these steps:

1. Method Definition (`getLargest`):

– Parameters: `a` (array of Integers), `total` (number of elements).

– The array is converted to a List using `Arrays.asList`.

– The List is sorted in ascending order using `Collections.sort`.

– The largest element (at index `total-1`) is retrieved and returned.

2. Main Method:

– Two Integer arrays (`a` and `b`) hold input elements.

– The `getLargest` method is called for both arrays, and the largest elements are printed using `System.out.println`.

The program sorts the List using Collections, ensuring the largest element is positioned at the end. It retrieves and prints the largest element from two different arrays.

#### Output:

``````Largest: 6
Largest: 99``````

## Java Program to Find 2nd Largest Number in an Array

When working with arrays in Java, it’s common to encounter scenarios where you need to find the second largest number. Whether you’re solving coding challenges, developing applications, or analyzing data, knowing how to efficiently find the second largest number is a valuable skill. In this blog, we’ll explore different methods to tackle this problem, each with its own approach and advantages.

## Methods to Find the 2nd Largest Number in an Array

1. By sorting the array

2. Using Arrays

3. Using Collections

### Method 1: by Sorting the Array

Check the Java program is designed to find the 2nd largest number in an array using a sorting-based approach:

```//Java Program to Find 2nd Largest Number in an Array
public class SecondLargestInArrayEx{
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,20,54,66,37,2};
System.out.println("Second Largest: "+getSecondLargest(a,6));
}
}
```

Explanation of the code:

The `getSecondLargest` function employs a nested loop to compare and swap elements, arranging them in ascending order. The program then returns the second-to-last element, which is the second largest number. In the main method, an example array is given, and the result is printed. While this approach is intuitive, it may not be the most efficient for larger arrays due to its sorting overhead. Alternative methods like using a priority queue or linear scan might offer better performance for this task.

#### Output:

``Second Largest: 54``

### Method 2: Using Arrays

The given Java program aims to find the second largest number in an array using a simple approach.

```//Java Program to Find 2nd Largest Number in an Array
import java.util.Arrays;
public class SecondLargestInArrayEx{
public static int getSecondLargest(int[] a, int total)
{
Arrays.sort(a);
return a[total-2];
}
public static void main(String args[]){
int a[]={1,74,5,47,3,92};
System.out.println("Second Largest: "+getSecondLargest(a,6));
}
}```

Explanation of code:
It sorts the array in ascending order and then retrieves the element located at the second-to-last index, which represents the second largest number. The program first imports the required package, defines a method `getSecondLargest` that takes an integer array and its length as parameters, sorts the array using the `Arrays.sort()` method, and returns the second-to-last element. In the `main()` function, an array is initialized, and the `getSecondLargest` method is called, displaying the second largest number in the array using the `System.out.println()` statement.

#### Output:

``Second Largest: 74``

### Method 3: Using Collections

The given Java program aims to find the second largest number in an array using a straightforward approach:

```//Java Program to Find 2nd Largest Number in an Array
import java.util.*;
public class SecondLargestInArrayEx{
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[]={16,28,57,66,34,21};
System.out.println("Second Largest: "+getSecondLargest(a,6));
}
} ```

Explanation of code:
It begins by converting the array into a list and sorting it in ascending order using the `Collections.sort()` method. By retrieving the element at the position `total – 2` from the sorted list, which corresponds to the second largest value, the program effectively identifies the desired result. The example array `{16, 28, 57, 66, 34, 21}` is utilized to demonstrate the functionality. The program outputs “Second Largest: 57,” providing a clear indication of the second largest number in the array.

#### Output:

``Second Largest: 57``

## Java Program to Find 3rd Largest Number in an Array

When working with arrays in Java, it’s common to encounter situations where you need to find specific elements, such as the largest or smallest numbers. In this blog, we will focus on finding the 3rd largest number in an array using different approaches. This problem is not only a coding exercise but also provides insights into algorithmic thinking and optimization.

## Methods to Find the 3rd Largest Number in an Array

1. By sorting the array and returning the 3rd largest number

2. Using Arrays

3. Using Collections

### Method 1: by sorting the array and returning the 3rd largest number

Check out Java program is designed to find the third largest number in an array using the selection sort algorithm:

```//Java Program to Find 3rd Largest Number in an Array
public class ThirdLargestInArrayEx{
public static int getThirdLargest(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-3];
}
public static void main(String args[]){
int a[]={1,20,5,60,3,28};
System.out.println("Third Largest: "+getThirdLargest(a,6));

}

} ```

Explanation of the code:

The `getThirdLargest` method takes an array `a` and the total number of elements `total` as parameters. It employs a nested loop structure to sort the array in ascending order using the selection sort technique. The third largest element is then obtained from the sorted array using the index `total-3` and returned. In the `main` method, an array `a` is defined with input elements. The `getThirdLargest` method is called, and the third largest element is displayed using `System.out.println`. The program ensures that the array is sorted, enabling the retrieval of the desired third largest element efficiently.

#### Output:

``Third Largest: 20``

### Method 2: Using Arrays

This Java program is designed to find the third largest number in an array using a simple and efficient approach:

```//Java Program to Find 3rd Largest Number in an Array
import java.util.*;
public class ThirdLargestInArrayEx{
public static int getThirdLargest(int[] a, int total){
Arrays.sort(a);
return a[total-3];
}
public static void main(String args[]){
int a[]={1,42,54,6,43,27};
System.out.println("Third Largest: "+getThirdLargest(a,6));
}
} ```

Explanation of the code:
Here’s a concise breakdown of its functionality:

1. **Method Definition (`getThirdLargest`)**:

– Parameters: `a` (array of integers), `total` (number of elements).

– The `Arrays.sort(a)` function is used to sort the array in ascending order.

– The third largest element is directly accessed using index `total-3`.

2. **Main Method**:

– Array `a` holds the input elements.

– The `getThirdLargest` method is called with the array and its size (`6`).

– The third largest element is printed using `System.out.println`.

The program sorts the array using `Arrays.sort` and directly returns the third largest element, which is printed in the `main` method. This approach has a time complexity of O(n log n) due to the sorting step, which is more efficient than earlier methods for larger arrays.

#### Output:

``Third Largest: 42``

### Method 3:Using Collections

The following Java program aims to find the third largest number in an array using the Collections framework:

```//Java Program to Find 3rd Largest Number in an Array
import java.util.*;
public class ThirdLargestInArrayEx{
public static int getThirdLargest(Integer[] a, int total)
{
List<Integer> list=Arrays.asList(a);
Collections.sort(list);
int element=list.get(total-3);
return element;
}
public static void main(String args[]){
Integer a[]={1,25,5,60,35,27};
System.out.println("Third Largest: "+getThirdLargest(a,6));
}
}

```

Explanation of the code:

This Java program is designed to find the third largest number in an array.:

1. **Method Definition (`getThirdLargest`)**:

– Parameters: `a` (array of Integers), `total` (number of elements).

– The input array is converted into a List using `Arrays.asList(a)`.

– The List is sorted in ascending order using `Collections.sort(list)`.

– The third largest element is retrieved from the sorted List (`list.get(total-3)`).

2. **Main Method**:

– An array `a` holds the input elements.

– The `getThirdLargest` method is called with the array and its size (`6`).

– The third largest element is printed using `System.out.println`.

#### Output:

``Third Largest: 27``

In conclusion, these Java programs provide various methods to find the largest, 2nd largest, and 3rd largest numbers in an array. Through sorting, Arrays, and Collections, you can efficiently identify these significant values. Mastering these techniques empowers you to manipulate arrays effectively, a crucial skill for programming and data manipulation tasks.

We hope that our blog on ‘Java Program to Find the Largest Number in an Array’ helps you to understand various methods to achieve. You can also visit our Newtum website for more information on various courses and blogs about  PHP, C Programming for kids, Java, and more. Happy coding with Newtum!