CodeGym /Java Blog /Java Math /Java Math.min() method
Author
Volodymyr Portianko
Java Engineer at Playtika

Java Math.min() method

Published in the Java Math group

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

Explanation

At line 8, double min = Math.min(berriesSoldInKg, cherriesSoldInKg); the double “min” stores the lowest of both weights. Later, we compare two doubles (amount in kgs) to check the minimum of the two fruits. That result can be used according to your requirements in any case.

Conclusion

By now you’d be able to understand the need and efficiency of Math.min() method. However, in case of any query or confusion feel free to consult this article again. Keep growing and practising!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION