Java Long Max Method

JavaJavaBeginner
Practice Now

Introduction

The Long.max() method is used to return the numerically greater value (maximum value) of the two long numbers passed as arguments. It returns the positive value if one positive and one negative number is passed, and the value with lower magnitude if both the numbers passed are negative.

Create a Java file

We will create a Java file to write the code for this example. Open the terminal in Ubuntu and navigate to the project directory by running the following command:

cd ~/project/

Now, create a file named LongMaxExample.java by running below command:

touch LongMaxExample.java

Write the code

In the LongMaxExample.java file, write the below code:

public class LongMaxExample {
    public static void main(String[] args) {
        long a = 5485;
        long b = -3242;
        long c = -5645;

        long max1 = Long.max(a, b);
        long max2 = Long.max(b, c);

        System.out.println("The maximum of " + a + " and " + b + " is " + max1);
        System.out.println("The maximum of " + b + " and " + c + " is " + max2);
    }
}

Save and Compile the code

After writing the code, save the file and close the editor.

Compile the Java file using the below command:

javac LongMaxExample.java

Run the code

After successful compilation, you can run the code using the below command:

java LongMaxExample

This will give the following output:

The maximum of 5485 and -3242 is 5485
The maximum of -3242 and -5645 is -3242

User Input Demonstration

Write the following code to demonstrate how Long.max() can be used with user input:

import java.util.Scanner;

public class LongMaxExample {
    public static void main(String[] args) {
        try {
            Scanner sc= new Scanner(System.in);

            System.out.println("Enter the first number:");
            long num1 = sc.nextLong();
            System.out.println("Enter the second number:");
            long num2 = sc.nextLong();

            System.out.println("The maximum of " + num1 + " and " + num2 + " is " + Long.max(num1, num2));
        }
        catch(Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Save and Compile the code

After writing the code, save the file and close the editor.

Compile the Java file using the below command:

javac LongMaxExample.java

Run the code

After successful compilation, you can run the code using the below command:

java LongMaxExample

This will give the following output:

Enter the first number:
-5
Enter the second number:
8
The maximum of -5 and 8 is 8

Enter two long values and the program will output the maximum value of the two numbers.

Summary

Congratulation! You have learned the concepts and implementation of Java Long.max() method. This method helps in finding the maximum value of two long numbers. We have also demonstrated how to use this method in a program with user inputs.

Other Java Tutorials you may like