Java – you cannot use expressions to increment byte values, but use the increment operator

See English answers > why byte + = 1 compile, but byte = byte + 1 not? 8

byte i=0;
i++;

The following is invalid

byte i=0;
i=i+1;

Why?

I know that in the case of I 1, the whole value is explicitly incremented by 1 (this will be the int value), so there will be a compilation problem, but in the case of I, it will do the same without any errors

Solution

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

Therefore, in your case, byte type A is first promoted to int because 1 is of type int Then, after the addition operation, the result is of type int Now, since you cannot assign int to a byte, you need to type cast to remove compiler errors:

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

Now, in the case of compound assignment operators, the type conversion is done implicitly for you Expression:

a += 1

Internal conversion to:

a = (byte)(a + 1);

This is in JLS - § 15.26 2. Compound assignment operator:

The composite 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

The prefix increment operator is similar to the suffix increment operator

According to JLS – § 15.15 unary operators:

The type of prefix increment expression is the type of variable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>