Java.math.BigInteger.compareTo() Method



The java.math.BigInteger.compareTo(BigInteger val) compares this BigInteger with the specified BigInteger. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=).

The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.


Following is the declaration for java.math.BigInteger.compareTo() method

public int compareTo(BigInteger val)

Specified by

compareTo in interface Comparable<BigInteger>


  • val - BigInteger to which this BigInteger is to be compared

Return Value

This method returns -1, 0 or 1 as this BigInteger is numerically less than, equal to, or greater than val.


  • NA


The following example shows the usage of math.BigInteger.compareTo() method

package com.tutorialspoint;

import java.math.*;

public class BigIntegerDemo {

public static void main(String[] args) {

        // create 2 BigInteger objects
        BigInteger bi1, bi2;

        bi1 = new BigInteger("6");
        bi2 = new BigInteger("3");

        // create int object
        int res;

        // compare bi1 with bi2
	res = bi1.compareTo(bi2);

        String str1 = "Both values are equal ";
	String str2 = "First Value is greater ";
	String str3 = "Second value is greater";

	if( res == 0 )
	System.out.println( str1 );
	else if( res == 1 )
	System.out.println( str2 );
	else if( res == -1 )
	System.out.println( str3 );

Let us compile and run the above program, this will produce the following result:

First Value is greater