+ 1
Why output are i=11 and j=44
public class Testing2 { public static void main(String[] args) { double x = 267.5; int y = 300; byte i = (byte)x; byte j = (byte)y; System .out .println ("i = "+i+"\nj = "+j); } }
1 Answer
+ 4
Firstly, there are two narrowing conversions from 32-bit integer and 64-bit double-precision FP to an 8-bit byte are taking place. In the case of Double to byte, what's happing is double type loses its precision and becomes an integer type, namely 267. Then, since a byte only capable of holding 8-bits, stuffing a bigger number into it causes an overflow, meaning it's undefined behavior in languages such as C/C++. However, in Java, it simply calculates the fittest number out of 267 to make it small enough for storing into the 8-bit container, either by successive subtractions from 128 Âč as
267 - 128 = 139
139 - 128 = 11
Or by taking modulo 128 as
267 % 128 = 11
Now, our byte can safely hold 11 without a problem. The same scenario is happening for 300.
__________
Âč The range of a byte type is from -128 to 127. That is, 1-bit for the sign and 7-bit for magnitude, so just to represent the non-negative integers, there are 128 vacancies are available (from 0 to 127).



