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,297
  • 1
  • 9
  • 26

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
  • 69,673
  • 13
  • 131
  • 165