BigInteger equals() Method in Java
The java.math.BigInteger.equals(Object x) method compares this BigInteger with the object passed as the parameter and returns true in both are equal in value else it returns false.
Syntax:
public boolean equals(Object x)
Parameter: This method accepts a single mandatory parameter x which is the Object to which BigInteger Object is to be compared.
Returns: This method returns boolean true if and only if the Object passed as parameter is a BigInteger whose value is equal to the BigInteger Object on which the method is applied. Otherwise it will return false.
Examples:
Input: BigInteger1=2345, BigInteger2=7456 Output: false Explanation: BigInteger1.equals(BigInteger2)=false. Input: BigInteger1=7356, BigInteger2=7456 Output: true Explanation: BigInteger1.equals(BigInteger2)=true.
Below programs illustrate equals() method of BigInteger class:
Example 1: When both are equal in value.
// Java program to demonstrate equals() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger( "321456" ); b2 = new BigInteger( "321456" ); // apply equals() method boolean response = b1.equals(b2); // print result if (response) { System.out.println( "BigInteger1 " + b1 + " and BigInteger2 " + b2 + " are equal" ); } else { System.out.println( "BigInteger1 " + b1 + " and BigInteger2 " + b2 + " are not equal" ); } } } |
BigInteger1 321456 and BigInteger2 321456 are equal
Example 2: When both are not equal in value.
// Java program to demonstrate equals() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger( "321456" ); b2 = new BigInteger( "456782" ); // apply equals() method boolean response = b1.equals(b2); // print result if (response) { System.out.println( "BigInteger1 " + b1 + " and BigInteger2 " + b2 + " are equal" ); } else { System.out.println( "BigInteger1 " + b1 + " and BigInteger2 " + b2 + " are not equal" ); } } } |
BigInteger1 321456 and BigInteger2 456782 are not equal
Example 3: When object passed as parameter is other than BigInteger.
// Java program to demonstrate equals() method of BigInteger import java.math.BigInteger; public class Main6 { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger( "321456" ); String object = "321456" ; // apply equals() method boolean response = b1.equals(object); // print result if (response) { System.out.println( "BigInteger1 " + b1 + " and String Object " + object + " are equal" ); } else { System.out.println( "BigInteger1 " + b1 + " and String Object " + object + " are not equal" ); } } } |
BigInteger1 321456 and String Object 321456 are not equal
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#equals(java.lang.Object)
Please Login to comment...