This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
Hi there, Could some one explain why the following codes work? 1. byte b1=(int) 16.2; //1 compile fine System.out.println(b1); 2. byte b2=(int)10; //2 compile fine System.out.println(b2); 3. int i=10; byte b3=(int)i; //3 compiler error System.out.println(b3); Why code1&2 are fine? Thanks.
Hi Cindy, In the first two examples you are using literal values. The compiler can tell that "3" and "10" will fit within the range of a "byte" data type. As the values are litrals, the compiler knows they will never change and it can write out bytecode that uses exactly those values. In the third example, the compiler only knows that you are using an "int" value. Even though, in the example, the assigned value of "i" (10) will fit into a byte; this isnt't true for all "int" values. As far as the compiler is concerned, the value of the variable "i" may be changed to a value that is greater than 127 (the maximum value that can be stored in a "byte") so it rejects the cast. It has to write out bytecode that uses the "i" variable. We can look at the code and see that "i" will not change but the compiler doesn't check the entire program; it would be too complex an operation. Hope that helps. ------------------ Jane Griscti Sun Certified Programmer for the Java� 2 Platform [This message has been edited by Jane Griscti (edited September 13, 2001).]