Didn't understand the answer of this piece of code (java)

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 the answer is 1.0. Explain, please.

+3


source to share


2 answers


i = i++ + f1(i);

      



first i increments by 1 and calls f1 (1) and there you print i, which prints 1 and returns 0, stores in i of the main method calculating 0 + 0 and you print it basically so that the output becomes 1. 0

+2


source


Look at the expression:

i = i++ + f1(i);

      

Here you need to understand what exactly does and returns i++

: it increments i

, but returns the old value i

. Therefore, if i == 0

, then i++

increments i

by 1

, but the resulting value of the expression 0

.

In Java, expressions are evaluated from left to right. So, in the above expression, it evaluates first i++

and then f1(i)

.



After i++

, i == 1

therefore f1(i)

actually f1(1)

. This method prints the value i

that 1

, with a comma after it, and returns 0

.

Since it i++

returns the old value i

(before it is incremented), the expression becomes:

i = 0 + 0;

      

The first 0

is the result i++

, the second 0

is the result f1(i)

. Thus, it is i

assigned 0

. Finally, you print the value i

.

+5


source







All Articles