Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.5k points)

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

1 Answer

0 votes
by (46k points)

As continually with these questions, the JLS operates the answer. In this instance §15.26.2 Compound Assignment Operators. In essence:

A compound job expression of the class E1 op= E2 is similar to E1 = (T)((E1) op (E2)), where T is the type of E1, besides that E1 is estimated only once.

A case cited from §15.26.2

[...] the following code is right:

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 word, your opinion is right.

Related questions

Browse Categories

...