The Java.lang.math.min() function is an inbuilt function in java that returns the minimum of two numbers. It supports the following primitive data types: int, long, float, double.
Behaviour Notes:
- If one value is negative and the other is positive, the negative value is returned.
- If both values are negative, the value with the greater magnitude (more negative) is returned.
- For floating-point values:
- If one argument is NaN, the result is NaN
- -0.0 is considered smaller than 0.0
Example:
public class GFG {
public static void main(String[] args) {
double a = 15;
double b = 11;
System.out.println(Math.min(a, b));
}
}
Output
11.0
Syntax
static dataType min(dataType a, dataType b)
Parameters:
- a: first numeric value
- b: second numeric value
Both parameters must be of the same primitive type.
Return value: Returns the minimum of the two values. The return type is the same as the argument type.
Example 1: Minimum of Two double Values
This short example demonstrates how Math.min() works with floating-point numbers.
public class GFG {
public static void main(String[] args) {
double a = 12.123;
double b = 12.456;
System.out.println(Math.min(a, b));
}
}
Output
12.123
Explanation: Two double values are passed to Math.min(). The method compares both values and returns the smaller one.
Since 12.123 < 12.456, the output is 12.123.
Example 2: One Positive and One Negative Integer
The behavior of Math.min() is shown, when one value is negative.
public class GFG {
public static void main(String[] args) {
int a = 23;
int b = -23;
System.out.println(Math.min(a, b));
}
}
Output
-23
Explanation: The method compares a positive and a negative integer. Negative numbers are always smaller than positive numbers.
Therefore, -23 is returned as the minimum value.
Example 3: Two Negative Integers
Math.min() compares two negative values.
public class GFG {
public static void main(String[] args) {
int a = -25;
int b = -23;
System.out.println(Math.min(a, b));
}
}
Output
-25
Explanation: Both integers passed to Math.min() are negative. The value with the greater negative magnitude is considered smaller.
Hence, -25 is returned as it is less than -23.
Using Static Import for Cleaner Code
If Math.min() is used frequently, you can statically import the method to avoid repeated class qualification.
import static java.lang.Math.min;
class GFG {
public static void main(String[] args) {
int a = 3;
int b = 4;
System.out.println(min(a, b));
}
}
Output
3
Explanation: The min() method is statically imported from java.lang.Math. This allows calling min() directly without the Math class name.
The method compares 3 and 4 and returns 3.