wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes cast Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "cast" Watch "cast" New topic
Author

cast

Cindy Yang
Greenhorn

Joined: Aug 24, 2001
Posts: 7
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.
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
Initialization and declaration can happen in a single line
Destination = Source
The source value must be in the range of the destination
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
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).]


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
 
 
subject: cast
 
Similar Threads
byte 0x7f, 0x80, 0x81
int to byte conversion/casting
Exception and Error Q
doubt in java conversion
Operator precedence