How to print long primitive in Java

11,374

In line 2 of your code, all your operands are integers, which is why the results of the operations will also be an integer.

Since the result(3,232,235,521) will not fit inside an integer(max value being 2^31 - 1), this results in an integer overflow, which is why you are getting the negative result.

So, you will need to use Long literals to get an accurate result. Change Line 2 to the below code.

long b = 192L * 16777216L + 168L * 65536L + 0L * 256L + 1L;

The above code should give you the correct output.

Share:
11,374
momi
Author by

momi

Updated on June 04, 2022

Comments

  • momi
    momi over 1 year

    Relatively new to Java and possibly some stupid question. Here is the code:

    long a = 3232235521L;
    long b = 192 * 16777216 + 168 * 65536 + 0 * 256 + 1;
    
    System.out.println("a="+a);
    System.out.println("b="+b);
    

    The output:

    a=3232235521
    b=-1062731775
    

    According to Java documentation max value for long 2^63-1 and that is: 9223372036854775807. So for b, there is no overflow, so why b isn't 3232235521?