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 Narrowing Primitive Conversions 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 "Narrowing Primitive Conversions" Watch "Narrowing Primitive Conversions" New topic

Narrowing Primitive Conversions

Talal Shaikh

Joined: Jul 17, 2001
Posts: 13
int i = -20;
final int j = 20;
final int k = i;
byte b1 = j; // J in rannge . no cast required
byte b2 = (byte) i;// cast req
byte b3 = (byte) k;// cast req
My question is why is the cast required for b2 eventhough -20 is in the range of byte ?
guo mark
Ranch Hand

Joined: Oct 20, 2001
Posts: 43
Hey ,Talal. In java when you cast a variable or a object to its norrow type,you must specify the type you want to cast no matter the variable is in the range of the norrow type or not.

meet once ,love every while
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
You are able to convert j from an int to a byte for two reason. First, it is within the range of a byte. Second, it is a compile-time constant.
Just as j is in range for a byte, i is also in range for a byte. However, i is not a compile-time constant.
Add the "final" modifier to i and remove the explicit casts as shown below. You will find that the code compiles and runs without error.

Have you tried my mock exam at the URL contained in my signature?

Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="" target="_blank" rel="nofollow">Try my mock exam.</a>
I agree. Here's the link:
subject: Narrowing Primitive Conversions
It's not a secret anymore!