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.
Implicit typecasting only works when the value of your
RHSis known atcompile-time, means they arecompile-time constants. In other cases, you need to do explicit typecasting.So: –
Also, note that, if you declare your variable
aasfinal byte a = 1, then the 2nd assignment will compile, as in that case, yourawill be a compile time constant.