Search code examples
javalong-integerprimitive-types

Not able to handle number whose length is more than 10


I know that max value for int and long are very high but somehow I am not able to handle them in my code. I am getting compilation error in all the scenarios below. Could someone please suggest how I can handle 20118998631 value.

I know that if I put l after this value 20118998631l then declaring it as long will work but problem is that I am getting this from a network call and if I declare my field as long and value will come simply as 20118998631 then it will break.

    int x = 20118998631; // compilation error
    long l = 20118998631; // compilation error
    double d = 20118998631; // compilation error
    Long l1 = new Long(20118998631); // compilation error

Solution

  • I know that max value for int and long are very high

    The definition of 'very' is in the eye of the beholder, isn't it?

    The max value of an int is Integer.MAX_VALUE, which is 2147483647. Specifically, that's 2, to the 31st power, minus 1. Because computers use bits, int uses 32 bits, and about half of all the numbers an int can represent are used to represent negative numbers, hence why you end up with 2^31-1 as max int.

    For longs, its 2^63-1 for the same reason: long uses 64 bit, and half of all representable values are negative.

    If you have numbers that are larger than this, you need to use BigInteger (a class in the standard library for integers of arbitrary size) or byte[] or something else.

    but problem is that I am getting this from a network call and if I declare my field as long and value will come simply as 20118998631 then it will break.

    This doesn't make sense. Are you getting stuff from the network, shoving what you get into a file with a prefix and suffix, and then that file is something you compile with javac? That sounds bonkers, but if you are, just.. add that L. Or, add " before and after the number and pass that to new BigInteger instead, now the number can be thousands of digits large if you want it to be.

    Otherwise, you're getting a bytes which either represent the number directly (and the L aspect is not relevant to this conversation), or you're getting a string in, which again, isn't relevant to this conversation: That L is just for writing literal numbers inside .java files, it doesn't come up anywhere else. Turning a string containing digits, such as "20118998631" into e.g. a long is done with Long.parseLong("20118998631") which works fine, and does not require the L (in fact, it won't work if you include it).