BigInteger(int,base)

This format of changing base is giving Number Format Exception. Cannot find anything about this type of constructor on the internet.

There is no built-in BigInteger in C++.

If you meant that. If not please add more details to your question.

I have imported java.math.BigInteger
When I tried to run:
import java.io.*; import java.math.BigInteger; public class Try { public static void main(String args[]) { String s="12345"; BigInteger b=new BigInteger(s,2); System.out.println(b); } }

It is giving me runtime exception:

Exception in thread "main" java.lang.NumberFormatException: For input string: "12345"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.math.BigInteger.<init>(BigInteger.java:537)
    at Try.main(Try.java:8)



The reason you are getting an error is because you have created a base 2 BigInteger but the string that you are giving to it contains 2345 which are invalid characters for a base 2 number as they can only have 0s and 1s.
If you are trying to create a base-10 (decimel) BigInteger then you must do the following.

import java.io.*;
import java.math.BigInteger;
public class Try {
    public static void main(String args[]) {
        String s = "12345";
        BigInteger b = new BigInteger(s, 10);
        System.out.println(b);
    }
}

Or you can simply let the class use default base parameter which is base 10.

import java.io.*;
import java.math.BigInteger;
public class Try {
    public static void main(String args[]) {
        String s = "12345";
        BigInteger b = new BigInteger(s);
        System.out.println(b);
    }
}
1 Like

Ohkay. I was under the wrong impression that this constructor could convert bases of numbers and numbers itself into those bases.
Thanks a lot.

If I have resolved your issue please mark the doubt as resolved and rate it. Thank You.