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):

/**
 * @author agur
 * Find Largest value in an array
 */
public class JavaLargestInArray {
    public static void main(String[] args) {
        //declare an integer array
        int arr[] = {10, 20, 101, 122, 1, 5, 12};
        int temp, total, largest;
        
        //find the total length of an array
        total = arr.length;
        
        //we have arr[0] to arr[6], check against each and find the largest
        for (int i = 0; i < total; i++) {
            for (int j = i + 1; j < total; j++) {
                /**
                 * eg. if the array value of arr[0] is greater than arr[1] then allow
                 * otherwise just loop till find the largest value
                 * the below code will bring the largest value to the end of array - arr[6]                 * 
                 */
                if (arr[i] > arr[j]) {                    
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        
        //set the largest value
        largest = arr[total - 1];
        System.out.println("Largest number: "+largest);
    }
}

The output of the above program is: 

run:
Largest number: 122

BUILD SUCCESSFUL (total time: 0 seconds)

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top