March 3, 2009

type promotion exception

the following code causes a compilation error.

int i = 120;
byte b = i;

how would you change the first line to fix the code (without changing the type of i)?

the problem is (as you probably guessed) that we want assign an int expression to a byte variable. the compiler cannot permit this since the range of int is wider than the range of byte.

if you read the specification carefully you’ll come accross this exception of the above rule: an int expression can be assigned to a byte variable given that the expression can be evaluated at compile time. and how can a variable made to a compile time constant? by using the final keyword.

that is, the final keyword should be appended to the begining of the first line:

final int i = 120;

thus the problem is fixed.

java  promotion 
Comments (View)
Bookmark and Share
blog comments powered by Disqus