Search code examples
javaprimitivescjp

Assigning result of an expression to a primitive


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.


Solution

  • 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.