Java – How to convert int to BigInteger?

In Java, we can use BigInteger.valueOf(int) to convert int to a BigInteger

JavaExample.java

package com.mkyong;

import java.math.BigInteger;

public class JavaExample {

    public static void main(String[] args) {

        int n = 100;
        System.out.println(n);

        // convert int to Integer
        Integer integer = Integer.valueOf(n);
        System.out.println(integer);

        // convert int to BigInteger
        BigInteger bigInteger = BigInteger.valueOf(n);
        System.out.println(bigInteger);

        // convert Integer to BigInteger
        //BigInteger bigInteger2 = BigInteger.valueOf(integer); // works
        BigInteger bigInteger2 = BigInteger.valueOf(integer.intValue());
        System.out.println(bigInteger2);

    }

}

Output


100
100
100
100

References

  1. BigInteger JavaDoc

2 comments on “Java – How to convert int to BigInteger?

  1. int n = 100;
    BigInteger bigInteger = BigInteger.valueOf(n);

    when we write like this it is throwing error.
    BigInteger.valueOf() only accepting long value not int value.
    So we have to store value like:

    long n = 100;
    BigInteger bigInteger = BigInteger.valueOf(n);

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *