class C{
static int f1(int i) {
System.out.print(i + ",");
return 0;
}
public static void main (String[] args) {
int i = 0;
i = i++ + f1(i);
System.out.print(i);
}
}
how come the answer is 1,0. Please explain.
Look at the expression:
i = i++ + f1(i);
One thing you need to understand here is what exactly i++ does and returns: it increments i, but returns the old value of i. So if i == 0, then i++ increments i to 1, but the resulting value of the expression is 0.
In Java, expressions are evaluated from left to right. So in the above expression, i++ is evaluated first, and then f1(i).
After i++, i == 1 so f1(i) is actually f1(1). This method prints the value of i, which is 1, with a comma after it, and returns 0.
Since i++ returns the old value of i (before it was incremented), the expression becomes:
i = 0 + 0;
The first 0 is the result of i++, the second 0 is the result of f1(i). So, i is assigned 0. Finally, you print the value of i.
i = i++ + f1(i);
first i is incremented to 1 and call f1(1) and there you print i , which prints 1 , and returns 0 which stores in i of main method by calculating 0 + 0 and you print it in main so the output becomes 1, 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With