Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not understood the answer of this code snippet(java) [closed]

Tags:

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 come the answer is 1,0. Please explain.

like image 442
Abhishek Prakash Avatar asked Nov 29 '25 05:11

Abhishek Prakash


2 Answers

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.

like image 88
Jesper Avatar answered Dec 01 '25 19:12

Jesper


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

like image 31
Chandra Sekhar Avatar answered Dec 01 '25 20:12

Chandra Sekhar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!