0

i know that by default numbers are stored as integer in java but

byte x = 10;
x = x + 10;

is giving error while

byte x = 10;
x += 10;

is compiling fine

  • When you do += that's a compound statement and Compiler internally casts it. Where as in first case the compiler straight way shouted at you since it is a direct statement :) – Suresh Atta Aug 15 '17 at 08:44

1 Answers1

2

JLS have an answer for you

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

So in your case your second statement equlas to

x = (byte) x + 10;

That is the reason compiler is happy about.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307