Can you use Math.max with an array?

No, but...

If you're using Java 8, you can use streams:

Arrays.stream(array).max().getAsInt()

Otherwise you can write a simple utility method to do it for you:

public static int max(int... array) {
    if (array.length == 0) {
        // ...
    }

    int max = array[0];

    for (int a : array) {
        if (a > max)
            max = a;
    }

    return max;
}
Answer from arshajii on Stack Overflow
🌐
Programiz
programiz.com › java-programming › library › math › max
Java Math max()
In the above example, we have used the Math.max() method with int, long, float, and double type arguments. class Main { public static void main(String[] args) { // create an array of int type int[] arr = {4, 2, 5, 3, 6}; // assign first element of array as maximum value int max = arr[0]; for (int i = 1; i < arr.length; i++) {
People also ask

What is the purpose of the Math.max() function in Java?
The primary purpose of Math.max() is as a programming tool that discovers the biggest number between any two input numbers using an effective mathematical detection method.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › the max function in java
Max Function in Java: A Complete Guide with Practice Exercises
Can Math.max() be used with arrays or collections directly?
The Math.max() functions cannot directly check array or collection values within JavaScript programming and its Java and similar language counterparts. To decompose array elements for Math.max() you should employ the spread operator (...) or apply().
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › the max function in java
Max Function in Java: A Complete Guide with Practice Exercises
What data types does Math.max() support?
Programming users can utilize Math.max() to evaluate int, float, double, and long numeric types and return the highest value in Java programming language.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › the max function in java
Max Function in Java: A Complete Guide with Practice Exercises
🌐
W3Schools
w3schools.com › java › ref_math_max.asp
Java Math max() Method
Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting ... How Tos Add Two Numbers Swap Two Variables Even or Odd Number Reverse a Number Positive or Negative Square Root Area of Rectangle Celsius to Fahrenheit Sum of Digits Check Armstrong Num Random Number Count Words Count Vowels in a String Remove Vowels Count Digits in a String Reverse a String Palindrome Check Check Anagram Convert String to Array Remove Whitespace Count Character Frequency Sum of Array Elements Find Array Average Sort an Array Find Smallest Element Find Largest Element Second Largest Array Min and Max Array Merge Two Arrays Remove Duplicates Find Duplicates Shuffle an Array Factorial of a Number Fibonacci Sequence Find GCD Check Prime Number ArrayList Loop HashMap Loop Loop Through an Enum
🌐
GeeksforGeeks
geeksforgeeks.org › java › find-max-min-value-array-primitives-using-java
Find max or min value in an array of primitives using Java - GeeksforGeeks
April 9, 2025 - ... // Java program to find min ... System.out.println("Minimum number of array is : " + min); System.out.println("Maximum number of array is : " + max); } }...
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › the max function in java
Max Function in Java: A Complete Guide with Practice Exercises
March 18, 2025 - We utilize the Math.max() method two times to assess the three numbers: Initially, it determines the higher value between num1 and num2. Next, it evaluates the outcome against num3 to determine the overall maximum. Ultimately, we display the maximum value. ... Enter the first number: 10 Enter the second number: 20 Enter the third number: 15 The maximum number is: 20 · Here’s a Java function that accepts an integer array as input and produces the maximum value through a loop:
🌐
Scaler
scaler.com › home › topics › max function in java
Max Function in Java - Scaler Topics
April 20, 2024 - The second method is to take the help of the inbuilt max() method of Math class in Java that takes two numbers as input and returns the maximum of two numbers. This one is easy compared to the first method. Let's understand the max() in Java with the help of examples. We will discuss few examples to understand max() method in Java. The simple example finds maximum value between two integers. ... We get 45 because the maximum of 4 and 45 is 45. Let's understand how to get a maximum value from an array using Math.max() method.
🌐
iO Flood
ioflood.com › blog › math-max-java
Math.max() Java Function | Usage, Syntax, and Examples
February 29, 2024 - This is a quick and concise way ... of numbers and want to find the maximum, one approach is to sort the array in ascending order and pick the last element. Here’s how you can do this in Java:...
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-for-program-to-find-largest-element-in-an-array
Java Program to Find Largest Element in an Array - GeeksforGeeks
The most common method to find and print the largest element of a Java array is to iterate over each element of the array and compare each element with the largest value. ... We assume that the first element is the largest and initialize the ...
Published   July 23, 2025
🌐
Dot Net Perls
dotnetperls.com › math-max-java
Java - Math.max and Math.min - Dot Net Perls
600 }; // Use Math.min to get smallest length for both arrays. int commonLength = Math.min(codes1.length, codes2.length); // Display elements in each array at indexes. // ... All indexes have elements. for (int i = 0; i < commonLength; i++) { System.out.println(codes1[i] + "/" + codes2[i]); } } } ... In this example we score words based on their letters. We use Math.max to keep track of the highest-scoring word.
🌐
Coderanch
coderanch.com › t › 405007 › java › Finding-maximum-array-loop
Finding the maximum of an array without using a loop (Beginning Java forum at Coderanch)
How would YOU, by hand, find the largest value in a list of numbers? you'd have to look at each and every number. if you don't know how many numbers there are, you have to keep looking until you run out. if you DO know the exact number, you could hard-code your java to say biggest = element 0; if ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-math-max-method
Java Math max() Method - GeeksforGeeks
May 14, 2025 - Example 1: In this example, we will see the basic usage of Math.max() method with Double values. ... // Java program to demonstrate // the use of max() function // when two double data-type // numbers are passed as arguments import java.lang.Math; public class Geeks { public static void main(String args[]) { double a = 12.123; double b = 12.456; // prints the maximum of two numbers System.out.println(Math.max(a, b)); } }
🌐
Baeldung
baeldung.com › home › java › java array › finding min/max in an array with java
Finding Min/Max in an Array with Java | Baeldung
January 2, 2026 - void givenIntegerList_whenGetMaxAbsolute_thenReturnMaxAbsolute() { List<Integer> numbers = Arrays.asList(-10, 3, -2, 8, 7); int absMax = numbers.stream() .max(Comparator.comparingInt(Math::abs)) .orElseThrow(NoSuchElementException::new); assertEquals(-10, absMax); } While Java 8 Streams provide an elegant, built-in way to find the maximum value, it’s also a common task to implement this using recursion.
🌐
DEV Community
dev.to › dhanush9952 › finding-minimum-and-maximum-values-in-an-array-effective-approaches-with-java-programming-39dp
Finding Minimum and Maximum Values in an Array: Effective Approaches with Java Programming - DEV Community
November 6, 2024 - Use Case: Use this method only when sorting the array is acceptable and you don’t mind modifying the original array. For readability: The simple loop or Math.min/max approach provides readable and efficient solutions. For modern Java: Use Arrays.stream() if you’re comfortable with Java 8+.
🌐
JavaBeat
javabeat.net › home › how to use the math.max() function in java?
How to Use the Math.max() Function in Java?
January 23, 2024 - The loop compares the value of the “Maximum” integer and the array’s value at index “i” by using the Math.max() method. The maximum of the two values is kept in the “Maximum” variable.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › math_max_int.htm
Java - Math max(int x, int y) Method
package com.tutorialspoint; public class MathDemo { public static void main(String[] args) { // get two int numbers int x = -60984; int y = 497; // call max and print the result System.out.println("Math.max(" + x + "," + y + ")=" + Math.max(x, y)); } }
🌐
Reddit
reddit.com › r/javahelp › how does the math.max function work in this code?
r/javahelp on Reddit: How does the Math.max function work in this code?
September 11, 2022 -
class consecutiveOnes
{

public int findMaxConsecutiveOnes(int[] nums) { //constructor that accepts as an argument an int array called nums.

        int maxHere = 0, max = 0; //int variable declarations initialized with zero.
        for (int n : nums) //for each loop. for int n in nums array:
            max = Math.max(max, maxHere = n == 0 ? 0 : maxHere +1); //ternary operator. max is assigned the math.max function (different use of max). max is the total max values consecutively. maxHere is the max value per n in the array.
                                                                    // This says if the larger of the two values (max, maxHere)

                                                                    // is zero, return zero and overwrite max with zero(this ensures the consecutive counter for 1 is reset), else increment maxHere by 1.
        return max;     //returns max
    }

    public static void main (String[] args)
    {
        consecutiveOnes co = new consecutiveOnes();

        int nums[] = {1, 0, 1, 1, 1, 1};

        //int n = nums.length;

        System.out.println("number of consecutive ones are: " +co.findMaxConsecutiveOnes(nums));

    }
}

I understand that the Math.max function returns the highest of two values (in this case, the highest of max and maxHere). Included are comments of what I believe is happening. What I don't understand is why the Math.max function is not returning 2 for max when for example, n in the array is 1. Would it not be the case since maxHere is incrementing by 1?

My rationalization is if n = 1, and maxhere +1 or increments by 1, then maxHere = 2 and new max value is 2, but that would not make sense, especially because consecutive count would be 2 at the first run of the loop...

EDIT: I apologize for the confusion. The code runs fine, but I have a limited understanding of why the Math.max function is choosing maxHere = 1 for max and not maxHere = 2 when maxHere = n =1 since maxHere + 1 would execute.

Top answer
1 of 4
2
As stated your code works fine. I'm a little confused as to what you're confused about, but if you step through the loop then you will have the following results; maxHere = 1, max = 0; -> max = 1; maxHere = 0, max = 1; -> max = 1; maxHere = 1, max = 1; -> max = 1; maxHere = 2, max = 1; -> max = 2; maxHere = 3, max = 2; -> max = 3; maxHere = 4, max =3; -> max = 4; And then after the loop it returns max which is 4.
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
Top answer
1 of 16
203

Using Commons Lang (to convert) + Collections (to min/max)

import java.util.Arrays;
import java.util.Collections;

import org.apache.commons.lang.ArrayUtils;

public class MinMaxValue {

    public static void main(String[] args) {
        char[] a = {'3', '5', '1', '4', '2'};

        List b = Arrays.asList(ArrayUtils.toObject(a));

        System.out.println(Collections.min(b));
        System.out.println(Collections.max(b));
   }
}

Note that Arrays.asList() wraps the underlying array, so it should not be too memory intensive and it should not perform a copy on the elements of the array.

2 of 16
176

You can simply use the new Java 8 Streams but you have to work with int.

The stream method of the utility class Arrays gives you an IntStream on which you can use the min method. You can also do max, sum, average,...

The getAsInt method is used to get the value from the OptionalInt

import java.util.Arrays;

public class Test {
    public static void main(String[] args){
        int[] tab = {12, 1, 21, 8};
        int min = Arrays.stream(tab).min().getAsInt();
        int max = Arrays.stream(tab).max().getAsInt();
        System.out.println("Min = " + min);
        System.out.println("Max = " + max)
    }

}

==UPDATE==

If execution time is important and you want to go through the data only once you can use the summaryStatistics() method like this

import java.util.Arrays;
import java.util.IntSummaryStatistics;

public class SOTest {
    public static void main(String[] args){
        int[] tab = {12, 1, 21, 8};
        IntSummaryStatistics stat = Arrays.stream(tab).summaryStatistics();
        int min = stat.getMin();
        int max = stat.getMax();
        System.out.println("Min = " + min);
        System.out.println("Max = " + max);
    }
}

This approach can give better performance than classical loop because the summaryStatistics method is a reduction operation and it allows parallelization.