0

Why b=b+8 throws an error where b+=8 dosent.

public static void main(String []args){
    byte b = 6;
    b=b+8;
    //b+=8;
    System.out.println(b);
    b+=7;
    System.out.println(b);
}
Anisur Rahman
  • 644
  • 1
  • 4
  • 17

1 Answers1

0

This is because b=b+8 is not exactly equivalent to b+=8.

According to the language specification, section 15.26.2:

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.

It also gives you an example:

For example, the following code is correct:

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 += not only assigns the sum to the variable, but it also casts the sum to the type of the left hand side variable. b=b+8 does not do this.

Why does b=b+8 produce the warning then?

This is because the + operator, when used on byte types, also performs numeric promotion. The type of the expression b+8 is actually int. Therefore the compiler tells you that you are converting an int to a byte.

Sweeper
  • 213,210
  • 22
  • 193
  • 313