Java Math min method example shows how to find a minimum of two numbers using the min
method of the Java Math class.
How to find a minimum of two numbers using Math class?
We can use the min
static method of the Java Math class to find a minimum of two numbers.
1 |
public static int min(int x, int y) |
This method returns a minimum of two integer numbers.
The min
method has been overloaded for double, float, and long data types so that the same method can be used for all of them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.javacodeexamples.mathexamples; public class FindMinNumberExample { public static void main(String[] args){ int i1 = -21; int i2 = -20; //find minimum of two integer numbers System.out.println( "Minimum Integer number: " + Math.max(i1, i2) ); long l1 = 2314l; long l2 = 1235l; //find minimum of two long numbers System.out.println( "Minimum long number: " + Math.max(l1, l2) ); float f1 = 7654.534f; float f2 = 7654.533f; //find minimum of two float numbers System.out.println( "Minimum float number: " + Math.max(f1, f2) ); double d1 = 58334.34d; double d2 = 58334.35d; //find minimum of two double numbers System.out.println( "Minimum double number: " + Math.max(d1, d2) ); } } |
Output
1 2 3 4 |
Minimum Integer number: -20 Minimum long number: 2314 Minimum float number: 7654.534 Minimum double number: 58334.35 |
How to find a minimum of 3 or more numbers?
Themin()
method of the Math class accepts only two arguments. So, a minimum of 3 numbers cannot be found directly using the min
method. However, we can find a min of 3 numbers like the below given example.
1 2 3 4 5 |
int a = 234; int b = 230; int c = 342; System.out.println( "Min of 3 numbers: " + Math.min( Math.min(a, b), c ) ); |
Output
1 |
Min of 3 numbers: 230 |
This example is a part of the Java Math class tutorial with examples.
Please let me know your views in the comments section below.