How to find min() of two numbers in Java?
Java provides a system library known as “java.lang.Math” for extensive handy operations. From trigonometry to logarithmic functions, you can find min/max or even absolute of a number using the methods provided by this library due to its diverse functionalities.Math.min() Method
Here’s a regular representation of the method.
Math.min(a, b)
Kindly note that this function accepts two parameters of same types int, long, float or double.
Let’s look at an executable example of the Math.min() method to understand an effective use of it. Make sure you run the script in your IDE to validate the outputs.Example 1
package com.math.min.core
public class MathMinMethod {
public static void main(String[] args) {
int leenasAge = 10;
int tiffanysAge = 15;
// example of min () function
int min = Math.min(leenasAge, tiffanysAge);
System.out.print("Who's the younger sister? ");
if (min < tiffanysAge)
System.out.print("Leena ------- Age " + leenasAge);
else
System.out.print("Tiffany ------- Age " + tiffanysAge);
}
}
Output
Who's the younger sister? Leena ------- Age 10
Explanation
At line 8, int min = Math.min(leenasAge, tiffanysAge); int min stores the minimum number returned by the min() function. Later we use that result to find the age of the smaller sibling.Example 2
package com.math.min.core;
public class MathMinMethod {
public static void main(String[] args) {
double berriesSoldInKg = 15.6;
double cherriesSoldInKg = 21.3;
// example of min () function
double min = Math.min(berriesSoldInKg, cherriesSoldInKg);
System.out.println("What's the minimum weight sold?");
if (min != cherriesSoldInKg)
System.out.print("Berries: " + berriesSoldInKg + " kg");
else
System.out.print("Cherries: " + cherriesSoldInKg +"kg");
}
}
Output
What's the minimum weight sold?
Berries: 15.6 kg
GO TO FULL VERSION