VOOZH about

URL: https://www.geeksforgeeks.org/java/java-double-compareto-method/

⇱ Java Double.compareTo() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Double.compareTo() Method

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:

  • equal to 0: Object is equal to the argument object.
  • less than 0: Object is less than the argument object.
  • greater than 0: Object is greater than the argument object.

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.


Output
obj1 is less than obj2


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

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.

Output:

error: incompatible types: String cannot be converted to Double


Important Points:

  • Always make sure the object passed to compareTo() method is of type Double.
  • Do not use raw objects like Object in compareTo() for wrapper classes, always prefer using the typed version.
  • For comparing primitive double values directly, consider using Double.compare(double d1, double d2).
Comment
Article Tags: