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,
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?
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.
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