My JDK version is 1.4.2_04 I saw a book said : byte b = 27; the compiler would put it in the cast automatically into byte b = (byte) 27; but if I tried byte b = 128; the compiler complianed : possible loss of precision but if I tried byte b = (byte) 128; is ok.
my question is if the compiler would cast automatically, why I got error when I tried byte b = 128; thanks a lot.
Hi. 128 is just a bit too big for byte, so you will lose precision (and the data) by doing what you set out to do. Now, The compiler will not complain if you're explicitly asking it to cast, because then all the responsibility is on you. Nimo.
Joined: Aug 04, 2002
Yes, I understand what you said. But my question is why the compiler did the cast when byte b = 7; is that because 7 is smaller than 127?
Joined: Mar 23, 2004
Hi. AFAIK - yes. 7 is safe, the compiler knows that beforehand, do there's no problem with that. It would have been different if you were to assign an int variable and not a literal. Nimo.