int x = Integer.MAX_VALUE; long y = Long.MAX_VALUE; System.out.println(x); System.out.println(y); System.out.println(x*2); // result -2 System.out.println(y*2); // result -2 Why I'm getting -2 as result when multiplying maximum value by 2, also I'm not evening storing the value just printing.
Playing with MAX Value
You must be signed in to leave a comment
19 February, 17:18
19 February, 13:34
int: MAX_VALUE in binary is 01111111 11111111 11111111 11111111 the first bit indicates if the number is positive (0) or negative (1). More you can't save in an int. If you double it, then the mathematical operation is shifting all bits to the left, so you get 11111111 11111111 11111111 11111110 (if you'd again multiply by 2 you'd get 11111111 11111111 11111111 11111100 -> -4) Now the first bit is set, and you have a negative value... quick hack how to see what value that is: just invert the bits and add 1 to the value (and finally don't forget the negative sign) the neg value inverted: 00000000 0000000 0000000 00000001 that's one plus the mentioned 1 = 2, make it negative -> -2