Can you explain to me the output of this Java code?
int a=5,i;
i=++a + ++a + a++;
i=a++ + ++a + ++a;
a=++a + ++a + a++;
System.out.println(a);
System.out.println(i);
The output is 20 in both cases
++a increments and then uses the variable.
a++ uses and then increments the variable.
If you have
a = 1;
and you do
System.out.println(a++); //You will see 1
//Now a is 2
System.out.println(++a); //You will see 3
codaddict explains your particular snippet.
Does this help?
a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)
a = 5;
i=a++ + ++a + ++a; =>
i=5 + 7 + 8; (a=8)
The main point is that ++a increments the value and immediately returns it.
a++ also increments the value (in the background) but returns unchanged value of the variable - what looks like it is executed later.
In both cases it first calculates value, but in post-increment it holds old value and after calculating returns it
++a
a = a + 1;
return a;
a++
temp = a;
a = a + 1;
return temp;
i = ++a + ++a + a++;
is
i = 6 + 7 + 7
Working: increment a to 6 (current value 6) + increment a to 7 (current value 7). Sum is 13 now add it to current value of a (=7) and then increment a to 8. Sum is 20 and value of a after the assignment completes is 8.
i = a++ + ++a + ++a;
is
i = 5 + 7 + 8
Working: At the start value of a is 5. Use it in the addition and then increment it to 6 (current value 6). Increment a from current value 6 to 7 to get other operand of +. Sum is 12 and current value of a is 7. Next increment a from 7 to 8 (current value = 8) and add it to previous sum 12 to get 20.
++a increments a before it is evaluated.
a++ evaluates a and then increments it.
Related to your expression given:
i = ((++a) + (++a) + (a++)) == ((6) + (7) + (7)); // a is 8 at the end
i = ((a++) + (++a) + (++a)) == ((5) + (7) + (8)); // a is 8 at the end
The parenteses I used above are implicitly used by Java. If you look at the terms this way you can easily see, that they are both the same as they are commutative.
In the above example
int a = 5,i;
i=++a + ++a + a++; //Ans: i = 6 + 7 + 7 = 20 then a = 8
i=a++ + ++a + ++a; //Ans: i = 8 + 10 + 11 = 29 then a = 11
a=++a + ++a + a++; //Ans: a = 12 + 13 + 13 = 38
System.out.println(a); //Ans: a = 38
System.out.println(i); //Ans: i = 29
I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.
The code will work like this:
int a=5,i;
i=++a + ++a + a++; /*a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8); i=20;*/
i=a++ + ++a + ++a; /*a = 5;
i=a++ + ++a + ++a; =>
i=8 + 10 + 11; (a=11); i=29;*/
a=++a + ++a + a++; /*a=5;
a=++a + ++a + a++; =>
a=12 + 13 + 13; a=38;*/
System.out.println(a); //output: 38
System.out.println(i); //output: 29
++a is prefix increment operator:
the result is calculated and stored first,
then the variable is used.
a++ is postfix increment operator:
the variable is used first,
then the result is calculated and stored.
Once you remember the rules, EZ for ya to calculate everything!
Presuming that you meant
int a=5; int i;
i=++a + ++a + a++;
System.out.println(i);
a=5;
i=a++ + ++a + ++a;
System.out.println(i);
a=5;
a=++a + ++a + a++;
System.out.println(a);
This evaluates to:
i = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
so i is 6 + 7 + 7 = 20 and so 20 is printed.
i = (5, a is now 6) + (7, a is now 7) + (8, a is now 8)
so i is 5 + 7 + 8 = 20 and so 20 is printed again.
a = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
and after all of the right hand side is evaluated (including setting a to 8) THEN a is set to 6 + 7 + 7 = 20 and so 20 is printed a final time.
when a is 5, then a++ gives a 5 to the expression and increments a afterwards, while ++a increments a before passing the number to the expression (which gives a 6 to the expression in this case).
So you calculate
i = 6 + 7 + 7
i = 5 + 7 + 8
Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.
Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.
pre-increment and post increment are equivalent if not in an expression
int j =0;
int r=0
for(int v = 0; v<10; ++v) {
++r;
j++;
System.out.println(j+" "+r);
}
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
I believe you are executing all these statements differently
executing together will result => 38 ,29
int a=5,i;
i=++a + ++a + a++;
//this means i= 6+7+7=20 and when this result is stored in i,
//then last *a* will be incremented <br>
i=a++ + ++a + ++a;
//this means i= 5+7+8=20 (this could be complicated,
//but its working like this),<br>
a=++a + ++a + a++;
//as a is 6+7+7=20 (this is incremented like this)
a=5; i=++a + ++a + a++;
is
i = 7 + 6 + 7
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6 . then a=7 is provided to post increment => 7 + 6 + 7 =20 and a =8.
a=5; i=a++ + ++a + ++a;
is
i=7 + 7 + 6
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6.then a=7 is provided to post increment => 7 + 7 + 6 =20 and a =8.
Related
Can you explain to me the output of this Java code?
int a=5,i;
i=++a + ++a + a++;
i=a++ + ++a + ++a;
a=++a + ++a + a++;
System.out.println(a);
System.out.println(i);
The output is 20 in both cases
++a increments and then uses the variable.
a++ uses and then increments the variable.
If you have
a = 1;
and you do
System.out.println(a++); //You will see 1
//Now a is 2
System.out.println(++a); //You will see 3
codaddict explains your particular snippet.
Does this help?
a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)
a = 5;
i=a++ + ++a + ++a; =>
i=5 + 7 + 8; (a=8)
The main point is that ++a increments the value and immediately returns it.
a++ also increments the value (in the background) but returns unchanged value of the variable - what looks like it is executed later.
In both cases it first calculates value, but in post-increment it holds old value and after calculating returns it
++a
a = a + 1;
return a;
a++
temp = a;
a = a + 1;
return temp;
i = ++a + ++a + a++;
is
i = 6 + 7 + 7
Working: increment a to 6 (current value 6) + increment a to 7 (current value 7). Sum is 13 now add it to current value of a (=7) and then increment a to 8. Sum is 20 and value of a after the assignment completes is 8.
i = a++ + ++a + ++a;
is
i = 5 + 7 + 8
Working: At the start value of a is 5. Use it in the addition and then increment it to 6 (current value 6). Increment a from current value 6 to 7 to get other operand of +. Sum is 12 and current value of a is 7. Next increment a from 7 to 8 (current value = 8) and add it to previous sum 12 to get 20.
++a increments a before it is evaluated.
a++ evaluates a and then increments it.
Related to your expression given:
i = ((++a) + (++a) + (a++)) == ((6) + (7) + (7)); // a is 8 at the end
i = ((a++) + (++a) + (++a)) == ((5) + (7) + (8)); // a is 8 at the end
The parenteses I used above are implicitly used by Java. If you look at the terms this way you can easily see, that they are both the same as they are commutative.
In the above example
int a = 5,i;
i=++a + ++a + a++; //Ans: i = 6 + 7 + 7 = 20 then a = 8
i=a++ + ++a + ++a; //Ans: i = 8 + 10 + 11 = 29 then a = 11
a=++a + ++a + a++; //Ans: a = 12 + 13 + 13 = 38
System.out.println(a); //Ans: a = 38
System.out.println(i); //Ans: i = 29
I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.
The code will work like this:
int a=5,i;
i=++a + ++a + a++; /*a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8); i=20;*/
i=a++ + ++a + ++a; /*a = 5;
i=a++ + ++a + ++a; =>
i=8 + 10 + 11; (a=11); i=29;*/
a=++a + ++a + a++; /*a=5;
a=++a + ++a + a++; =>
a=12 + 13 + 13; a=38;*/
System.out.println(a); //output: 38
System.out.println(i); //output: 29
++a is prefix increment operator:
the result is calculated and stored first,
then the variable is used.
a++ is postfix increment operator:
the variable is used first,
then the result is calculated and stored.
Once you remember the rules, EZ for ya to calculate everything!
Presuming that you meant
int a=5; int i;
i=++a + ++a + a++;
System.out.println(i);
a=5;
i=a++ + ++a + ++a;
System.out.println(i);
a=5;
a=++a + ++a + a++;
System.out.println(a);
This evaluates to:
i = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
so i is 6 + 7 + 7 = 20 and so 20 is printed.
i = (5, a is now 6) + (7, a is now 7) + (8, a is now 8)
so i is 5 + 7 + 8 = 20 and so 20 is printed again.
a = (6, a is now 6) + (7, a is now 7) + (7, a is now 8)
and after all of the right hand side is evaluated (including setting a to 8) THEN a is set to 6 + 7 + 7 = 20 and so 20 is printed a final time.
when a is 5, then a++ gives a 5 to the expression and increments a afterwards, while ++a increments a before passing the number to the expression (which gives a 6 to the expression in this case).
So you calculate
i = 6 + 7 + 7
i = 5 + 7 + 8
Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.
Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.
pre-increment and post increment are equivalent if not in an expression
int j =0;
int r=0
for(int v = 0; v<10; ++v) {
++r;
j++;
System.out.println(j+" "+r);
}
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
I believe you are executing all these statements differently
executing together will result => 38 ,29
int a=5,i;
i=++a + ++a + a++;
//this means i= 6+7+7=20 and when this result is stored in i,
//then last *a* will be incremented <br>
i=a++ + ++a + ++a;
//this means i= 5+7+8=20 (this could be complicated,
//but its working like this),<br>
a=++a + ++a + a++;
//as a is 6+7+7=20 (this is incremented like this)
a=5; i=++a + ++a + a++;
is
i = 7 + 6 + 7
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6 . then a=7 is provided to post increment => 7 + 6 + 7 =20 and a =8.
a=5; i=a++ + ++a + ++a;
is
i=7 + 7 + 6
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6.then a=7 is provided to post increment => 7 + 7 + 6 =20 and a =8.
package com;
public class Test {
public static void main(String[] args)
{
int a= 11, b = 10;
a = a++ + ++b; //why? output is "22 11" and not "23 11"
System.out.println(a+" "+b);
}
}
Here's how the expression gets evaluated (roughly, I didn't check the JLS for evaluation order but I think it's from left to right):
a = a++ + ++b; // a is 11, b is 10
a = 11 + ++b; // a is 12 but its previous value 11 was returned by a++, b is 10
a = 11 + 11; // a is 12, b is 11 and its updated value was returned by ++b
a = 22; // a is 12, b is 11 and its updated value was returned by ++b
Therefore, it's the expected result, you just have to apply the definition of those operators.
a++ means that "a" has old value in place where you write it and change it after. ++a means that "a" at fist change value and than will be calculate.
So:
a = 5;
b = 5;
So:
a++ + ++b = (5 (and a + 1 later) + (at first b + 1) 6.
I hope you understand me) My English is in the same level with your Java=)
This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
(14 answers)
Closed 5 years ago.
In the below programs , post increment operator is used just after completion of expression evaluation. Now for the first program shouldn't the answer be 40 n then value of a be incremented to 41.N likewise for program 2 answer should be 41 instead of 42?
class IncrementDemo{
public static void main(String [] args){
int a=20;
a= a++ + a++;
System.out.println(a); //Answer given is 41
}
class IncrementDemo{
public static void main(String [] args){
int a=20;
a= a++ + ++a;
System.out.println(a);
}
Answer given is 42 for second program.
You can understand the behaviour if you analyze how the statement is executed and the state of a in the meanwhile.
a = 20
a++ is executed, 20 is the result of the evaluation, a = 21
the second a++ is executed, 21 is the result, a = 22
the two results are added, 20 + 21 = 41, a = 41
on the other side, in the second case:
a = 20
a++ is executed, 20 is the result of the evaluation, a = 21
++a is executed, a = 22, 22 is the result
the two results are added, 20 + 22 = 42, a = 42
This is because the two increment operators are evaluated sequentially, so the second sees the effect of the first one.
The difference between those two is, that ++a will increment the value of a and return the incremented value. On the other hand a++ will increment the value, but return the original value that a had before being incremented.
The results are correct.
First case
int a=20;
a= a++ + a++;
This results in the following evaluation steps:
a = a++ + a++ (with a=20)
a = 20 + a++ (with a=21)
a = 20 + 21 (with a=22)
Second case
int a=20;
a= a++ + ++a;
This results in the following evaluation steps:
a = a++ + ++a (with a=20)
a = 20 + ++a (with a=21)
a = 20 + 22 (with a=22)
When operator used in prefix mode, it increments the operand and
evaluates to the incremented value of that operand. When used in
postfix mode, it increments its operand, but evaluates to the value of
that operand before it was incremented.
a= a++ + a++;
so first a++ will yield 20, now a value become 21
second a++ will yield 21, so final operation return 20+21 = 41
similar for second program
int a=20;
a= a++ + ++a;
First a++ will yield 20, now a value become 21
second ++a will yield value 22
combining both will return result 20+22 = 42
a = a++ + a++
For the first a++, the value of a being used for the calculation is its actual value: 20, and after that it is incremented to 21.
So, for the second a++, the value used for the calculation, is also the actual value of a, but this time it is 21 because it has been incremented in the first a++.
So you have 20 + 21, hence 41.
a = a++ + ++a
Same thing for a++, the actual value of a, 20 is used for the calculation, and then it is incremented to 21.
Then ++a, the value is incremented before it is used, so it becomes 22, and then it is used for the calculation.
So you have 20 + 22, hence 42.
I saw this code online but what I am asking is how did the program come up with an answer of 12 ?
I did a tracing of the program, and I only come up with an answer of 6 .
Why is the answer 12 ?
The inputs are a=6 and b=6.
This is the code:
public static int addxy(int a, int b)
{
if (a==0)
return b;
else if (b==0)
return a;
else
return 1 + addxy(a, b-1);
}
addxy(6,6)
1+addxy(6,5)
1+1+addxy(6,4)
1+1+1+addxy(6,3)
1+1+1+1addxy(6,2)
1+1+1+1+1+addxy(6,1)
1+1+1+1+1+1+addxy(6,0) = 12
Try walking over it step by step:
addxy(6, 6) returns 1 + addxy(6, 5)
addxy(6, 5) returns 1 + addxy(6, 4)
addxy(6, 4) returns 1 + addxy(6, 3)
addxy(6, 3) returns 1 + addxy(6, 2)
addxy(6, 2) returns 1 + addxy(6, 1)
addxy(6, 1) returns 1 + addxy(6, 0)
addxy(6, 0) returns 6
So, addxy(6, 1) returns 1 + 6 = 7
So, addxy(6, 2) returns 1 + 7 = 8
So, addxy(6, 3) returns 1 + 8 = 9
So, addxy(6, 4) returns 1 + 9 = 10
So, addxy(6, 5) returns 1 + 10 = 11
So, addxy(6, 6) returns 1 + 11 = 12
This
return 1 + addxy(a, b-1);
returns 1 plus the result of calling the method recursively while removing 1 from b. This basically means that it adds b.
When b is 0, you return a.
else if (b==0)
return a;
(You also return b, when a is 0.
Without even tracing anything, you can tell that (with non-negative values for a and b) the method simply adds a and b and returns the result.
Look at the return statement
return 1 + addxy(a, b-1);
You have a function call in the return statement to the same function. This is called a recursive function. So as long as b is not 0, it keeps on calling it again n again but by adding 1 and subtracting b by 1. This goes on till b becomes 0. Which is 6 times. And thats why you get 1*6 + a = 6
Equivalent execution would be
return 1 + addxy(6, 5);
return 1 + 1 + addxy(6, 4);
return 1 + 1 + 1 + addxy(6, 3);
return 1 + 1 + 1 + 1 + addxy(6, 2);
return 1 + 1 + 1 + 1 + 1 + addxy(6, 1);
return 1 + 1 + 1 + 1 + 1 + 1 + addxy(6, 0);
return 1 + 1 + 1 + 1 + 1 + 1 + 6; // Value of a = 6
return 12;
As #Mureinik answer is perfect but you didn't understand it ,
So Lets start with a very basic example of Calculating Factorial via Recursion:
public int factorial(int num){
if(num==0) //break condition of Recursion Since 0! is always 1
return 1;
return num*fact(num-1);
}
So here is the Tracing
factorial(4) return 4*factorial(3);
factorial(3) return 3*factorial(2);
factorial(2) return 2*factorial(1);
factorial(1) return 1*factorial(0);
factorial(0) returns 1;
, Now backtrace this answers and this below image is formed
May Be now you are able to understand it
Consider
int a = 20;
a = a + (a = 5); // a == 25, why not 10?
Don't parentheses trump all precedence rules? Are some variables on the RHS prepopulated before evaluation of certain expressions?
Because a is loaded first in the example you have, and then the bit in parenthesis is evaluated. If you reversed the order:
int a = 20;
a = (a = 5) + a;
System.out.println(a);
10
... you do indeed get 10. Expressions are evaluated from left to right.
Consider this:
f() + g()
f will be called before g. Imagine how unintuitive it would be, in
f() + (g())
to have g be called before f.
This is all detailed in JLS ยง15.7.1 (thanks to #paisanco for bringing it up in the comments).
From the JLS
The Java programming language guarantees that the operands of
operators appear to be evaluated in a specific evaluation order,
namely, from left to right.
and
The left-hand operand of a binary operator appears to be fully
evaluated before any part of the right-hand operand is evaluated.
Wrapping an expression in parentheses just helps grouping (and associativity), it doesn't force its evaluation to happen before anything to its left.
Generated bytecode:
BIPUSH 20
ISTORE 1
ILOAD 1
ICONST_5
DUP
ISTORE 1
IADD
ISTORE 1
RETURN
LOCALVARIABLE a I
First, you assign 20 to the first variable (a):
BIPUSH 20
ISTORE 1
Then, you load the contents of the first variable to stack (20 is put on stack):
ILOAD 1
Then, you push the constant '5' to the stack twice (20 5 5):
ICONST_5
DUP
Then, you store the top of the stack to the first variable (a):
ISTORE 1
a is now 5, stack is now (20 5). We add both operands and put their sum to the first variable (a):
IADD
ISTORE 1
As a consequence, a is now 20 + 5 = 25. We end:
RETURN
You asked why and the latest JLS provides a clearer explanation of what is happening in JLS 17:
In particular, the presence or absence of parentheses around an
expression does not affect whether a variable is definitely assigned,
definitely assigned when true, definitely assigned when false,
definitely unassigned, definitely unassigned when true, or definitely
unassigned when false.
In effect they are saying that parentheses do not prompt assignment, which explains why assignment occurs left-to-right, unlike evaluation, which occurs in innermost-to-outermost order.
But that still does not answer why.
It's not because of compatibility with Java's predecessor, at least not in its present form, because the behavior does not match C:
Java 17:
int j = 3, k = 4, l = 5, m = 6, n = 7;
System.out.println(((j = 3) + j) + j); // 3 + 3 + 3 = 9
System.out.println(k + (k + (k = 3))); // 4 + 4 + 3 = 11
System.out.println(l + ((l = 3) + l)); // 5 + 3 + 3 = 11
System.out.println((m + (m += 3)) + m); // 6 + 9 + 9 = 24
System.out.println(n + (n += n / 2) + ++n); // 7 + 11 + 12 = 28
GCC 7.5.0:
printf("%d\n",((j = 3) + j) + j); // 3 + 3 + 3 = 9
printf("%d\n",k + (k + (k = 3))); // 3 + 3 + 3 = 9
printf("%d\n",l + ((l = 3) + l)); // 3 + 3 + 3 = 9
printf("%d\n",(m + (m += 3)) + m); // 9 + 9 + 9 = 27
printf("%d\n",n + (n += n / 2) + ++n); // 10 + 10 + 11 = 31
This leaves us with the explanation used elsewhere for Java awkwardness: upgradeability. Java happened to do it this way at the time it was written; changing it to work in alignment with C would potentially break existing code. I'd be curious to know of any discussion that might have taken place when the initial design was decided.