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

increment - Precedence of ++ and -- operators in Java

I read from the official tutorial of Java that prefix and postfix ++ -- have different precedences:

postfix: expr++ expr--

unary: ++expr --expr +expr -expr ~ !

Operators

According to the tutorial, shouldn't this

d = 1; System.out.println(d++ + ++d);

print out 6 (d++ makes d 2, ++d makes it 3) instead of 4?

I know the explanation of ++d being evaluated beforehand, but if d++ has higher precedence then ++d, why isn't d++ being first evaluated? And what is more, in what case should d++ shows that it has higher precedence?

EDIT:

I tried the following:

d = 1; System.out.println(++d * d++);

It returns 4. It seems that it should be 2*2, instead of 1*3.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The inside of the println statement is this operation (d++) + (++d)

  1. It is as follows, the value of d is read (d = 1)
  2. current value of d (1) is put into the addition function
  3. value of d is incremented (d = 2).

  4. Then, on the right side, the value of d is read (2)

  5. The value of d is incremented (now d = 3)
  6. Finally, the value of d (3) is put into the addition function

    thus 1 + 3 results in the 4

edit: sorry for the format, I'm rather bad at using the list haha


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

...