Fxdqe
Fxdqe

Reputation: 33

java type conversion issue

Why does Eclipse point out the code below an error on the last "X"

int a = 1;
final int X = a;
byte b = X;

Type mismatch: cannot convert from int to byte

while the code below does not?

final int Y =10;
byte b2 = Y;

Upvotes: 3

Views: 63

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726679

This behavior boils down to the distinction between a final variable and a constant variable.

According to Java Language Specification 4.12.4

We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression a constant variable.

In your first example X is initialized from another variable, so it is simply a final variable. In your second example Y is initialized from a constant expression, so it is a constant variable.

Java can use its knowledge of Y value in the second code example to decide that there is no narrowing conversion to byte. It is allowed to treat byte b2 = Y as byte b2 = 10.

In the first example, though, X is not a constant expression, so the compiler must treat it as an expression that could be potentially outside the range of byte, so an error is triggered.

Upvotes: 2

Ousmane D.
Ousmane D.

Reputation: 56443

When you do:

final int Y =10;
byte b2 = Y;

The compiler knows that the value of Y is a valid byte range value and it can never change due to the final modifier.

Whereas the first example:

int a = 1;
final int X = a;
byte b = X;

a could be any value and by the time we mark it with the final modifier, we don't know if it's a valid byte range value hence doing:

byte b = X;

will result in a compilation error.

if you were to do:

final int a = 1;
final int X = a;
byte b = X;

then it would also work just like the second example you've provided.

Upvotes: 3

Related Questions