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)
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 am java newbie and trying to understand how calculation steps are performed to achieve final result. The final answer is coming as 49. Looking at precedence operators hierarchy my calculation is not coming to 49.
Following is my code with expression:
class Test
{
public static void main(String args[])
{
int a = 6, b = 5;
a = a + a++ % b++ *a + b++ * --b;
System.out.print(a)
}
}
Modulo has same precedence as division and multiplication. The next precedence goes to addition and subtraction.Operations happen left to right.
Adding brackets for better clarity:
( a ) + ( a++ % b++ *a ) + ( b++ * --b )
group I II III
a++ % b++ *a evaluated as :a. (6 % 5) = 1
b. 1 * 6 till now, a = 6, b = 5
Having completed this operation, the value of a & b are incremented to 7 & 6 respectively. i.e the post fix increment happens only after the modulo/multiplication/division during a step or group as shown above.
b++ * --b => 6 * 6. gives value of 36
Having completed this operation the ++ operation is performed but -- is also performed, effectively leaving the value of b at 6.
next operation is addition. i.e 7 + 6 + 36 = 49
Reference: https://www.programiz.com/java-programming/operator-precedence
Operators have priorities. There is a table of these here.
Also, you can use round brackets (parentheses) for forcing the right sequence of calculations.
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:
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
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.)