Java overflow have different result when calculating on a calculator to the IDE result?

Ehsan Waheed :

I don't understand where I am going wrong with the calculation I did, why did I receive a different result to the IDE console. Console receives a result of 14464 for the println for my ShortTotal. But via manual calculation on a calculator I received a similar number but +1 which was 14465?

I understand what the short type maximum and minimum values are. Here is what I have done so far:

As the short maximum value is around 32,767. So it goes to the minimum again with the remaining amount. So on a calculator, you can check this by doing: 1000 x (bytevalue+shortvalue + intvalue) = 80000. As 80,000 is bigger than short max val it overflows with the remainder. 80,000-32767 =47233 then add this value back onto minimum which is : - 32768 + 47233 = 14465

I managed to get close to the value of 14464 but don't know why I'm receiving 14465?

package com.company;

public class Main {

    public static void main(String[] args) {
   byte ByteValue = 10;
   short ShortValue = 20;
   int IntValue = 50;
   long LongTotal = 50000 + 10 * (ByteValue + ShortValue + IntValue);
        System.out.println(LongTotal);
//The issue in question is below.
        short ShortTotal = (short) (1000 * (ByteValue + ShortValue + IntValue));
      System.out.println(ShortTotal);
    }
}
Robby Cornelissen :

I don't understand your confusion.

80,000 as an int value gives the following bit pattern:

00000000000000010011100010000000

Chopping off the first two bytes gives you the following bit pattern for the short value:

0011100010000000

Converted to decimal, this is:

14464

Or to put it differently: a short can represent 2^16 possible values:

80000 - (2^16) = 80000 - 65536 = 14464

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327884&siteId=1