Java Long compareTo Method

JavaJavaBeginner
Practice Now

Introduction

The Long class in Java provides various methods to perform operations on long values. The compareTo() method, belonging to the Long class, is used to compare two Long object values numerically. It returns 0 if the values are equal, -1 if the first value is less than the second value, or 1 if the first value is greater than the second one.

Create a Java file

Create a Java file named LongComparetoMethod.java in the ~/project directory.

cd ~/project
touch LongComparetoMethod.java

Declare and initialize Long objects

In this step, we will declare and initialize two Long objects.

Long longObj1 = 456789L;
Long longObj2 = 23456L;

Compare the Long objects using compareTo()

In this step, we will compare the two Long objects using the compareTo() method.

int result = longObj1.compareTo(longObj2);

Check the result

In this step, we will check the result of comparison.

if(result == 0) {
    System.out.println("Both Long objects are equal");
} else if(result > 0) {
    System.out.println("longObj1 is greater than longObj2");
} else {
    System.out.println("longObj1 is less than longObj2");
}

Compile and run the program

In this step, we will compile and run the Java program using the following commands:

javac LongComparetoMethod.java
java LongComparetoMethod

Test with different values

In this step, you can modify the program by changing the values of Long objects and check the results.

Long longObj1 = 25389L;
Long longObj2 = 6754L;

Use Try-Catch block

In this step, we will use a try-catch block if any invalid value is entered by the user.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter first long value: ");
Long longObj1 = null;
Long longObj2 = null;

try {
    longObj1 = scanner.nextLong();
    System.out.print("Enter second long value: ");
    longObj2 = scanner.nextLong();

} catch (InputMismatchException e) {
    System.out.println("Invalid input. Please enter a valid long value.");
    System.exit(0);
}

int rst = longObj1.compareTo(longObj2);

if (rst == 0) {
    System.out.println(longObj1 + " is equal to " + longObj2);
} else if (rst > 0) {
    System.out.println(longObj1 + " is greater than " + longObj2);
} else {
    System.out.println(longObj1 + " is less than " + longObj2);
}

Compile and Run the program

In this step, we will compile and run the Java program using the following commands:

javac LongComparetoMethod.java
java LongComparetoMethod

If the input value is invalid, an error message will be displayed, and the program will exit.

Summary

In this lab, we learned about the Java Long compareTo() method. We learned how to declare and initialize Long objects and use the compareTo() method to compare them numerically. We also learned how to handle invalid user input using the try-catch block.

Other Java Tutorials you may like