CKTIS / Java
Math.min — smaller of two values and upper limits
`Math.min` returns the smaller of two numeric values. Use it to keep an increasing priority from going above 5.
Version: Java SE 21
Syntax
Math.min(a, 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)Math.min(a, b) is a static method of java.lang.Math. You do not need to create an object or write an import statement. The method returns the smaller of the two values, or their shared value if they are equal.
Java SE 21 provides four overloads: int, long, float, and double. Each takes two arguments of the same type and returns that type. The compiler selects an overload based on the argument types: for example, in Math.min(3, 5L) it converts 3 to long, and the result is a long.
For float and double, if either argument is NaN, the result is NaN. When the arguments are negative zero and positive zero, the method returns negative zero regardless of their order.
priority = Math.min(priority + 1, 5); computes the proposed priority and stores whichever is smaller: the proposal or 5. The method itself does not change priority; the assignment does. This sets only an upper limit: it does not raise a value that is too low.
Examples
public class Main {
public static void main(String[] args) {
int priority = 3;
for (int step = 0; step < 3; step++) {
priority = Math.min(priority + 1, 5);
System.out.println(priority);
}
}
}Result
4 5 5
The priority starts at `3`. The program prints `4`, `5`, and `5` on separate lines: the last increment proposes `6`, but the stored value is `5`.
Related lessons
- Java · Lesson 44 · Basic · Version: 2