Home > Blockchain >  Long overflow Even Though It doesn't pass the limit
Long overflow Even Though It doesn't pass the limit

Time:07-09

I have this code where I set the byte, short, and int to their max values, and then multiplied their sum by 10 and added 50000. I calculated on my calculator that this should be allowed, because the result is less than the maximum of longs, but its giving me a weird output.


public class Main {
    public static void main(String[] args) {
        byte byteValue = 127;
        short shortValue = 32767;
        int intValue = 2147483647;

        long longTotal = (50000L   10L * (byteValue   shortValue   intValue));
        System.out.println(longTotal);
    }
}

Output : -21474457550 Expected output : 2.14 * 10^10

CodePudding user response:

You are adding (byte) 127 (short) 32767 (int) 2147483647 first. The result is implicitly interpreted as an int by Java. So naturally this does not fit. Then afterwards you do the Long multiplication and addition but by that time the result has already overflowed the int boundary so has become some negative value.

You could do this:

long longTotal = 0;
longTotal  = byteValue;
longTotal  = shortValue;
longTotal  = intValue;
longTotal *= 10;
longTotal  = 50000;

@maloomeister suggests this more concise approach:

long longTotal = (50000   10 * ((long) byteValue   shortValue   intValue));

So here one (doesn't matter which) of the arguments of the addition is explicitly cast to long. This triggers Java to interpret the result as a long rather than an int.

  •  Tags:  
  • java
  • Related