Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

operator precedence - a += a++ * a++ * a++ in Java. How does it get evaluated?

I came across this problem in this website, and tried it in Eclipse but couldn't understand how exactly they are evaluated.

    int x = 3, y = 7, z = 4;

    x += x++ * x++ * x++;  // gives x = 63
    System.out.println(x);

    y = y * y++;
    System.out.println(y); // gives y = 49

    z = z++ + z;
    System.out.println(z);  // gives z = 9

According to a comment in the website, x += x++ * x++ * x++ resolves to x = x+((x+2)*(x+1)*x) which turns out to be true. I think I am missing something about this operator precedence.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Java evaluates expressions left to right & according to their precedence.

int x = 3, y = 7, z = 4;

x (3) += x++ (3) * x++ (4) * x++ (5);  // gives x = 63
System.out.println(x);

y = y (7) * y++ (7);
System.out.println(y); // gives y = 49

z = z++ (4) + z (5);
System.out.println(z);  // gives z = 9

Postfix increment operator only increments the variable after the variable is used/returned. All seems correct.

This is pseudocode for the postfix increment operator:

int x = 5;
int temp = x;
x += 1;
return temp;

From JLS 15.14.2 (reference):

The value of the postfix increment expression is the value of the variable before the new value is stored.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...