Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the maxValue + 1 of an int is the same as maxValue, but not for shorts and bytes?

I was experiencing Java primitive types ranges, and I came up with a small confusion, here is some line of code that illustrates clearly what is it about:

System.out.println((byte) (Math.pow(2, 7))+1); //the maximum value + 1 overflows to the minimum value
System.out.println((short) (Math.pow(2, 15)-1)); //same for shorts
System.out.println((int) Math.pow(2, 31)); 
System.out.println((int) (Math.pow(2, 31)+1)); //returns the maximum value of the int range
System.out.println((int) (Math.pow(2, 31)+100)); //returns the maximum value of the int range
like image 447
Curcuma_ Avatar asked Jan 09 '23 20:01

Curcuma_


1 Answers

Math.pow(2, 7)

is 128.0, which is more than can fit in a byte. When you cast, it becomes -128. Add 1 and it becomes -127.

The same behavior applies to your short example.

As for the int example, you should apply the (int) cast before you do your addition +. In your current case, the + happens with a double and an int. Numeric promotion happens on the int to convert it to a double. Then it's just a matter of precision.

System.out.println(Math.pow(2,31) + 1);

prints

2.147483649E9
like image 61
Sotirios Delimanolis Avatar answered Jan 12 '23 08:01

Sotirios Delimanolis