When you attempt to compile the above code you'll get one error: ByteExample.java:10: Incompatible type for declaration. Explicit cast needed to convert int to byte. byte abb=2000;
from A Programmer's Guide to Java Certification by Mughal and Rasmussen: ...implicit narrowing primitive conversions on assignment can occur in cases where the souce is an int constant expression whose value can be determined to be in the range of the destination type at compile time; the destination type is either byte, short, or char type. ...all other narrowing primitive conversions will produce a compile error on assignment and will explicity require a cast.
With those rules in mind -- lets look at your statement again: byte abb = 2000; * The RHS (right hand side) is a constant int expression * The LHS (left hand side) is a byte * The RHS is not within range of the LHS. (a byte's range is -128 to 127)] So.... that means you need to do an explicit cast: byte abb = (byte)2000; ... of course, when you do that because 2000 is out of the range of a byte the number will spill over to the negative side and you end up with -48!! [ November 22, 2002: Message edited by: Jessica Sant ]
when you explicitly cast an int or long to a byte or short or char, all what happens is that the number gets trimmed, for instance 0x7FFFA7CB changed to short will be 0xA7CB to byte will be 0xCB so the output is not mathematically calcualted, represent 2000 in HD and trim it and you will get the -48
Sudha, Very simplistically... A byte can have values between -128 and 127. To make a byte of a specific number, Java starts at -128 and works its way up to 127. Because 2000 is bigger than 256 (value between -128 and 127), when it gets up to 127 Java finds it hasn't fitted all of 2000 in the byte, so it goes back to -128 then back up to 127 and so on until it has added all of 2000. The byte value at this point happens to be -48. (Even simpler, keep subtracting 256 from 2000 and the first value you get between -128 and 127 is -48) Linda
Why am I so drawn to cherry pie? I can't seem to stop. Save me tiny ad!