In Java, why does the assignment in parentheses not occur before the rest of the expression is evaluated?

Consider

int a = 20;
a = a + (a = 5); // a == 25, why not 10?

Are all priority rules enclosed in parentheses? Are some variables represented in RHS before evaluating certain expressions?

+4
source share
3 answers

Because it is aloaded first in the example that you have, and then the bit in parentheses is calculated. If you change the order:

int a = 20;
a = (a = 5) + a;
System.out.println(a);
10

... you really get 10. Expressions are evaluated left to right.

Consider this:

f() + g()

fwill be called before g. Imagine how unintuitive he would be in

f() + (g())

to gbe called before f.

JLS §15.7.1 ( @paisanco , ).

+5

JLS

Java , , -, , .

, .

( ), , - .

+4

-:

BIPUSH 20
ISTORE 1
ILOAD 1
ICONST_5
DUP
ISTORE 1
IADD
ISTORE 1
RETURN
LOCALVARIABLE a I

20 (a):

BIPUSH 20
ISTORE 1

(20 ):

ILOAD 1

"5" (20 5 5):

ICONST_5
DUP

(a):

ISTORE 1

a now 5, now a stack (20 5). We add both operands and put their sum in the first variable (a):

IADD
ISTORE 1

As a result, and now 20 + 5 = 25. Finish:

RETURN
+2
source

All Articles