Introduction
In this lab, we will learn how to use the Java Long min()
method and how it returns the smaller number between two long values.
In this lab, we will learn how to use the Java Long min()
method and how it returns the smaller number between two long values.
Import the required package java.lang.Long
to use the Long
class.
import java.lang.Long;
main()
MethodDefine the main()
method that will execute the code block.
public static void main(String[] args) {
// Code block goes here
}
Declare three long variables.
long num1 = 1000L;
long num2 = -2000L;
long num3 = -3000L;
Long min()
Method to Find the Smaller NumberUse the Long min()
method to find the smaller number between num1
and num2
. Then, print the result.
long smallerNum = Long.min(num1, num2);
System.out.println("The smaller number between " + num1 + " and " +
num2 + " is " + smallerNum);
Long min()
Method for Negative NumbersUse the Long min()
method to find the appropriate smaller number between two negative numbers. Print the result.
smallerNum = Long.min(num2, num3);
System.out.println("The smaller number between " + num2 + " and " +
num3 + " is " + smallerNum);
Let's create a program that allows users to input two long values and returns the smaller value using the Long min()
method. First, import the java.util.Scanner
package to read user input.
import java.util.Scanner;
Read two long values from the user using the Scanner
class and assign them to the num1
and num2
variables.
Scanner input = new Scanner(System.in);
System.out.println("Enter the first long number: ");
long num1 = input.nextLong();
System.out.println("Enter the second long number: ");
long num2 = input.nextLong();
Using the Long min()
method, find the smaller number between the two user input values and print the result.
long smallerNumber = Long.min(num1, num2);
System.out.println("The smaller number between " + num1 + " and " +
num2 + " is " + smallerNumber);
To execute the program, run the following commands in the terminal.
```bash
javac LongMinDemo.java
java LongMinDemo
```
The Long min()
method is used to return the numerically smaller value(minimum value) of the two numbers(long) passed as arguments. When a positive and negative number are passed, the negative value is returned, but if both numbers are negative, the value with a higher magnitude is returned. In this lab, we learned step by step how to use the Long min()
method with examples.