Does Java compiler recognize byte and short as literals?

What I actually meant to ask is, if I write :

byte b=13;
short s=14;

Then values on the right-hand side ie, 13 and 14 respectively are treated as byte and short Or is just read as an int type by the compiler. If they are read as bytes and shorts respectively then why,

byte b1=13;
byte b2=23;
byte b3=b1+b2;

And

short s1=14;
short s2=24;
short s3=s1+s2;

are invalid statements(short s3=s1+s2; and byte b3=b1+b2;) in java even if the the precision is not compromised in bothe the cases.

And if they are just read as int types by the compilers, then how their identity is maintained by the compiler for being byte or short types?


Java doesn't have byte or short literals. What it does have is an implicit assignment conversion from int to byte, char and short when the int is a compile time constant and in range for the target type.

So, this is OK:

byte b = 13+14; // implicit conversion

But this is not:

void method(byte b) {}

method(13);

Nor this:

byte b = 13+nonConstant;

你需要投出+这是一个int的结果。

byte b1 = 13;
byte b2 = 23;
byte b3 = (byte) (b1 + b2);

short s1 = 14;
short s2 = 24;
short s3 = (short) (s1 + s2);

This is because integer literals (and more generally constant expressions of type int) are handled specially by the compiler. When you assign an integer literal to a byte or short, the compiler checks if it is in the range of the target type and then allows the assignment without a cast.

链接地址: http://www.djcxy.com/p/73634.html

上一篇: 变化的行为可能导致精度损失

下一篇: Java编译器是否将字节和短文字识别为文字?