Assigning result of an expression to a primitive

混江龙づ霸主 提交于 2019-12-21 21:27:26

问题


K.Sierra in her book "SCJP Study Guide" mentions "We know that a literal integer is always an int, but more importantly, the result of an expression involving anything int-sized or smaller is always an int."

I've started experimenting and I'm a little bit confused with the below results:

byte a = 1; // correct
byte b = 1 + a; // incorrect (needs explicit casting)
byte c = 1 + 1; // correct (I expected it to be incorrect)

Could anyone explain to me why the last example does not require casting? Why does the Java compiler put the implicit cast? Is it because there are 2 int literals? Clarification greatly appreciated.


回答1:


Implicit typecasting only works when the value of your RHS is known at compile-time, means they are compile-time constants. In other cases, you need to do explicit typecasting.

So: -

byte c = 1 + 1; // Value of `1 + 1` is known at compile time. Implicit cast
byte c = 1 + a; // Value of `1 + a` is evaluated at runtime. Explicit cast needed

Also, note that, if you declare your variable a as final byte a = 1, then the 2nd assignment will compile, as in that case, your a will be a compile time constant.




回答2:


Yes, it is because they are literals, meaning they are compile-time constants and the compiler ensures that the size of the result is indeed a byte. The same will fail if you exceed the byte range. Try assigning 128 to c or, for that matter, 1 << 7 or any other compile-time constant greater than 127.




回答3:


As said "The result of an expression involving anything int-sized or smaller is always an int"

So byte b = 1 + a; returns an int value which is not evaluated at complie time. Hence Compiler cannot check it if the result falls within the byte range and expects us to put an explicit cast.



来源:https://stackoverflow.com/questions/13010878/assigning-result-of-an-expression-to-a-primitive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!