Java - Double Class compare() Method

Double class compare() method: Here, we are going to learn about the compare() method of Double class with its syntax and example. By Preeti Jain Last updated : March 23, 2024

Double class compare() method

  • compare() method is available in Double class of java.lang package.
  • compare() method is used to check equality or inequality of the given two double values or in other words, we can say this method is used to compare two double values.
  • compare() method is a static method, it is accessible with the class name too and if we try to access the method with the class object then also, we will not get an error.
  • compare() method does not throw an exception at the time of comparing double values.

Syntax

public static int compare(double value1, double value2);

Parameters

  • double value1, double value2 – These parameters represent the double values to be compared.

Return Value

The return type of this method is int, it returns an integer value.

  • In the first case, it returns 0 if value1 is mathematically equals to value2.
  • In the second case, it returns the value < 0 if value1 is mathematically less than value2.
  • In the third case, it returns the value > 0 if value1 is mathematically greater than value2.

Example

// Java program to demonstrate the example 
// of compare(double value1,double value2) 
// method of Double class

public class CompareOfDoubleClass {
    public static void main(String[] args) {
        // Variables initialization
        double value1 = 18.20;
        double value2 = 20.20;

        // It compares two double values and 
        // returns the result in another variable (compare) 
        // of integer types
        int compare = Double.compare(value1, value2);

        // Display result
        System.out.println("Double.compare(value1,value2): " + compare);
        System.out.println();

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

Output

Double.compare(value1,value2): -1

value1 is less than value2

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.