Loading
Find the maximum-tutorial
In Java, we can easily find the largest (maximum) number in an array using a simple loop. This operation is useful in many applications, including ranking, scoring, and statistics.



Key Point

  • Use a variable to keep track of the maximum value.
  • Compare each element with the current maximum.
  • If any number is greater, update the max.



Example: Find Maximum in Array

import java.util.Scanner;

public class Main {
    public static void main(String[ ] args) {

        System.out.println("Finding maximum number");

        Scanner input = new Scanner(System.in);
        System.out.println("Enter array size:");
        int size = input.nextInt();

        int[] arr = new int[10];
        System.out.println("Enter array values:");
        for (int i = 0; i < size; i++) {
            arr[i] = input.nextInt();
        }

        int max = arr[0];  // Assume first element is max initially

        // Function call to find the maximum value
        int ans = MaxValue(arr, max, size);
        System.out.println("Max value is = " + ans);
    }

    public static int MaxValue(int[ ] arr, int max, int size) {
        for (int j = 0; j < size; j++) {
            if (arr[j] > max) {
                max = arr[j];  // Update max if current element is greater
            }
        }
        return max;
    }
}

Output:

Finding maximum number
Enter array size:
5
Enter array values:
1
2
25
0
2
Max value is = 25

Explanation

StepDescription
arr[0]First value is taken as initial maximum
for loopIterates through the array
if (arr[j] > max)Compares current value with max
max = arr[j]Updates max if a larger number is found