Introduction
In this lab, you will learn about the max()
method of the Float
class in Java. This method returns the greater of two float values passed to it as parameters.
In this lab, you will learn about the max()
method of the Float
class in Java. This method returns the greater of two float values passed to it as parameters.
In the first step, create a new Java file named "FloatMax.java" in the ~/project
directory.
touch ~/project/FloatMax.java
java.lang.Float
The max()
method is a part of the Float
class of the java.lang
package. In order to use this method, you must include the java.lang.Float
package in your code. Add the following line at the beginning of the "FloatMax.java" file:
import java.lang.Float;
Declare two float type variables and assign them some values. Here, we assign the variables a
and b
the values 7.5 and 6.2, respectively.
float a = 7.5f;
float b = 6.2f;
Float.max()
to find the maximum of two float valuesUse the Float.max()
method to find the greater value of the two variables a
and b
. Assign the result to a third float type variable max
.
float max = Float.max(a, b);
Finally, print the result using the System.out.println()
method.
System.out.println("The maximum of " + a + " and " + b + " is " + max);
Compile and run the "FloatMax.java" file using the following commands in the terminal:
cd ~/project
javac FloatMax.java
java FloatMax
Scanner
class to get input from the userImport the java.util.Scanner
package. Create a new instance of the Scanner
class to take input from the user. Read two float numbers from the user and store them in a
and b
variables, respectively.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a float number: ");
float a = scanner.nextFloat();
System.out.println("Enter another float number: ");
float b = scanner.nextFloat();
Float.max()
to find the maximum of two float valuesUse the Float.max()
method to find the greater value of the two variables a
and b
. Assign the result to a third float type variable max
.
float max = Float.max(a, b);
Finally, print the result using the System.out.println()
method.
System.out.println("The maximum of " + a + " and " + b + " is " + max);
In this lab, you learned about the max()
method of the Float
class in Java. You also learned how to import packages, declare variables, use the System.out.println()
method to print results, and how to take input from the user using the Scanner
class. Now you can use the Float.max()
method to find the greater value of any two float numbers you want!