Question :
char x = 'a';
x += 3; // ok
x = x + 3; // compile time error
x++ is postfix increment and y is postfix decrement, postfix means the values of x and y will be used first in the expression after that increment/decrement operation will be applied. eg : int x=5,y=4; int z=x++*y--; //value of z will be 20 (5*4) //value of x will be 6 and value of y will be 3.
It's the Addition assignment operator. Let's understand the += operator in Java and learn to use it for our day to day programming. x += y in Java is the same as x = x + y. It is a compound assignment operator. Most commonly used for incrementing the value of a variable since x++ only increments the value by one.
The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable.
You probably learned that x++ is the same as x = x+1 .
Because x += 3
is equivalent to x = (char)(x+3)
, while x + 3
is default to int
operation, assign an int to char must cast.
From the JLS specification : 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. Note that the implied cast to type T may be either an identity conversion (?.1.1) or a narrowing primitive conversion (?.1.3).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With