1

Doing this is legal in Java

byte = 27     // 27 treated as int; implicit cast to byte

But when assigning a value as a result of expression, Java requires explicit casting

int a = 9;
byte b = 8;
byte c = a + b;  // Compile error

What is the reason behind this?

Vivin
  • 1,327
  • 2
  • 9
  • 28

1 Answers1

2

27 is a literal. The compiler knows that it is representable in a byte (from -128 to 127).

a + b is an expression involving variables. Its result may not be representable in a byte

M A
  • 71,713
  • 13
  • 134
  • 174