Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happen in method after return statement

public class TestReturn {
     int i = 0;

    public static void main(String[] args) {
        TestReturn t = new TestReturn();

        System.out.println(t.test());
        System.out.println(t.i);
    }

    private int test() {
            return i++;
    }
}

output

0
1

My question is,

  1. Since return value of test() is 0, i,e un-incremented, so when i print i why it is incremented. What i know is, return is the exit point of method but from this method i found that there is something happening after returning from method.

So how exactly return works?

like image 604
Gaurav Gupta Avatar asked Nov 21 '25 11:11

Gaurav Gupta


1 Answers

Simple.

When you do return i++ i is initially 0. The i++ is called the post-increment and as its name says i will be incremeneted after.

Although i++ returns a value before incrementing, the method finishes this statement before heading back to main. A return won't abruptly stop this statement halfway(evaluating but not incrementing)

So you'll return 0, increment it, and then see 1 when calling System.out.println(t.i);.


Technically, the value of i is stored onto the stack, the class field is incremented, and then the copied-out values of i is returned.

like image 134
nanofarad Avatar answered Nov 23 '25 23:11

nanofarad



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!