EN
Java - Math.min() method example
0 points
The Math.min()
function returns the smallest number from given numbers.
xxxxxxxxxx
1
public class MathExample {
2
3
public static void main(String[] args) {
4
int min = Math.min(2, 5);
5
System.out.println( min ); // 2
6
7
System.out.println( Math.min(1, 2) ); // 1
8
System.out.println( Math.min(1.5, 2.0) ); // 1.5
9
10
System.out.println( Math.min(2, Float.NaN) ); // NaN
11
}
12
}
Syntax |
xxxxxxxxxx 1 package java.lang; 2 3 public final class Math { 4 5 public static double min(double number1, double number2) { ... } 6 public static float min(float number1, float number2) { ... } 7 public static int min(int number1, int number2) { ... } 8 public static long min(long number1, long number2) { ... } 9 10 }
|
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. |
xxxxxxxxxx
1
public class MathExample {
2
3
public static void main(String[] args) {
4
Integer[] numbersArray = { 1, 5, 2, 16, -5};
5
6
int min = Collections.min( Arrays.asList(numbersArray) );
7
System.out.println( min ); // -5
8
}
9
}
xxxxxxxxxx
1
public class MathExample {
2
3
static double min(double[] array) {
4
double result = Double.POSITIVE_INFINITY;
5
for (double currentNumber : array) {
6
if (result > currentNumber) result = currentNumber;
7
}
8
return result;
9
}
10
11
public static void main(String[] args) {
12
double[] numbersArray = {1.4, 5.0, 2.2, 16.0, -5.0};
13
14
System.out.println( min(numbersArray) ); // -5.0
15
}
16
}