Java Long Min Method

JavaJavaBeginner
Practice Now

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.

Import Required Packages

Import the required package java.lang.Long to use the Long class.

import java.lang.Long;

Define main() Method

Define the main() method that will execute the code block.

public static void main(String[] args) {
    // Code block goes here
}

Declare long Variables

Declare three long variables.

long num1 = 1000L;
long num2 = -2000L;
long num3 = -3000L;

Use Long min() Method to Find the Smaller Number

Use 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);

Use Long min() Method for Negative Numbers

Use 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);

User Input Example

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 User Input

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();

Return the Smaller Value

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);

Execute the Program

To execute the program, run the following commands in the terminal.

```bash
javac LongMinDemo.java
java LongMinDemo
```

Summary

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.

Other Java Tutorials you may like