java.math.BigInteger compareTo(BigInteger val)

Description

On this document we will be showing a java example on how to use the compareTo(BigInteger val) method of BigInteger Class. Basically this method 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) 0), where is one of the six comparison operators.

Notes:

  • this method is specified by compareTo in interface Comparable<BigInteger>.

Method Syntax

public int compareTo(BigInteger val)

Method Argument

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

Method Returns

The compareTo() method returns -1, 0 or 1 as this BigInteger is numerically less than, equal to, or greater than val.

Compatibility

Requires Java 1.1 and up

Java BigInteger compareTo() Example

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

package com.javatutorialhq.java.examples;

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

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

public class BigIntegerCompareTotExample {

	public static void main(String[] args) {	
		
		// ask for two input
		System.out.print("Enter the first number:");
		Scanner s = new Scanner(System.in);
		String firstInput = s.nextLine();
		System.out.print("Enter the second number:");
		String secondInput = s.nextLine();
		s.close();
		
		// convert the string input to BigInteger
		BigInteger val1 = new BigInteger(firstInput);
		BigInteger val2 = new BigInteger(secondInput);
		
		int result = val1.compareTo(val2);
		// compare the two input
		if(result==1){
			System.out.println("First input is higher");
		}else if(result==-1){
			System.out.println("Second input is higher");
		}else{
			System.out.println("Both input are equal");
		}
		
		
				
	}

}

This example is a lot simpler than it looks. We simply ask the user for two inputs and convert these into BigInteger. The two values were then compared to each numerically and the result is printed based on the return value of the comapareTo() method.

Sample Output

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

BigInteger compareTo() example output