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
296 views
in Technique[技术] by (71.8m points)

increment - When are values in Java variables evaluated/returned/fetched in an expression?

According to http://introcs.cs.princeton.edu/java/11precedence/, post-increment operator has higher precedence than addition operator.

So, for the following code:

    int i = 1;
    int j = i + i++;
    System.out.println(j);

I would have thought that the expression assigned to j would have been evaluated as follows (with each line being a "step" in the evaluation) :

   i + i++
   i + (1)   // do post-increment operator; returns 1, and makes i = 2
   (2) + (1)   // do addition operator. need to get the operand i, so do that.
   3

But when I try this program, the value of j is 2.
So I'm confused. In the expression, does it replace all the "i"s in the expression with the current value of i, BEFORE even touching the i++ ?


Edit: the phrase "evaluation order" that people here used, helped me to find the following potentially helpful stackoverflow answer: What are the rules for evaluation order in Java? .


Edit: I made my best guess into an answer below. I still welcome corrections to it.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

According to Java Language Specification, 15.7.1

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.

Hence the i on the left side of the addition operator is evaluated before i++ on the right side.


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

...