Home Communities
IT Knowledge
Inspiration
Languages
EN

# Java - Math.min() method example

0 points
Created by:
384

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 ``````package java.lang; public final class Math { public static double min(double number1, double number2) { ... } public static float min(float number1, float number2) { ... } public static int min(int number1, int number2) { ... } public static long min(long number1, long number2) { ... } }`````` Note: Classes in the `java.lang` package are imported automatically, so it is not necessary to do it manually - we use just `Math.min()` call. Parameters `number1, number2 -` values to compare. Result Minimal `number` value (primitive value). It returns `NaN` if at least one of the provided values is not a number. 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
}
}``````

## References

1. Maxima and minima - Wikipedia

Join to our subscribers to be up to date with content, news and offers.