Home java The + = Operator in Java

The + = Operator in Java

Author

Date

Category

Until now, I thought that writing

i + = j;

is the same as

i = i + j;

However, if you take

int i = 5;
long j = 8;

That expression i = i + j will not compile, while i + = j will compile without problem.

Does i + = j mean something like i = (type of i) (i + j) ?


Answer 1, authority 100%

The answer can be found in the Java specs, ยง15.26.2 Compound Assignment Operators :

Assignment of the form E1 op = E2 is equivalent to the expression E1 = (T) ((E1) op (E2)) , where T is the type of E1. The only difference is that E1 is evaluated only once.

Next, there is the following example:

This code is correct:

short x = 3;
x + = 4.6;

As a result, we get 7 for x , as this is equivalent to:

short x = 3;
x = (short) (x + 4.6);

In other words, your guesses are correct.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions