java.math.BigInteger equals(Object x)

Description

On this document we will be showing a java example on how to use the equals(Object x) method of BigInteger Class. Basically this method check if this BigInteger is equal to the Object method argument. In dealing with primitive data types we usually use the ‘==’ as a way to check the equality of two numbers however in dealing with Objects, it’s a rule to use the equals() method.

Notes:

  • this method overrides equals in class Object

Method Syntax

public boolean equals(Object x)

Method Argument

Data Type Parameter Description
Object x Object to which this BigInteger is to be compared.

Method Returns

The equals() method true if and only if the specified Object is a BigInteger whose value is numerically equal to this BigInteger.

Compatibility

Requires Java 1.1 and up

Java BigInteger equals() Example

Below is a java code demonstrates the use of equals() method of BigInteger class. The example presented might be simple however it shows the behavior of the equals() method.

package com.javatutorialhq.java.examples;

import java.math.BigInteger;
import java.util.Scanner;

/*
 * A java example source code to demonstrate
 * the use of equals() method of BigInteger class
 */

public class BigIntegerEqualsValueExample {

	public static void main(String[] args) {	
		
		// Declare and initialize our BigInteger values
		BigInteger val1 = new BigInteger("12");
		BigInteger val2 = new BigInteger("12");
		BigInteger val3 = new BigInteger("15");

		// compare the three BigIntegers
		boolean result = val1==val2;
		System.out.println("val1=va2 is "+result);
		result = val1.equals(val1);
		System.out.println("val1.equals(val1) is "+result);
		result = val1.equals(val3);
		System.out.println("val1.equals(val3) is "+result);
	}

}


This example is a lot simpler than it looks. The first part is the declaration of three BigIntegers val1,val2,val3. The values is declared in such a way that val1 and val2 is numerically equal. There were three comparisons made, the first one is to compare val1 and val2 using the == operator. Even though val1 and val2 is numerically equal, since we used the == operator it will still result to false which is ambiguous. Moreover the two result is making use of the equals method which gives the right result.

Sample Output

Below is the sample output when you run the above example.

BigInteger equals() example output