Java Double.compareTo() Method (original) (raw)

Last Updated : 15 May, 2025

The **Double.compareTo() method is a built-in method in Java of java.lang package. This method is used to compare two **Double objects numerically. This method returns 0 if this object is equal to the argument object, it returns less than 0 if this object is numerically less than the argument object, and a value greater than 0 if this object is numerically greater than the argument object.

In this article, we are going to learn about the **Double.compareTo() method in Java with examples.

Syntax of Double.compareTo() Method

public int compareTo(Double anotherDouble)

**Parameter: **obj: The object that is to be compared to.

**Return Values: The function can return three values:

**Note: This method only accepts a Double object as an argument. If we pass anything else or no argument at all, it will result in a compile-time error.

Examples of Java Double.compareTo() Method

**Example 1: In this example, we are going to compare two different **Double objects.

Java `

// Java program to demonstrate Double.compareTo() method import java.lang.Double;

public class Geeks {

public static void main(String[] args) {
    
    Double obj1 = new Double(124);
    Double obj2 = new Double(167);

    int compareValue = obj1.compareTo(obj2);

    if (compareValue == 0)
        System.out.println("obj1 and obj2 are equal");
    else if (compareValue < 0)
        System.out.println("obj1 is less than obj2");
    else
        System.out.println("obj1 is greater than obj2");
}

}

`

Output

obj1 is less than obj2

**Example 2: In this example, we are going to pass no argument and see what happens.

Java `

// No argument passed import java.lang.Double;

public class Geeks {

public static void main(String[] args) {
    Double obj1 = new Double(124);

    // This will result in a compile-time error
    int result = obj1.compareTo(); 
}

}

`

**Output:

error: method compareTo in class Double cannot be applied to given types;
int result = obj1.compareTo();
^
required: Double
found: no arguments
reason: actual and formal argument lists differ in length

**Example 3: In this example, we are going to pass a non-Double object.

Java `

// Passing incompatible type import java.lang.Double;

public class Geeks {

public static void main(String[] args) {
    Double obj1 = new Double(124);

    // This will also result in a compile-time error
    int result = obj1.compareTo("gfg"); 
}

}

`

**Output:

error: incompatible types: String cannot be converted to Double

**Important Points: