How byte b= (byte)400
is a valid statement although 400
is out of range? I want to know the algorithm java uses to bring 400
within byte's range.
Asked
Active
Viewed 160 times
0

Nicolas Filotto
- 43,537
- 11
- 94
- 122

Paras Gupta
- 63
- 1
- 7
-
1You can find all details in the Oracle tutorial: [Conversions and Promotions#Narrowing](http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3) (30 seconds google search though) – BackSlash Jan 23 '17 at 09:25
1 Answers
4
It takes the least significant 8 bytes of the binary representation of 400 and assigns them to the byte
variable.
The binary representation of the int
400 is :
00000000000000000000000110010000
--------
When taking the low 8 bits, you get 10010000
, which is the binary representation of -112.

Eran
- 387,369
- 54
- 702
- 768