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.
Related
This question already has answers here:
What are the rules for evaluation order in Java?
(5 answers)
Closed 4 years ago.
For the next code, what it's z? (Java)
int x = 5;
int y = 10;
int z =++x*y--;
The order of priority is: y--, ++x, *, =.
( https://introcs.cs.princeton.edu/java/11precedence/ )
Why after run the code, z = 60 ?
The ++ operator is evaluated before the expression.
i.e.:
int x = 10;
int y = ++x; //y = 11
int z = x ++; // z = 11;
y-- is higher up on the list from your source. However, when the post-decrement happens, it happens after the whole evaluation.
So if you print y after getting the value of z, it will be 9.
And the pre-increment happens first, so ++x becomes 6 within that statement (and obviously multiplies by 10).
See an example in the docs.
Considering this expression:
x1 = ++x - x++ + --x
if the value of x is entered 5
What will be the output of such expression in java, and why?
There is no greater precedence in + or -.
Without parentheses they are just executed in the order of apperance, lets consider your example:
public class Test {
public static void main(String[] args) {
int x = 5;
int x1 = ++x - x++ + --x;
System.out.println(x1);
}
}
will print 6
There are four operations of pre/post incrementation/decrementation:
++x will increment before evaluation (before using its value in the expression)
--x will decrement before evaluation
x++ will increment after evaluation (after using its value in the expression)
x-- will decreemnt after evaluation
Breaking the expression to parts:
1) "++x" the x will be incremented by 1 before using its value in the expression, so for now it is:
6 -
2) "- x++" the x will be incremented by one after using its value in expression, so it is:
6 - 6 , but now x=7
3) "+ --x" the x will be decremented by one, before its value will be used, so it finally translates to:
x1 = 6 - 6 + 6;
This will be executed as:
x1 = 0 + 6;
x1 = 6;
Obviously, there is no greater precedence in + or -, as it is just subtracted and added in the order of apperance.
Confusion rose because of this post. The author updated his post, and the result became clear.
Conclusion: Java evaluates expressions from left to right
Closed!
As evaluation of expression is done from right to left the following code should store 5 in j:
int i=2;
int j=++i+i++;
System.out.println(j);
But I get 6 as the output, which forces me to re-think the right to left evaluation idea. Kindly explain the theory here.
You get 6 because it's 3 + 3:
the first OP is ++i which increments first (to 3) then that value is used
next OP is +i which adds 3 again
last OP ++ doesn't take part in the addition, but it increments i after using it
Your assumption is false. Here's what the documentation says :
All binary operators except for the assignment operators are evaluated
from left to right
So
++i+i++
is equivalent to
(++i)+(i++)
where ++i is evaluated first.
This gives
3+3
which is 6 (and i has value 4 after this).
int i = 2;
int j = ++i + i++;
is the same as
int i = 2;
// This part is from ++i
i = i + 1;
int left = i; // 3
// This part is from i++
int right = i; // 3
i = i + 1;
int j = left + right; // 3 + 3 = 6
If instead you'd done:
int i = 2;
int j = i++ + ++i;
that would be equivalent to:
int i = 2;
// This part is from i++
int left = i; // 2
i = i + 1;
// This part is from ++i
i = i + 1;
int right = i; // 4
int j = left + right; // 2 + 4 = 6
So the sum is the same, but the terms being summed are different.
The first ++ increments i. The + adds i to itself. i is 3.
Where'd you get the idea that it is right-to-left? It is left-to-right.
What are the rules for evaluation order in Java?
This how it works, since unary operators have more precedance than binary:
int i=2;
int j =(++i)+(i++);
^^^ ^^^
3 +(i++) //The value of i is now 3.
^^^ ^^^
3 + 3 //The value of i is incremented after it is assigned.
When evaluating an expression such as a+b, before you can add 'b' to 'a', you need to know what 'a' is. In this case, a is ++i, which is 3, and b is i++ which is 3. Evaluating right-to-left gives 3 + 3 = 6
In Java and C#, the evaluation of subexpressions will be done left to right:
int j=++i + i++;
contains the following two subexpressions ++i and i++. These subexpressions will be evaluated in this order so this will translate into:
int j= 3 + 3;
As in Java and C#, the ++i will be executed returning 3 but i will be changed to 3 before the second i++. The second will return the current value of i which is 3 now and after i++ the value of i will be 4.
In C++ this would be undefined.
And in real-world, you do not want to type this code (except for code golfing)
I've misplaced += with =+ one too many times, and I think I keep forgetting because I don't know the difference between these two, only that one gives me the value I expect it to, and the other does not.
Why is this?
a += b is short-hand for a = a + b (though note that the expression a will only be evaluated once.)
a =+ b is a = (+b), i.e. assigning the unary + of b to a.
Examples:
int a = 15;
int b = -5;
a += b; // a is now 10
a =+ b; // a is now -5
+= is a compound assignment operator - it adds the RHS operand to the existing value of the LHS operand.
=+ is just the assignment operator followed by the unary + operator. It sets the value of the LHS operand to the value of the RHS operand:
int x = 10;
x += 10; // x = x + 10; i.e. x = 20
x =+ 5; // Equivalent to x = +5, so x = 5.
+= → Add the right side to the left
=+ → Don't use this. Set the left to the right side.
a += b equals a = a + b. a =+ b equals a = (+b).
x += y
is the same as
x = x + y
and
x =+ y
is wrong but could be interpreted as
x = 0 + y
It's simple.
x += 1 is the same as x = x + 1 while
x =+ 1 will make x have the value of (positive) one
Some historical perspective: Java inherited the += and similar operators from C. In very early versions of C (mid 1970s), the compound assignment operators had the "=" on the left, so
x =- 3;
was equivalent to
x = x - 3;
(except that x is only evaluated once).
This caused confusion, because
x=-1;
would decrement x rather than assigning the value -1 to it, so the syntax was changed (avoiding the horror of having to surround operators with blanks: x = -1;).
(I used -= and =- in the examples because early C didn't have the unary + operator.)
Fortunately, Java was invented long after C changed to the current syntax, so it never had this particular problem.
Because =+ is not a Java operator.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is there a difference between x++ and ++x in java?
I am reading the official Java tutorial and I don't get the difference between postfix and prefix (++x vs x++). Could someone explain?
++x: increment x; the value of the overall expression is the value after the increment
x++: increment x; the value of the overall expression is the value before the increment
Consider these two sections:
int x = 0;
System.out.println(x++); // Prints 0
// x is now 1
int y = 0;
System.out.println(++y); // Prints 1
// y is now 1
I personally try to avoid using them as expressions within a larger statement - I prefer standalone code, like this:
int x = 0;
System.out.println(x); // Prints 0
x++;
// x is now 1
int y = 0;
y++;
System.out.println(y); // Prints 1
// y is now 1
Here I believe everyone would be able to work out what's printed and the final values of x and y without scratching their heads too much.
There are definitely times when it's useful to have pre/post-increment available within an expression, but think of readability first.
++x increments x and then returns the value
x++ returns the value of x and then increments the variable
For example:
int x = 0;
int A = ++x; // A = 1
int B = x++; // B = 1
int C = x; // C = 2
Well, you get enough answers, I'm going just to worry you... Both post- and pre-increment operators can confuse code, so sometimes it is better to use just x+1 then you and other people definitely know what is going on there. Some examples:
int x = 5;
x = ++x;
System.out.println( x ); // prints 6
x = x++;
System.out.println( x ); // prints 6!
x = ++x + x++;
System.out.println( x ); // prints 14!
two last incrementing can be a source of problems to debug then (was watching that few times in my life...). x = x++ - it is evaluated before incrementing... So be careful!
++x is pre-incrementing and x++ is post-incrementing. With post-incrementing the value is increased after evaluation and with pre-incrementing the value is increased before evaluation.
Well, standing alone it's the same. but, if there are other operands involved - ++x will advance x and then apply the other operands, and x++ will first use x and then advance it.
Basically, ++x adds 1 to x before x is evaluated, while x++ adds 1 afterwards. It makes sense if you use it as an argument.
Let's start with x
int x = 3;
If we call System.out.println on x using the infix operator:
System.out.println(++x);
x will first increase to 4 and the println will output, "4". It is pretty much the same if we did:
x+=1;
System.out.println(x);
Let's imagine x equals 3 again. If we call System.out.println on x using the postfix operator:
System.out.println(x++);
It will first output the current value of x, "3", and then increase x. So it's like:
System.out.println(x);
x+=1;
Hope that helps.