I'm teaching a class on type conversions in Java, and I've run into something that I don't know myself. Here is a simple bit of code to show how type conversions are sometimes unreliable.
long l = 1000;
byte b = (byte) l;
System.out.println(b); // -24 (Unsure how Java arrives at this value)
System.out.println(l); // 1000
The variable "long l" is set to 1000. It is then converted to "byte b". "byte" can only hold values from -128 to 127. When I print variable "b", it prints a gibberish number of "-24".
How does Java arrive at "-24" when converting "1000" to fit into a "byte"? Is this value predictable?
2007-07-05
04:10:20
·
4 answers
·
asked by
Anonymous
in
Computers & Internet
➔ Programming & Design