In
int x = 5;
int answer = x++ * 6 + 4 * 10 / 2;
the output is 50, and but why the ++ operator doesn't evaluate the expression to 51?
The ++ is on the x not the result.
why the ++ operator doesn't evaluate the expression to 51?
Can you explain how or why that would work? If you wanted that just do
int answer = x * 6 + 4 * 10 / 2 + 1;
The assignment is using the postfix operator which increments after the statement is executed.
The JLS mentions this:
The value of the postfix increment expression is the value of the
variable before the new value is stored.
For more details see the full specification entry.
Postfix operator is evaluates after execution of statement.
According to java
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value.
The defined effect of the ++ postfix operator is that the variable x gets incremented, as if you wrote x = x+1, but the value of the expression x++is the value before the increment. If you want to have th esame effect regarding how xchanges, but use the after avlue in the surrounding expression, you need to use ++x. And if you actually didn't want to increment the contents of x at all, use (x+1).
(It is however not defined, I think, when the assignment of the incremented value to x takes place - it might even be afer anwser obtains its value; on the other hand, usually x++ is almost atomic.)
Related
This question already has answers here:
How increment and decrement with if condition
(2 answers)
Closed 5 months ago.
class Example{
public static void main(String args[]){
int x=99;
if(x++==x){
System.out.println("x++==x : "+x); //Why this code line is not run?
}
if(++x==x ){
System.out.println("++x==x : "+x);
}
}
}
Why isn't the first println statement executed?
The operands of an expression are evaluated left to right.
In the expression x++ == x, first x++ is evaluated. It increments x by 1, but returns the original value of x. So x++ returns 99.
Then x is evaluated, which returns 100 (since it was incremented by x++).
Since 99 is not equal to 100, this condition evaluates to false.
If you change the expression to x==x++, you'll get true.
The differece between i++ and ++i is very simple.
i++ - means exactly first get the value and then increment it for the further usage
++i - means exactly first increment the value and use the incremented value
Following the shippet x++ == x means following:
Analyze expression from left to the right
Get x = 99 as the left operand and use it in the expression
Increment x and thus x == 100
Get x = 100 as the right operand (note it is already incremented)
99 != 100
Following the shippet ++x == x means following:
Analyze expression from left to the right
Get x = 99 as the left operand
Increment x and thus x == 100 and use it in the expression
Get x = 100 as the right operand (note it is already incremented)
100 == 100
You can see all these logic. E.g. not experienced developer cannot know these details. Therefore the best practice is to avoid such increments in the expression. Just do it before the expression in the single line. In this case the logic will be straight forward and you get much less problems.
I had to understand some code which mixes pre- and post-increments in functions. There was one thing that confused me.
So I tried to test some smaller function. But I could not explain following behaviour:
int i = 1;
i = i++ * ++i * 2;
System.out.println("i = " + i);
int x = 1;
x = ++x * x++ * 2;
System.out.println("x = " + x);
The expected output was:
i = 8
x = 8
But actually is:
i = 6
x = 8
Can someone tell me why?
i++ * ++i * 2 --> 1 * 3 * 2 --> 6
++x * x++ * 2 --> 2 * 2 * 2 --> 8
Important values in bold.
The difference between the prefix and postfix increment when returning values in Java can be better summarized by Oracle themselves (my bold again for highlighting purposes):
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.
Source here.
In your specific case, as the postfix evaluates to the original value and the order of operations is left to right for same arithmetic operator - here, only multiplier applies - your operations are translated as above.
Post-increment increases the value of i but does not immediately assign the new value of i.
Pre-increment increases the value of i and is immediately assigned the new value.
Thus, in your example for y, after i++,
i has become 2 but it is still holding on to the previous value of 1.
When ++i occurs, i with the value of 2 will be increased by 1 and simultaneously, assigned the new value of 3. Therefore, 1 * 3 * 2 gives us the value 6 for y.
The same goes for x,
when ++x occurs, x is immediately assigned the new value of 2.
However, when x++ occurs, x is increased by 1 but is still assigned the previous value of 2. Therefore, 2 * 2 * 2 gives us 8.
This question already has answers here:
Why does this expression i+=i++ differs from Java and C?
(8 answers)
Closed 6 years ago.
I am not understanding why this post increment equation does not increase. I would have thought that after the += operation the value would increment by 1 and then the second time around i would have a 1 value. But the output is an infinite loop of 0 zero. Is anyone able to explain why 'i' doesn't increase.
int i = 0;
for(; ; ) {
if ( i >= 10) break;
i += i++;
}
System.out.println(i);
Let's examine i += i++;
i++ means read the value for i, then increment i.
i += x means evaluate i, then evaluate x and add the 2 and put the result in i.
So, what happens is:
i gets evaluated, it is 0
i++ gets evaluated. it returns 0, and the value for i is set to 1
i += i++ is now i = 0 + 0.
i = 0
Try with ++i to get the result of the incrementation before reading its value.
While the answer from #njzk2 is correct, it is useful to point out why it is correct.
There are other possibilities - for example, why doesn't Java execute the postincrement operator after the assignment? (Answer: because that's not what the Java Language Designers chose)
The evaluation order for compound assignments (things like +=) is specified in the Java Language Specification section 15.26.2. I'll quote how it is defined for Java 8:
First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression
completes abruptly for the same reason; the right-hand operand is not
evaluated and no assignment occurs.
Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes
abruptly, then the assignment expression completes abruptly for the
same reason and no assignment occurs.
Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation
indicated by the compound assignment operator. If this operation
completes abruptly, then the assignment expression completes abruptly
for the same reason and no assignment occurs.
Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion
(ยง5.1.13) to the appropriate standard value set (not an
extended-exponent value set), and the result of the conversion is
stored into the variable.
The most important thing is that the value of the left hand expression is saved first, then the right hand is completely evaluated, and then the result of the compound operation is stored in the variable on the left hand side.
No surprise you are getting into infinity loop..
class Demo{
public static void main(String[] args){
int i = 0;
for( ; ; ) {
if (i >= 10)
break;
i = i+i++;
System.out.println(i);
}
}
}
assume the above code, I have just replaced your line with increment with what compiler will substitute.
Now, initially i=0;
So
i = i+i++
results in i = 0 + 0 // and now i is 1
but at the end you again make i equal to 0!
Hence infinity...
This question already has answers here:
What are the rules for evaluation order in Java?
(5 answers)
Closed 6 years ago.
x=10;
y = --x + x++;
System.out.println(y);
// prints 18
As per the link https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html, postfix increment(x++) has higher precedence than prefix increment/decrement (--x).
Hence x++ (value 10) should be executed before --x (value 11-1=10); so y=20. But How does 'y' become 18?
As it is explained at this link
Associativity and precedence determine in which order Java applies operators to subexpressions but they do not determine in which order the subexpressions are evaluated. In Java, subexpressions are evaluated from left to right (when there is a choice). So, for example in the expression A() + B() * C(D(), E()), the subexpressions are evaluated in the order A(), B(), D(), E(), and C(). Although, C() appears to the left of both D() and E(), we need the results of both D() and E() to evaluate C(). It is considered poor style to write code that relies upon this behavior (and different programming languages may use different rules).
This explains why
--x
is executed and evaluated before than
x++
as it is a sum of two sub-expressions and the whole expression is evaluated from left to right. So the first one is executed before than the x++ one (yes, the post-fix ++ has more precedence in general, but here the sub-expression that includes it is evaluated after the first one).
So, 18 is correct, as you are summing two times 9 to x, as clarified below
x=10;
y = --x + x++;
// y = (10-1) /* now x==9 */ + (9); /* after this x == 10 */
// y = (9) + (9); /* and now x == 10 */
// y == 18 and x == 10
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a difference between x++ and ++x in java?
Can anyone please explain me what is happening backyard to these statements?
int x=5;
System.out.println((x++)*x); //Gives output as 30
int x=5;
System.out.println((++x)*x); //Gives output as 36.
int x=5;
System.out.println((x++)*x); //Gives output as 30
You first take x (x = 5) as an operand. Then it's incremented to 6 which is second operand.
int x=5;
System.out.println((++x)*x); //Gives output as 36.
You first increment x by one (x = 6) and then multiply by x => 6 * 6 = 36
Multiplication is left-to-right associative, so the left operand will be evaluated first, then the right operand.
Post-increment operator will evaluate to current value of the variable, and increment it right after.
Pre-increment operator will increment the variable, then evaluate to the incremented value.
(x++) * x (x = 5)
--> 5 * x (increment deferred, x = 5)
--> 5 * x (increment x, x = 6)
--> 5 * 6
--> 30
(++x) * x (x = 5)
--> 6 * x (x is incremented before evaluated into expression, x = 6)
--> 6 * 6
--> 36
I mentioned the associativity here because it will affect the final result. If the associativity of multiplication is right-to-left instead of left-to-right, then the result will be 25 and 30 for post-increment and pre-increment expression respectively.
Assuming you understand that:
++x returns x+1 and increments x, while
x++ returns x and increments x,
the reason for the result is defined by the Java Language Specification #15.17
The multiplicative operators have the same precedence and are syntactically left-associative (they group left-to-right).
So in the first case, x++ is first evaluated, which returns 5 (it is the postfix operator) and adds 1 to x afterwards. Then the result of x++ (5) is multiplied by x (which is now 6) ==> 30
In the second case, ++x is first evaluated, which adds 1 to x and returns 6 (it is the prefix operator). Then the result of ++x (6) is multiplied by x (which is now 6) ==> 36
p++ means use then increment with a copy (copy is extremely local)
++p means increment and use without a copy
p++: use 5 and use incremented thing later in that line
++p: increment and use immediately
Post increment operators do the incrementation after the expression has been calculated.
In your first example, what is actually happening is:-
(x++) * x ; // (now incremented, 6 )
// x (5) * x+1 (6)
In your second example, the increment happens first
(++x) * x; // incremented straight away.
// x+1 (6) * x (now 6)