Java Math.min and Math.max
Math.min chooses the smaller value and Math.max chooses the larger. Together they can keep an amount between zero and a bill total.
A simple example
Math.min and Math.max
- Start with 8, allowed range 0–5
- Do this Take the minimum with 5, then maximum with 0
- Result 5
Syntax
Math.max(0, Math.min(requested, bill))
JDK 21 method signatures (8)
public static int max(int a, int b)
public static long max(long a, long b)
public static float max(float a, float b)
public static double max(double a, double b)
public static int min(int a, int b)
public static long min(long a, long b)
public static float min(float a, float b)
public static double min(double a, double b)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaApply store credit
A shopper presents store credit at checkout. The till must cap the usable credit at the outstanding bill and handle boundary amounts before it prints the balance.
public class Main {
public static void main(String[] args) throws Exception {
int bill = 800;
for (int requested : new int[]{-50, 300, 1000}) {
System.out.println(Math.max(0, Math.min(requested, bill)));
}
}
}
0 300 800
Negative credit becomes zero. A request for 300 cents fits the bill. A request for 1,000 cents is capped at 800.
Limit a reservation to available seats
A booking screen receives a requested party size and the current seat inventory. Use the available capacity to decide how many places can actually be assigned.
class Main {
public static void main(String[] args) throws Exception {
double requested = 18.0;
double available = 12.0;
System.out.printf(java.util.Locale.ROOT, "%.3f%n", (double) (Math.min(requested, available)));
}
}
12.000
Twelve seats remain, so a request for eighteen can reserve at most twelve.
Record the busiest hour at a help desk
A help desk is planning coverage for its busiest period. Compare the recorded hourly loads to identify the peak that the next shift needs to handle.
class Main {
public static void main(String[] args) throws Exception {
double baseline = 15.0;
double current = 23.0;
System.out.printf(java.util.Locale.ROOT, "%.3f%n", (double) (Math.max(baseline, current)));
}
}
23.000
The current count of 23 exceeds the previous record of 15.
What to watch for
Keep all amounts in the same unit. The example uses whole cents.