Java Program to find the largest number in an Array

In this post, we are going to see how to find the largest number in an Array using core Java program.

So, here is the complete program for you (JavaLargestInArray.java):

The output of the above program is:

Please go through inline comments in the above program to understand it. But the basic idea is, we are swapping the array values each time when there is a large number.

Here is a detailed explanation of the above program about the swapping,

//this is our array and the array length is 7
int arr[] = {10, 20, 101, 122, 1, 5, 12};

Let’s see the loop and if condition:

1. if (a[0] > a[1]) ie., if (10 > 20) – is false, so nothing happens here
2. if (a[1] > a[2]) ie., if (20 > 101) – is false, so nothing happens here
3. if (a[2] > a[3]) ie., if (101 > 122) – is false, so nothing happens here
4. if (a[3] > a[4]) ie., if (122 > 1) – is true, now the swap happens here
• let’s swap, a[3] = 1, a[4] = 122
5. if (a[4] > a[5]) ie., if (122 > 5) – is true again, so again swap the value
• a[4] = 5, a[5] = 122
6. if (a[5] > a[6]) ie., if (122 > 12) – is true again, so again swap the value
• a[5] = 5, a[6] = 122

So, the largest number is at the end of the array arr[6] = 122. That’s the value we are printing at the end.