Value of expression with pre-increment and post-decrement in Java - java

Consider the following expressions:
int x = 5, y = 5, z;
z = y + x * y-- + ++x;
According to my calculations the value of z should be 40 considering ++ and -- have higher precedence than +.
So z = 4 + 6 * 5 + 6 = 40.
Running the code yields a result of z = 36. How does Java arrive at that result?
Also, what role does associativity (right to left) play here?

You must interpret it from left to right, so :
so z = y(5) + x(5) * y--(still 5, since the decrement will apply afterwards) + ++x(which is 6 because the increment applies before the evaluation of x)
The result being 36.

Operator precedence tells you how to parse the expression. It doesn't tell you anything about evaluation order.
There are two ways to look at this, you can either look at it as implicit braces, or as how the AST looks like.
If you look at it through the PoV of using braces, you end up with this:
z = y + x * y-- + ++x;
<=> z = y + (x * (y--)) + (++x);
<=> z = 5 + (5 * 5) + 6 // y-- is still 5 (4 afterwards), ++x is 6
<=> z = 5 + 25 + 6
<=> z = 36
If you look at it through the AST lens, you get
+
/ \
y +
/ \
* x++
/ \
x y--
Now if you go through that AST in evaluation order (left-right), you see that the leftmost y is still 5. On the right tree, we have again a +, which is the result of the multiplication and ++x. The multiplication is 5 * 5, since y-- is still 5 at that point, and y is 4 afterwards. And finally, ++x is 6 and x is 6 afterwards. Putting together, 5 + 25 + 6 = 36.
The AST is always evaluated in-order, operator precedence tells you how the AST looks like (stronger binding operators at the bottom, weaker binding one at the top).

int x = 5, y = 5, z;
z = y + x * y-- + ++x;
In this example var-- and var++ will be executed after z. And --var and ++var will be executed before z. In your case
z = 5 + 5 * 5 + 6 = 36
If you rewrite your expression to z = y + x * --y + ++x it will be z = 5 + 5 * 4 + 6 = 40.
If you rewrite your expression to z = y + x * y-- + x++ it will be z = 5 + 5 * 5 + 5 = 35.

Related

Java Unexped Outputs From Pre-Increment

I am trying to figure out why the following code gives two different results
I tried the followingL
int x = 4, y = 4;
System.out.println(x + --x);
System.out.println(--y + y);
And It outputs 7 6. From my knowledge, preincrement has a higher precendence than addition so it should decrease the value of x/y regardless of it's value in the expression but this is clearly not the case. Can anyone please explain this to me?
System.out.println(x + --x);
System.out.println(--y + y);
This can be re-written as:
x + --x => x + (x = x-1) => 4 + 3 = 7
--y + y => (y = y-1) + y (y here is already decreased in value) = 3 + 3 = 6

Tricky basic java operations [duplicate]

This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 3 years ago.
I got these 2 different codes in Java that I can't understand how they produce these specific outputs.
They seemed to work in 2 different logic and I can't figure it out!
int a = 5;
int b = 4;
a -= (b++) + ++a; // For more confusing results replace -= with += and see how the logic changes.
System.out.println(a); // Output: -5
and
int c = 8;
c += ++c;
System.out.println(++c); // Output: 18
How does each situation work and how are they producing these specific outputs?
The major difference here is what post and pre increment are. These determine whether the value is increased before evaluation, or afterward.
Here is how the first case breaks down mathematically:
a = 5 - (4 + 6), which reduces to -5.
Note that a is increased from ++a AKA preincrement before the math is done, however b is calculated as 4. Another thing to note is the a used from the -= uses the original a value, regardless of post or pre increment.
The second equation reduces to this mathematically:
c = 8 + 9 which reduces to 17.
The output prints 18 because your System.out.print(++c) increments it one more time before output due it being preincrement. Note if the print statement used c++, the value would print to 17.
The chart for operator precedence can be found here. Note that assignment has lower precedence than the unary/postfix operators.
It's all about the Operator Precedence in Java. Check that table and figure out which operation takes place first and which last.
It is equivalent to:
int a = 5;
int b = 4;
a -= (b++) + ++a; // => 5 -= (4) + 6
int c = 8;
c += ++c; // => 9 += 9
The main diff is thet:
++a and ++c increments the value and immediately returns it.
b++ returns the value and then increments it.
There is a difference in the order of ++. While both increase the variable, ++a will pass the original value to the operation chain your in middle of; while a++ would pass the new value. So for your first example:
++a --> a is now 6; but the equation is using 5:
a -= (b++) + 5;
b++ --> b is now 5;
a -= 5 + 5;
a -= 10;
? = 5 - 10;
a = a - 5 + 5;
a = 5 - 5 + 5;
a = -10;
(You should have enough to trace the second example).
For a list of operations try this. Some more increment examples are here.
A minimal example is `
int x=3,y=3;
x += ++x;
y+= y++;
at the x x is 7 and y is 6. Precedence alone is not enough to explain the behaviour. Using precedence the second line would be x += (++x), i.e. increment x and return its value, (x is now 4); next we have x+=4 which would return 8.
Instead, it seems better to treat x += w as a short hand for x = x + w, this rewriting happens before evaluation. In our case the rewriting is x = x + ++x interpreted as x = (x + (++x)). So interpreted as
x = ( 3 + (++x))
x = ( 3 + 4 ) x is 4
x = 7 x is 7
A simlar system works to the y equation giving y = 6 at the end.

If post-increment/decrement has precedence over pre-increment/decrement, then why is this expression evaluated like so: [duplicate]

This question already has answers here:
What are the rules for evaluation order in Java?
(5 answers)
Closed 6 years ago.
public class Test {
public static void main(String[] args) {
int x = 3;
int y = ++x * 5 * x--;
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
The output is:
x is 3
y is 80
But using the rule that post-operators take precedence over pre-operators, shouldn't it be like this:
y = ++x * 5 * 3 (x is 2)
y = 3 * 5 * 3 (x is 3)
y = 45
Instead, this code is acting as if it just evaluated the expression from left-to-right, evaluating the pre-increment before the post-decrement. Why?
int y = ++x * 5 * x--;
++x => Increase then evaluate => x == 4
x-- => Evaluate then decrease
So actually it looks like this:
int y = 4 * 5 * 4; // == 80
and because of the decrement operator, your x is 3 at the end.
Your problem is y = ++x * 5 * 3 (x is 2) its not (4)*5*3 its (4)*5*4. Pemdas my friend
int x = 3;
int y = ++x * 5 * x--; //x becomes 4 , then its 4*5*4 =80 = y
System.out.println("x is " + x); // x-- comes into affect and x = 3
System.out.println("y is " + y); // y = 80
Although x-- is being evaluated before x++ and everything else. It changes the value of x after the whole expression is evaluated. Unlike ++x when it get evaluated it changes the value of x immediately.

Order of code execute in java

I was running the following code
int x=4;
int y=3;
double z=1.5;
z=++x/y*(x-- +2);
int t=(++x/y);
System.out.println(z); //7
wondering how does it produce 7 when
(x-- +2) =6
++x/y=1.6666
3=6*1.6666=10
z=++x/y*(x-- +2);
is evaluated as:
z = ++x / y * (x-- + 2); // Substitute value of ++x, y and x--
= 5 / 3 * (5 + 2); // After this point, x will be 4. Evaluate parenthesized expr
= 5 / 3 * 7 // Now, left-to-right evaluation follows
= 1 * 7 // 5 / 3 due to integer division will give you 1, and not 1.66
and:
t = ++x / y; // x is 4 here
= 5 / 3
= 1
The code is evaluated as:
z=((++x)/y)*(x-- +2);
x and y are both int, so the calculation results of each step will be cast into int type. Which means 5/3=1.
In the end, the result is assigned to a double variable, so 7 will be cast to 7.0.
Modify the code to:
z=1.0 * ((++x)/y)*(x-- +2);
You'll get a decimal result.

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.
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.
Nothing to do with operator precedence per se, just the order of evaluation.
Two things to know here:
x++ is the postfix increment, so the value of x is incremented after it is evaluated
* evaluates the right side then the left side.
Considering point 2, the expression x++ * x++ * x++ can be rewritten more specifically as x++ * (x++ * (x++)).
The whole expression can be written as the procedures:
a = x
x += 1
b = x
x += 1
c = a*b
d = x
x += 1
return c*d
The postfix operator x++ means something like "give me the value of x now, but increment it for future references"
So, by the order of operations and evaluation,
x++ * x++ * x++
is interpreted first as
3 * 4 * 5 (=60)
Which is then added to the original 3, yielding 63.
The original value is used because it's on the same line, had you written something like:
int x = 3;
int y += x++ * x++ * x++;
x += y;
x would now be 66, instead of 63 because the x in the second line is now 6, rather than its original 3.
Because the increment Operation ++ is added after the variable x. That's a post increment operation. That means, x is incremented after the operation is handled.
In your example the expression would be:
x += 3 * 4 * 5
First the expression is added by 3 (x+=....)
then the first x++ results in 3
the second x++ results in 4 (because it was incremented before)
and the third x++ results in 5.
If you want your variable incremented before the operation is executed, you have to write ++x (pre increment operation)
Because a postincrement modifies the variable after the value is taken and += evaluates its left hand side before evaluating its right hand side,
x += x++ * x++ * x++;
becomes
tmp0 = x
tmp1 = x
++x
tmp2 = tmp1 * x
++x
tmp3 = tmp2 * x
++x
x = tmp0 + x
unary operators evaluated left to right, so the first x++ gets the value x, the second is (x+1), etc. And the += evaluates according to the value of x at the start, hence the addition of x

Categories

Resources