问题
My question is how compile time constant works internally so we didn't get an error in Below statement.
final int a = 10;
byte b = a;
And why am I getting error in this statement.
int a = 10;
byte b = a;
回答1:
This is because not all ints will fit into a byte.
In your first example, the value of a
is known and cannot change. The compiler knows that it will fit into a byte.
In your second example, because a
is not final, it's possible that it could have been changed (though not in your example). The Java compiler isn't smart enough to notice that nothing has changed it, so it's no longer certain that it will fit into a byte.
As an example, take a look at this:
final int a = 10000;
byte b = a;
Because the value of a
is now too big to fit into an int, it no longer compiles.
回答2:
In below case when your int
value is not final
,you have to cast int
to byte
while assigning an integer value to byte
in java.
int a=11;
byte b= (byte) a;
来源:https://stackoverflow.com/questions/60445385/how-compile-time-constant-will-work-internally-in-java