Return value from function

How does returning a function internally work?

See this example ..

alt text

+7
java function stack return return-value
source share
2 answers

The JVM uses a value stack to store values, and the stack is used for all method calls in this thread. Usually, when a non-void method is returned, the return value is pushed onto the stack, and the caller pushes it from the stack and either uses it or discards it.

+7
source share

JLS 14.17 return

[...] The return without expression attempts to transfer control to the calling method or constructor containing it.

[...] The return with an expression tries to transfer control to the calling method that contains it; the value of the expression becomes the value of the method call.

[...] Thus, it can be seen that the return statement always terminates abruptly.

Abrupt completion means that any of the following statements will not be executed, and in some cases this can lead to a compile-time error ( JLS 14.21 Unreachable reports )

 void unreachable() { return; System.out.println("Bye!"); // DOESN'T COMPILE! Unreachable code! } 

To be continued ...

The previous descriptions say “ attempts to transfer control”, and not just “transfers control”, because if there are any try [...] instructions, then any finally [...] sentences will be executed [...] completing the finally clause may disrupt the control transfer initiated by the return .

This means that the next function will be return -1 instead of 0 .

 int tryReturn() { try { return 0; } finally { return -1; } } 

If there is no try-finally , the control will be immediately transferred, and the Expression value, if any, will be passed to the caller.

+2
source share

All Articles