Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to increment byte value with expression but with increment operator [duplicate]

Tags:

java

byte

why the following is valid

byte i=0;
i++;

where as the following is invalid

byte i=0;
i=i+1;

what would be the reason?

I know in the case of i+1 the entire value is explicitly incremented by 1 (which will be int value) so compilation problem will occur, but in case of i++ it does the same but did not get any error.

like image 712
MaheshVarma Avatar asked Dec 18 '13 06:12

MaheshVarma


1 Answers

Whenever you perform a binary operation between two operands of different types, one of the operands is promoted to the higher type. And then the result of the operation is of that type.

So, in your case, the byte type a is first promoted to an int, since 1 is an int type. And then after the addition operation, the result is of type int. Now, since you cannot assign an int to a byte, you need to do a typecast to remove the compiler error:

byte a = 2;
a = a + 1;   // Error: Cannot assign an int value to byte
a = (byte)(a + 1);  // OK

Now, in case of Compound Assignment Operator, the typecasting is done implicitly for you. The expression:

a += 1

is internally converted to:

a = (byte)(a + 1);

This is specified in JLS - §15.26.2 Compound Assignment Operator:

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.

Similar is the case with prefix increment operators, and postfix increment operators.

According to JLS - §15.15 Unary Operators:

The type of the prefix increment expression is the type of the variable.

like image 66
rachana Avatar answered Sep 18 '22 13:09

rachana