java.lang.Math.min()
Description
- public static int min(int a, int b)
- public static long min(long a, long b)
- public static float min(float a, float b)
- public static double min(double a, double b)
The overloaded methods are basically the same, it’s just that they deal with different data type either int, long, float, and double
Most of the methods of the Math class is static and the min() method is no exception. Thus don’t forget that in order to call this method, you don’t have to create a new object. Use the method in the format Math.min(a).
Method Returns
The min() method returns which of the two values (a and b) have the lowest numerical value.
Compatibility
Requires Java 1.0 and up
Java Math min() Example
Below is a java code demonstrates the use of max() method of Math class. The example presented might be simple however it shows the behavior of the max() method.
package com.javatutorialhq.java.examples; import java.util.Scanner; /* * This example source code demonstrates the use of * min() method of Math class */ public class MathMinExample { public static void main(String[] args) { // Ask for user input System.out.print("Enter first value:"); // use scanner to read the console input Scanner scan = new Scanner(System.in); // Assign the 1st input to String variable String value1 = scan.nextLine(); // ask for the second input System.out.print("Enter second value:"); // Assign the 2nd input to String variable String value2 = scan.nextLine(); // close the scanner object scan.close(); // convert the values to int int a = Integer.parseInt(value1); int b = Integer.parseInt(value2); // get the result of min method int result = Math.min(a,b); System.out.print("Lowest value:"+result); } }
The above java example source code demonstrates the use of min() method of Math class. We simply ask for 2 user input and we use the Scanner class to parse it. Since we have used the nextLine() method to get the console value which is having a return data type of String thus we have used the Integer.parseInt to transform it into int. Alternatively if the requirements is to use long then you must use the Long.ParseLong() instead, Double.parseDouble() for double, and Float.parseFloat() for float. This conversion is required because the argument for min() method only accepts either int, long, double or float.