Thursday, April 7, 2022

BigInteger in Java With Examples

Java BigInteger class is used where the operations involve holding and storing huge integer values that are beyond the limit of primitive data types like int and long. Though not very common but you may come across such scenarios, for example if you have to calculate factorial of 25 that will have 26 digits in it.

Max value of int and long is–

System.out.println("int max value - " + Integer.MAX_VALUE);
System.out.println("long max value - " + Long.MAX_VALUE);

Output

int max value - 2147483647
long max value – 9223372036854775807

So you can see that neither int nor long can hold the value of 25!. That’s when enters BigInteger.


Java BigInteger class

BigInteger class can hold very big integers. Since it’s a class and you will use an object of this class so memory can be dynamically allocated to a BigInteger type and it can theoretically store a number that the memory of your system can hold.

BigInteger class in Java extends Number and also implements Comparable interface.

public class BigInteger extends Number implements Comparable<BigInteger> {

}

BigInteger Java Example

As we already talked about the factorial of 25 so let’s try to do that itself using BigInteger.

public class First {
  public static void main(String[] args) {
    First first = new First();       
    first.factorial(25);
  }

  private void factorial(int count){
    BigInteger fact = BigInteger.ONE; 
    for (int i = 2; i <= count; i++){
      fact = fact.multiply(BigInteger.valueOf(i));
    }
    System.out.println("fact " + fact);  
  }
}

Output

15511210043330985984000000

Fields in BigInteger class

Following are the static fields in java.math.BigInteger class-

  • static BigInteger ONE- The BigInteger constant one.
  • static BigInteger TEN- The BigInteger constant ten.
  • static BigInteger TWO- The BigInteger constant two. Added in Java 9.
  • static BigInteger ZERO- The BigInteger constant zero.

If you have noticed in the example code above BigInteger.ONE is used to initialize the BigInteger object.

Java BigInteger Constructors

There are six constructors provided in the BigInteger class in Java-

  • BigInteger(byte[] val)- Translates a byte array containing the two's-complement binary representation of a BigInteger into a BigInteger.
  • BigInteger(int signum, byte[] magnitude)- Translates the sign-magnitude representation of a BigInteger into a BigInteger.
  • BigInteger(int bitLength, int certainty, Random rnd)- Constructs a randomly generated positive BigInteger that is probably prime, with the specified bitLength.
  • BigInteger(int numBits, Random rnd)- Constructs a randomly generated BigInteger, uniformly distributed over the range 0 to (2numBits - 1), inclusive.
  • BigInteger(String val)- Translates the decimal String representation of a BigInteger into a BigInteger.
  • BigInteger(String val, int radix)- Translates the String representation of a BigInteger in the specified radix into a BigInteger.

Features of BigInteger in Java

  1. No Overloaded operators– In Java arithmetic operators (+, -, *, /) are not permitted with objects so these operators are not used with BigInteger numbers, you will have to use method calls instead. BigInteger class has methods add, subtract, multiply, divide and remainder for the arithmetic operations.
    BigInteger bint = new BigInteger("56");
    BigInteger res = BigInteger.valueOf(45).multiply(bint);
    System.out.println("result is - " + res);
    

    Output

    result is - 2520
    
  2. BigInteger class is immutable– BigInteger objects are immutable, so any operation won't result in the original object being modified.
  3. Don’t use any decimal number– While initializing a BigInteger and using String argument you can provide a number with decimal but at runtime it will throw NumberFormatException so make sure you don’t use any number with decimal points. After all it is an integer even if it is a BigInteger.
    BigInteger bint2 = new BigInteger("12.00");
    

    Any such initialization will throw exception-

    Exception in thread "main" java.lang.NumberFormatException: For input string: "12.00"

  4. For comparing you can use equals or compareTo method– Though in BigDecimal class equals() method should not be used for comparing as it will take numbers with different scale as unequal. So in BigDecimal 2.0 and 2.00 will be termed as unequal if equals() method is used.

    With BigInteger there is no problem of scale so equals or compareTo both can be used. As you would have seen in the general form of the BigInteger class it implements Comparable interface and provides its own implementation of compareTo() method.

    bint1.compareTo(bint2)
    
    returns
    • -1 if bint1 is less than bint2.
    • 0 if both bint1 and bint2 are equal
    • 1 if bint1 is greater than bint2

    As example–

    BigInteger bint1 = new BigInteger("21");
    BigInteger bint2 = new BigInteger("12");
    System.out.println("bint1 compareTo bint2 " + bint1.compareTo(bint2));
    

    Output

    bint1 compareTo bint2 1
    

That's all for this topic BigInteger in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. BigDecimal in Java With Examples
  2. Array in Java With Examples
  3. TypeWrapper Classes in Java
  4. Access Modifiers in Java - Public, Private, Protected and Default
  5. Convert int to String in Java

You may also like-

  1. Multi-Catch Statement in Java Exception Handling
  2. static Import in Java With Examples
  3. Constructor Chaining in Java
  4. equals() And hashCode() Methods in Java
  5. Fail-Fast Vs Fail-Safe Iterator in Java
  6. Callable and Future in Java With Examples
  7. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  8. Volatile Keyword in Java With Examples

No comments:

Post a Comment