The minimum values are identified to find the least value from the provided data. It is calculated to gather information about the least-working product or the one that generates the least revenue. To perform the mentioned operation, the “Math.min()” method is used in Java. This method accepts a couple of arguments and returns the minimum value argument accordingly.
This article covers the following aspects:
- How to Use Math.min() Method in Java?
- Find Minimum Value From Array Via “Math.min()” Method
- Enhanced Implementation of “Math.min()” Method
- Alternatives of “Math.min()” Method in Java
How to Use Math.min() Method in Java?
The “Math.min()” method accepts two values as an argument and, according to the provided values, returns the argument that holds the minimum value. It is very efficient and can work with any data type argument like “int”, “float”, “double”, and “long”. The “Math.min()” method provides the most efficient result when dealing with negative arguments as well.
Syntax
Let’s take a look at the syntax of a “java.lang.Math.min()” method:
public static dataType Math.min(dataType firstArg, dataType secondArg)
In the above syntax:
- The “firstArg” and “secondArg” are the two arguments that can have one of the following data types: “int”, “double”, “long”, or “float”.
- The “public static” keywords specify the scope and make the method available from any part of the program.
Return Type
The returned argument data type of the “Math.min()” method will be the same as the data type of the specified argument values.
Let’s take a look over the most faced scenarios for returned value according to the provided arguments data type or values:
- If both arguments are “positive” then the argument with the minimum value will be returned by the “Math.min()” method in Java.
- If both arguments are “negative” then the argument with a higher magnitude will be returned by the mentioned method.
- If one argument is not a number “NaN” then the output of “Nan” will be returned as the minimum value by the “Math.min()” method.
- If one argument is negative and the other one is positive then the “negative” value argument will be considered as the minimum value and returned by the stated method.
After understanding the working and syntax structure of the “math.min()” method. Let’s walk through multiple examples to practically implement the discussed scenarios:
Example 1: Use of “Math.min()” Method With Positive Arguments
In this example, two positive argument values are passed to the “Math.min()” method to efficiently find the minimum value:
public class javabeat {
public static void main(String args[])
{
int firstArg = 25;
int secondArg = 45;
int output = Math.min(firstArg, secondArg);
System.out.println("The minimum Value From Provided Data is: " + output);
}}
The explanation of the above code is shown below:
- Inside the main “public” type class “javabeat”, two “int” type variables are declared and initialized with dummy positive values.
- Then, both of these variables are passed as arguments for the “Math.min()” method. This function returns the argument having the minimum value. The output of this method is stored in a new “int” type variable named “output”.
- Finally, the “output” variable storing the result is displayed on the console via the “System.out.println()” method.
The output generated after the compilation of the above code block shows that the minimum argument value has been returned by the “Math.min()” method:
The user can also directly insert values as an operand instead of variables storing values in the “Math.min()” method. The below gif shows the direct insertion of values as an operand:
Example 2: Use of “Math.min()” Method With Negative Arguments
In this case, both “negative” values are passed as arguments to the “Math.min()” method to find the minimum number:
public class javabeat {
public static void main(String args[])
{
int firstArg = -25;
int secondArg = -45;
int output = Math.min(firstArg, secondArg);
System.out.println("The minimum Value From Provided Data is: " + output);
}
}
In the above code:
- Two variables namely “firstArg” and “secondArg” are declared and initialized with the negative values.
- These variables are then passed as an argument to the “Math.min()” method in order to find the variable having the minimum value.
- Finally, the output of the “Math.min()” method is displayed on the console.
The output of the above code shows that the minimum negative value has been retrieved:
Example 3: Use of “Math.min()” Method With Positive and Negative Arguments
In this case, both positive and negative arguments are passed into the “Math.min()” method to retrieve the minimum number:
public class javabeat {
public static void main(String args[])
{
int firstArg = +25;
int secondArg = -45;
int output = Math.min(firstArg, secondArg);
System.out.println("The minimum Value From Provided Data is: " + output);
}
}
In the above code:
- The positive and negative values are assigned to the “firstArg” and “secondArg” variables, respectively.
- Then, to find the minimum value these variables are passed into the “Math.min()” method and the result is stored in the “output” variable.
- This variable is then displayed on the console window via the “System.out.println()” method.
Output generated in the response of the above code shows that the minimum value has been returned by the “Math.min()” method:
Example 4: Use of “Math.min()” Method With NaN(Not a Number) as Argument
In this example, the “NaN(Not a Number)” and the negative value having the primitive data type of “Double” are passed as an argument in the “Math.min()” method to find the minimum number. The result will be “NaN” because the “Math.min()” method always considers “NaN” as an entity with the minimum value, as shown in the code snippet:
public class javabeat {
public static void main(String args[])
{
Double firstArg = Double.NaN;
Double secondArg = -4.5;
Double output = Math.min(firstArg, secondArg);
System.out.println("\nThe minimum Value From Provided Data is: " + output);
}
}
In the above code:
- The “Double” type variables “firstArg” and “secondArg” are initialized and the double type “NaN” is stored as a value for the “firstArg” variable.
- The dummy “negative” value is stored in “secondArg” and both are passed as arguments for the “Math.min()” method.
- The result of this method is stored in the “output” variable which is then displayed on the console.
Output for the above code shows that “NaN” (Not a Number) is returned by the “Math.min()” method as the minimum value:
Example 5: Use of “Math.min()” Method With Different Primitive Data Types as Argument
The “Math.min()” method can be utilized with any datatype arguments and the values can be negative or positive according to requirements. For instance, the arguments with different primitive data type values are being passed into the “Math.min()” method to find the minimum value, as shown below:
public class javabeat {
public static void main(String args[])
{
int arg1 = 238;
int arg2 = 738;
System.out.println("\nMinimum Integer Value: " + Math.min(arg1, arg2));
long arg3 = 222112L;
long arg4 = 239898L;
System.out.println("\nMinimum Long Value: " + Math.min(arg3, arg4));
float arg5 = 4.5f;
float arg6 = 9.67f;
System.out.println("\nMinimum Long Value: " + Math.min(arg5, arg6));
double arg7 = 19.23;
double arg8 = 41.73d;
System.out.println("\nMinimum Double Value: " + Math.min(arg7, arg8));
}
}
Explanation of the above code:
- First, two variables with the data type of “int” are created namely “arg1” and “arg2”. These variables are then passed into the “Math.min()” method and the result is displayed on the console.
- Next, the “long” data type variables namely “arg3” and “arg4” are created and passed into the “Math.min()” method. The returned value from this method is then displayed on the console.
- In the same manner, the variables with data types of “float” and “double” are created and passed into the “Math.min()” method. Finally, the corresponding results are displayed on the console window.
Output for the above code confirms that minimum values for provided variables in different data types have been retrieved:
Example 6: Use of “Math.min()” Method To Find Minimum Value Based on User Input
The method provided by the “Scanner” class is used to get data from the user at run time and this data is then passed to the “Math.min()” method to find the minimum value. Utilize the nested “Math.min()” method to find the minimum of more than two values because it only accepts two arguments. Take a look at the below code block for the practical implementation of both discussed scenarios:
import java.util.Scanner;
public class javabeat {
public static void main(String args[])
{
Scanner insert = new Scanner(System.in);
System.out.print("Enter the First Number: ");
int a = insert.nextInt();
System.out.print("Enter the Second Number: ");
int b = insert.nextInt();
System.out.print("Enter the third Number: ");
int c = insert.nextInt();
System.out.print("The Minimum Value From Provided Data is : " + Math.min(Math.min(a, b), c));
insert.close();
}
}
Explanation of the above code block is as follows:
- First, the java “Scanner” utility is imported, and the class of “javabeat” containing the “main()” method is created.
- Next, create an “insert” instance of the “Scanner” utility and pass the “System.in” as the constructor parameter. This allows the programmer to select a value inserted by the user.
- Utilize the “System.out.print()” method to display messages over the console related to the input values. Along with that, invoke the “nextInt()” method using the “insert” variable to select the inputted data in response to the displayed message.
- Using this approach gather three values based on user inputs and store them in “i”, “j”, and “k” variables respectively.
- Now, utilize the main “Math.min()” method, and as its first parameter utilize another “Math.min()” method containing two arguments of “a” and “b”. In addition, pass the remaining “c” variable as a second argument to the outer “Math.min()” method. In this way, the minimum value from three variables gets calculated.
- Finally, display the returned result on the console for code verification and apply the “close()” method on the Scanner instance “insert”.
The generated output shows that the minimum values according to the user requirements have been retrieved:
Bonus Tip 1: Find Minimum Value From Array Via “Math.min()” Method
The “Math.min()” method can be utilized to find the minimum value residing inside the data structures like “arrays”, “list”, “hashmap” or “LinkedList”. For instance, the minimum value residing inside the provided array is going to be retrieved using the “Math.min()” method in below code snippet:
public class javabeat {
public static void main(String args[])
{
int[] providedArr = {30, 20, 10, 40, 50};
int min = providedArr[0];
for (int j = 0; j < providedArr.length; j++)
{
System.out.println("Elements of Array: " + providedArr[j]);
min = Math.min(min, providedArr[j]);
}
System.out.println("\nMinimum Value Residing in the Array is: " + min);
}
}
The above code works like this:
- First, create a class named “javabeat” and it contains the “main()” method from which the compilation process gets started.
- Inside the method, create an array named “providedArr” containing random numerical values and set its first index “0” as a value for the “min” variable.
- Next, utilize the “for” loop that iterates till the length of an array. Inside the loop, use the println() to print the entries or elements stored in the array on the console.
- Moreover, apply the “Math.min()” method that identifies the minimum value by checking each array element with the value stored in the “min” variable.
- If the array value is less than the one stored in the “min” variable then that array value is stored in the “min” variable.
- In this way, the “min” variable contains the minimum value which is then displayed on the console after exiting from the loop scope.
The generated output for the above code shows that the elements residing in the array are displayed and the minimum value is also retrieved and displayed:
Bonus Tip 2: Enhanced Implementation of “Math.min()” Method
If the programmer is required to use the “Math.min()” method multiple times at various positions in the code. Then it is a headache and time-consuming procedure to write the whole method repeatedly. To prevent this repetition and save time, it is better to import the library in your file and only use the method name “min()” instead of “Math.min()”. The below code block shows the enhanced implementation of the “Math.min()” method:
import static java.lang.Math.min;
public class javabeat {
public static void main(String args[])
{
int firstArg = 238;
int secondArg = 738;
System.out.println("\nVia Enhanced Form: " + min(firstArg, secondArg));
}
}
The above code works like this:
- First, import the “java.lang.Math.min” library into the currently working “.java” file.
- Then, create a public class “javabeat” and initialize the “main()” method in it. Inside the method, declare and initialize two variables “firstArg” and “secondArg” with random values.
- After that, pass both of these variables into the “min()” method and it will work exactly like the “Math.min()” method and display the output on the console.
The output after the compilation confirms that the minimum value has been retrieved and displayed on the console:
Alternatives of “Math.min()” Method in Java
The “Math.min()” method functionality can be easily created by the combination of an “if/else” statement and the less than “<” logical operator. This alternative scenario is practically demonstrated below:
public class javabeat {
public static void main(String args[])
{
double i = 4.34, j = 4.00034;
double minimum;
if (i < j) {
minimum = i;
} else {
minimum = j;
}
System.out.println("The minimum value is: " + minimum);
}
}
The above code works like this:
- First, the class “javabeat” containing the “main()” method is created. Inside it declares and initializes two variables namely “i” and “j” having random numerical values.
- Next, utilize the “if” conditional statement that uses the “less than” operator to check if the value stored in the “i” variable is less than the value stored in the “j” variable or not.
- If the condition returns true, store the value of the “i” variable in the “minimum” variable. Otherwise, store the value of the “j” variable in the “minimum” variable.
- Finally, display the “minimum” variable on the console.
The output shows that the minimum value has been retrieved and displayed on the console:
This guide has explained the working of a Math.min() method in Java.
Conclusion
To use the “Math.min()” method in Java, pass two variables from which the minimum value needs to be found as arguments and the method returns the smallest value argument. If one of the operand values is negative, then the negative value will be returned and it can be worked with all primitive data types like int, float, double, and long. If one operand is NaN(Not a Number) then the result will always be “NaN”. This guide has explained the working and implementation of the Math.min() method in Java.