0 votes
1 view
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 (46.1k 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

0 votes
1 answer
asked Jul 15, 2019 in Java by Nigam (4.1k points)
0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...