Assigning result of an expression to a primitive

泄露秘密 提交于 2019-12-04 15:20:22

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.

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.

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.

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