Home » Java programming language

Java Long Class compareTo() method with example

Long class compareTo() method: Here, we are going to learn about the compareTo() method of Long class with its syntax and example.
Submitted by Preeti Jain, on October 09, 2019

Long class compareTo() method

  • compareTo() method is available in java.lang package.
  • compareTo() method is used to check equality or inequality for this Long object against the given Long object mathematically or in other words, we can say this method is used to compare two Long objects.
  • compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • compareTo() method does not throw an exception at the time of comparing Long object.

Syntax:

    public int compareTo(Long value2);

Parameter(s):

  • Long value2 – represents the Long object to compare with.

Return value:

The return type of this method is int, it returns an integer value based on the following cases,

  • It returns 0, if value1 is mathematically equal to value2.
  • It returns the value < 0, if value1 is mathematically less than value2.
  • It returns the value > 0, if value1 is mathematically greater than value2.

Example:

// Java program to demonstrate the example 
// of compareTo(Long value2) method of Long class

public class CompareToOfLongClass {
    public static void main(String[] args) {
        // Variables initialization
        long l1 = 10;
        long l2 = 20;

        // Long instance 
        Long ob1 = new Long(l1);
        Long ob2 = new Long(l2);

        // It compares two Long objects and placed the result in 
        // another variable (compare) of integer type
        int compare = ob1.compareTo(ob2);

        // Display result
        System.out.println("ob1.compareTo(ob2): " + compare);
        System.out.println();

        if (compare == 0)
            System.out.println("ob1 is equal to ob2");
        else if (compare < 0)
            System.out.println("ob1 is less than ob2");
        else
            System.out.println("ob1 is greater than ob2");
    }
}

Output

ob1.compareTo(ob2): -1

ob1 is less than ob2






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.