GuruKulki
GuruKulki

Reputation: 26428

How does this expression will be calculated

I have an expression with compound assignment as

x += 2*5

so how it will be evaluated is it

x = (x + 2) * 5

or

x = x + (2 * 5)

and why?

Upvotes: 0

Views: 118

Answers (3)

polygenelubricants
polygenelubricants

Reputation: 384016

I see the phrase "operator precedence" mentioned, and I believe this is confusing the issue. Consider this:

x *= a + b;

Even though * has a higher precedence than +, this is still evaluated as

x = x * (a + b)

The full explanation is given in JLS 15.26.2 Compound Assignment Operatos:

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

Upvotes: 1

Progman
Progman

Reputation: 19570

Any expression in the form of var op= expr is evaluated to var = var op expr. This is defined in the java specification 15.26.2 Compound Assignment Operators.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1504122

An expression of the form

x += expr;

is equivalent to

x = x + (expr);

So in this case it's

x = x + (2 * 5);

It would be very weird and confusing if the current value of x was used for part of the expression implicitly.

Upvotes: 7

Related Questions