File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "cast" Watch "cast" New topic


Cindy Yang

Joined: Aug 24, 2001
Posts: 7
Hi there,
Could some one explain why the following codes work?
byte b1=(int) 16.2; //1 compile fine
byte b2=(int)10; //2 compile fine
int i=10;
byte b3=(int)i; //3 compiler error
Why code1&2 are fine?
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
It's not a secret anymore!