Java Float Min Method

JavaJavaBeginner
Practice Now

Introduction

In some cases, we need to compare two floating-point numbers and determine which one is smaller. The Java 'Float' class provides a method min() that returns the smaller value out of two floating-point numbers passed to it.

Set up the project directory

Create a project directory named project in the home directory using the following command:

mkdir ~/project

Change directory to project directory using the following command:

cd ~/project

Create a Java file

To use min() method, we need to create a Java class. Run the following command to create a file named FloatMin.java.

touch FloatMin.java

Write the Java code

In this step, we will write the Java code that demonstrates the usage of min() method. Copy and paste the below code in the FloatMin.java file.

public class FloatMin {
    public static void main(String[] args) {
        float num1 = -27.56f;
        float num2 = -45.98f;
        float num3 = 68.3452f;
        float num4 = -94.456f;

        // Find the minimum of two numbers using Math.min() method
        float minNum1 = Math.min(num1, num2);
        float minNum2 = Math.min(num3, num4);

        System.out.println("Minimum of " + num1 + " and " + num2 + " is " + minNum1);
        System.out.println("Minimum of " + num3 + " and " + num4 + " is " + minNum2);
    }
}

Compile the Java file

Compile the FloatMin.java file using the following command:

javac FloatMin.java

Execute the Java program

Run the compiled code using the following command:

java FloatMin

You should see the following output:

Minimum of -27.56 and -45.98 is -45.98
Minimum of 68.3452 and -94.456 is -94.456

Summary

In this lab session, you have learned about the Java Float min() method and demonstrated its usage by finding the minimum value between two floating-point numbers.

Congratulations! You have successfully completed the Java Float min() Method lab.

Other Java Tutorials you may like