Search code examples
javastringlong-integertypeconverter

Convert a long String only containing numbers into long


I'm trying to convert a String(32 digits) into a long and it returns a NumberFormatException. I've tried it with Long.parseLong() and a Long object, but bone of them worked. code:

class ConvertStringToLong{
    public static void main(String in){
        long out;
        out=java.lang.Long.parseLong(in);
        System.out.println(out);
    }
}

i also tried

class ConvertStringToLong{
    public static void main(String in){
        long out;
        out = new Long(in);
        System.out.println(out);
    }
}

Solution

  • The long datatype is a 64-bit signed integer, so its maximum value is 2^63 - 1, which is 19 digits long. To represent larger numbers than this, you will need to use a different datatype, such as BigInteger, which allows arbitrarily large numbers. The constructor new BigInteger(String val) will parse a string as a BigInteger.