Why does maxValue + 1 from int match maxValue, but not for shorts and bytes?

I was testing ranges of Java primitive types, and I came up with a little confusion, here are a few lines of code that clearly show what it is:

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
+4
source share
3 answers

Math.pow returns a double, so you add +1 to the double value and then add it to int, short or byte. But this part is already covered in other answers.

There is another interesting thing in your example. Differences between casting with double and decimal types.

You have differences in bracketing. And -sing instead +on the line short.

Fixed them for you (always discard at the end):

    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

:

-127
-32767
2147483647
2147483647
2147483647

, int overflows. .

http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html - :

The results for char, int, and long are unsurprising, producing the minimum and maximum representable values of the type.

The results for byte and short lose information about the sign and magnitude of the numeric values and also lose precision. The results can be understood by examining the low order bits of the minimum and maximum int. The minimum int is, in hexadecimal, 0x80000000, and the maximum int is 0x7fffffff. This explains the short results, which are the low 16 bits of these values, namely, 0x0000 and 0xffff; it explains the char results, which also are the low 16 bits of these values, namely, '\u0000' and '\uffff'; and it explains the byte results, which are the low 8 bits of these values, namely, 0x00 and 0xff.

: +1 . (byte) (0b10000000) -128, .

+1
Math.pow(2, 7)

128.0, , byte. , -128. 1, -127.

short.

int, (int), +. + double int. int, double. .

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

2.147483649E9
+6

. MAX_VALUE + 1 MIN_VALUE,

int i = Integer.MAX_VALUE;
if (i + 1 == Integer.MIN_VALUE) {
    System.out.println("MAX_VALUE + 1 == MIN_VALUE");
}

MAX_VALUE + 1 == MIN_VALUE

, , double int.

System.out.println((int) (1 + (double) Integer.MAX_VALUE));

MAX_VALUE, .

+2

All Articles