Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

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)?

like image 670
Honza Brabec Avatar asked Jan 03 '12 10:01

Honza Brabec


People also ask

What is the *= operator in Java?

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.

Is there such thing as *= in Java?

In Java, the *= is called a multiplication compound assignment operator.

Which Cannot be used as 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.

What does -= do in Java?

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.


1 Answers

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 to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 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.

like image 162
Lukas Eder Avatar answered Oct 20 '22 01:10

Lukas Eder