Until today, I thought that for example:
i += j;
Was just a shortcut for:
i = i + j;
But if we try this:
int i = 5; long j = 8;
Then i = i + j;
will not compile but i += j;
will compile fine.
Does it mean that in fact i += j;
is a shortcut for something like this i = (type of i) (i + j)
?
The *= operator is a combined operator that consists of the * (multiply) and = (assignment) operators. This first multiplies and then assigns the result to the left operand. This operator is also known as shorthand operator and makes code more concise.
In Java, the *= is called a multiplication compound assignment operator.
Which of the following is not an assignment operator? Explanation: Assignment operators are used to assign some value to a data object. <= operator is used to assign values to a SIGNAL. := operator is used to assign values to VARIABLE, CONSTANTS and GENERICS; this operator is also used for assigning initial values.
The -= operator first subtracts the value of the expression (on the right-hand side of the operator) from the value of the variable or property (on the left-hand side of the operator). The operator then assigns the result of that operation to the variable or property.
As always with these questions, the JLS holds the answer. In this case §15.26.2 Compound Assignment Operators. An extract:
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T)((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.
An example cited from §15.26.2
[...] 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);
In other words, your assumption is correct.
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