0
0
JavaHow-ToBeginner · 3 min read

How to Use Math.max and Math.min in Java: Simple Guide

In Java, use Math.max(a, b) to get the larger of two values and Math.min(a, b) to get the smaller. Both methods take two numbers as arguments and return the maximum or minimum respectively.
📐

Syntax

The Math.max and Math.min methods each take two arguments of the same numeric type and return the larger or smaller value respectively.

  • Math.max(type a, type b): Returns the greater of a and b.
  • Math.min(type a, type b): Returns the smaller of a and b.
  • Supported types include int, long, float, and double.
java
int maxVal = Math.max(5, 10);
int minVal = Math.min(5, 10);
💻

Example

This example shows how to use Math.max and Math.min to find the largest and smallest numbers among two values.

java
public class MaxMinExample {
    public static void main(String[] args) {
        int a = 15;
        int b = 25;

        int max = Math.max(a, b);
        int min = Math.min(a, b);

        System.out.println("Max value: " + max);
        System.out.println("Min value: " + min);
    }
}
Output
Max value: 25 Min value: 15
⚠️

Common Pitfalls

Common mistakes include:

  • Passing arguments of different types without casting, which causes a compile error.
  • Trying to find max or min of more than two numbers directly; Math.max and Math.min only take two arguments.
  • Confusing the order of arguments does not affect the result, but both must be valid numbers.

To find max or min of multiple numbers, chain calls like Math.max(a, Math.max(b, c)).

java
/* Wrong: mixing types without cast */
// int max = Math.max(5, 10.5); // Compile error

/* Right: cast to double */
double max = Math.max(5, 10.5);

/* Finding max of three numbers */
int maxThree = Math.max(5, Math.max(10, 7));
📊

Quick Reference

MethodDescriptionExample
Math.max(a, b)Returns the larger of a and bMath.max(3, 7) → 7
Math.min(a, b)Returns the smaller of a and bMath.min(3, 7) → 3

Key Takeaways

Use Math.max(a, b) to get the larger of two numbers and Math.min(a, b) for the smaller.
Both methods accept two arguments of the same numeric type and return a value of that type.
To find max or min of more than two numbers, chain calls like Math.max(a, Math.max(b, c)).
Passing mixed numeric types without casting causes compile errors.
Order of arguments does not affect the result but both must be valid numbers.