0
0
JavaHow-ToBeginner · 3 min read

How to Find Maximum Value in Array in Java

To find the maximum value in an array in Java, you can loop through the array comparing each element to track the largest value using a variable. Alternatively, use Arrays.stream(array).max() for a concise approach.
📐

Syntax

Use a loop to check each element and keep track of the maximum value found so far.

Example syntax:

int max = array[0];
for (int i = 1; i < array.length; i++) {
    if (array[i] > max) {
        max = array[i];
    }
}

Here, max starts as the first element. The loop compares each element to max and updates it if a bigger value is found.

java
int max = array[0];
for (int i = 1; i < array.length; i++) {
    if (array[i] > max) {
        max = array[i];
    }
}
💻

Example

This example shows how to find the maximum number in an integer array using a simple loop.

java
public class MaxInArray {
    public static void main(String[] args) {
        int[] numbers = {3, 7, 2, 9, 5};
        int max = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > max) {
                max = numbers[i];
            }
        }
        System.out.println("Maximum value is: " + max);
    }
}
Output
Maximum value is: 9
⚠️

Common Pitfalls

  • Not initializing max with the first element of the array can cause errors.
  • For empty arrays, this method will throw an error; always check if the array is not empty before finding max.
  • Using Arrays.stream(array).max() returns an OptionalInt, so you must handle the case when the array is empty.
java
/* Wrong: max not initialized */
int max;
for (int i = 0; i < array.length; i++) {
    if (array[i] > max) { // error: max not initialized
        max = array[i];
    }
}

/* Right: initialize max with first element */
int max = array[0];
for (int i = 1; i < array.length; i++) {
    if (array[i] > max) {
        max = array[i];
    }
}
📊

Quick Reference

Summary tips for finding max in array:

  • Always initialize max with the first element.
  • Use a loop to compare each element.
  • Check for empty arrays before processing.
  • Use Arrays.stream(array).max() for a concise modern approach.

Key Takeaways

Initialize the max variable with the first array element before looping.
Loop through the array comparing each element to update max.
Always check if the array is empty to avoid errors.
Use Java Streams for a concise max value retrieval with proper empty checks.