Java BigDecimal equals() Method with Example

BigDecimal Class equals() method: Here, we are going to learn about the equals() method of BigDecimal Class with its syntax and example.
Submitted by Preeti Jain, on May 03, 2020

BigDecimal Class equals() method

  • equals() method is available in java.math package.
  • equals() method is used to check whether this BigDecimal and the given object are equal or not and the two objects are equal when both the objects hold the same value and scale.
  • equals() 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.
  • equals() method does not throw an exception at the time of comparing.

Syntax:

    public boolean equals(Object ob);

Parameter(s):

  • Object ob – represents the object to be compared to this BigDecimal object.

Return value:

The return type of this method is boolean, it returns true when both objects are of "BigDecimal" type and both holds the same value and scale otherwise it returns false.

Example:

// Java program to demonstrate the example 
// of boolean equals(Object ob) method of BigDecimal

import java.math.*;

public class EqualsOfBD {
    public static void main(String args[]) {
        // Initialize two variables first is
        // of "double" and second is of "String"
        // type
        double d = 587.0;
        String str = "587.00";

        // Initialize two BigDecimal objects  
        BigDecimal b_dec1 = new BigDecimal(d);
        BigDecimal b_dec2 = new BigDecimal(str);


        // By using equals() method, we are comparing
        // this BigDecimal (b_dec1) to the given
        // BigDecimal b_dec2 and here it returns
        // false because they are equal in value
        // but not in terms of scale
        boolean compare = b_dec1.equals(b_dec2);
        System.out.println("b_dec1.equals(b_dec2): " + compare);

        // By using equals() method, we are comparing
        // this BigDecimal (b_dec1) to the given
        // BigDecimal b_dec2 and here it returns
        // true because they both are equal in value
        // and scale
        compare = b_dec1.equals(b_dec1);
        System.out.println("b_dec1.equals(b_dec1): " + compare);
    }
}

Output

b_dec1.equals(b_dec2): false
b_dec1.equals(b_dec1): true


Comments and Discussions!

Load comments ↻





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