aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes inc / dec Operations precedence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "inc / dec Operations precedence" Watch "inc / dec Operations precedence" New topic
Author

inc / dec Operations precedence

Ruediger Froehlich
Greenhorn

Joined: Nov 18, 2010
Posts: 2
Hi there,

I'am prepairing for SCJP with ExamLab mock exams and got a Question about increment/decrement Operators.

x = 90;
y = 91;
I thought 'y' would be like : y = 45 + 45 , since it is a post-fix Operator.
So why 91?

if i change the term to:

... everything is as I expect it to be.
y = 46;


thanks for your help!

Ruediger

btw. can anyone point out, where to find this in the Java documentation?
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3068
    
  33


is equivalent to




is equivalent to


Mohamed Sanaulla | My Blog
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18747
    
  40

Ruediger Froehlich wrote:

x = 90;
y = 91;
I thought 'y' would be like : y = 45 + 45 , since it is a post-fix Operator.
So why 91?

btw. can anyone point out, where to find this in the Java documentation?


You getting confused with a mix of three different things ...

1. The behavior of the postfix operator has nothing to do with its precedence. In fact, the prefix and postfix increment operator has the same precedence. The behavior of the postfix operator merely states that the expression has value (the original value), and it has a side affect (the variable gets incremented) when used.

2. Precedence is used to determine which operands and results from other expressions should an operator work on. Think of it as the compiler putting implicit parens for you. It has nothing to do with what actually gets evaluated first. In this case, the postfix increment has higher priority than the add operator.

3. The order of evaluation is the actual order that the expression gets evaluated. And generally, it is done left to right.


So...

y = y++ + y;

Apply precedence...

y = ((y++) + y);

BTW, the assignment has the lowest precedence.

Evaluate left to right...

y = ((45)) + y);

The increment operator is encountered, it has a value of 45, and it has a side affect of incrementing y (So, y is now 46).

y = (45 + 46);

The result of the post increment is 45. Then the next operand is encountered, which is y, which has a value of 46.... and at this point, I think you can figure the rest for yourself.

Henry

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: inc / dec Operations precedence