I am new to java, and I don't understand the differences between these two:
Lets init some variables for the overflow:
byte myByte = 100;
short myShort = 5000 ;
int myInt = 2_000_150_000;
I know whenever I got variable and arithmetic I need to do a casting with (long)
long myLong = (long)(50_000 + 10 * (long)(myByte + myShort + myInt));
long myLong2 =(long)(50_000 + 10 * (myByte + myShort + myInt));
sysout(myLong);
sysout(myLong2);
OUTPUT:
20001601000
-1473235480
but why do I need to do it outside two times?
for short type, this works differently:
short myShortTest = (short)(50_000 + 10*(short)(myByte + myInt +myShort));
short myShortTest2 = (short)(50_000 + 10*(myByte + myInt +myShort));
sysout(myShortTest);
sysout(myShortTest2);
OUTPUT
13800
13800
Whenever an overflow happens, an int
will move to the other end of the boundary as seen in the output of the following program:
public class Main {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MAX_VALUE + 1);
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MIN_VALUE - 1);
}
}
Output:
2147483647
-2147483648
-2147483648
2147483647
test1
, because of casting to long
, the result of the intermediate calculation [10*(long)(myByte + myShort + myInt)
] was stored as long
which can accommodate the result without an overflow and hence you got the correct value.test2
, in lack of proper cast, the result of the intermediate calculation [10*(myByte + myShort + myInt)
] was stored as int
but the value overflew for int
and hence you got the negative value.