• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Narrowing Primitive Conversions

 
Talal Shaikh
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Talal,
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?
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic