Java BigInteger Class | compareTo() Method with Example

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

BigInteger Class compareTo() method

  • compareTo() method is available in java.math package.
  • compareTo() method is used to compare to this BigInteger object with the given object or in other words we can say this method compares two objects of the "BigInteger" type.
  • compareTo() 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.
  • compareTo() method does not throw an exception at the time of comparing.

Syntax:

    public int compareTo(BigInteger ob);

Parameter(s):

  • BigInteger ob – represents the object to be compared to this BigInteger object.

Return value:

The return type of this method is int, it may return anyone of the given values,

  • When (this BigInteger) == (BigInteger ob), it returns 0.
  • When (this BigInteger) < (BigInteger ob), it returns -1.
  • When (this BigInteger) > (BigInteger ob), it returns 1.

Example:

// Java program to demonstrate the example 
// of int compareTo() method of BigInteger

import java.math.*;

public class CompareToOfBI {
    public static void main(String args[]) {
        // Initialize two variables str1 and str2
        String str1 = "60";
        String str2 = "100";

        // Initialize two BigInteger objects  
        BigInteger b_int1 = new BigInteger(str1);
        BigInteger b_int2 = new BigInteger(str2);

        // Display b_int1 and b_int2
        System.out.println("b_int1: " + b_int1);
        System.out.println("b_int2: " + b_int2);

        // compares two BigInteger values
        // and here it returns -1 when (this BigInteger) 
        // < (BigInteger b_int2)

        int compare = b_int1.compareTo(b_int2);
        System.out.println("b_int1.compareTo(b_int2): " + compare);

        // compares two BigInteger values
        // and here it returns 0 when (this BigInteger) 
        // == (BigInteger b_int1)

        compare = b_int1.compareTo(b_int1);
        System.out.println("b_int1.compareTo(b_int1): " + compare);

        // compares two BigInteger values
        // and here it returns 1 when (this BigInteger) 
        // > (BigInteger b_int1)

        compare = b_int2.compareTo(b_int1);
        System.out.println("b_int2.compareTo(b_int1): " + compare);
    }
}

Output

b_int1: 60
b_int2: 100
b_int1.compareTo(b_int2): -1
b_int1.compareTo(b_int1): 0
b_int2.compareTo(b_int1): 1


Comments and Discussions!

Load comments ↻





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