EN
Java - Math.min() method example
0
points
The Math.min()
function returns the smallest number from given numbers.
public class MathExample {
public static void main(String[] args) {
int min = Math.min(2, 5);
System.out.println( min ); // 2
System.out.println( Math.min(1, 2) ); // 1
System.out.println( Math.min(1.5, 2.0) ); // 1.5
System.out.println( Math.min(2, Float.NaN) ); // NaN
}
}
1. Documentation
Syntax |
|
Parameters | number1, number2 - values to compare. |
Result |
Minimal It returns |
Description | min is a static method that takes number arguments and returns the smallest one value. |
2. Getting min value from array examples
2.1. With Collections.min
method example
public class MathExample {
public static void main(String[] args) {
Integer[] numbersArray = { 1, 5, 2, 16, -5};
int min = Collections.min( Arrays.asList(numbersArray) );
System.out.println( min ); // -5
}
}
2.2. By comparing all the elements in the array
public class MathExample {
static double min(double[] array) {
double result = Double.POSITIVE_INFINITY;
for (double currentNumber : array) {
if (result > currentNumber) result = currentNumber;
}
return result;
}
public static void main(String[] args) {
double[] numbersArray = {1.4, 5.0, 2.2, 16.0, -5.0};
System.out.println( min(numbersArray) ); // -5.0
}
}