Duggs
Duggs

Reputation: 179

In java why prefix increment or decrement operator does not require cast in case of byte

In java Suppose i have following code snippet

byte b = 127;
b=-b ;//(which require a cast due to numeric promotion)
b=++b; //does not require cast

Upvotes: 0

Views: 252

Answers (1)

Stephen C
Stephen C

Reputation: 718788

The JLS specification of ++ says:

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

.... Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable after the new value is stored.

(The term "narrowing primitive conversion" refers to a type cast ...)

Reference: JLS 15.15.1.

Therefore ++b is a byte and no explicit cast is required.

Upvotes: 1

Related Questions