inc / dec Operations precedence

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?

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?

is equivalent to

is equivalent to

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

Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards

This thread has been viewed 1044 times.

All times above are in ranch (not your local) time.

The current ranch time is

Jun 19, 2018 08:47:00.

The current ranch time is

Jun 19, 2018 08:47:00.