This is a question from a Java course at the college I attend. My teacher says the answer is D - "The program terminates", but I think the answer is C - "Control is returned to method C".
What's the correct answer, and why?
If method A calls method B, and method B calls method C, and method C calls method D, when method D finishes, what happens?
A. Control is returned to method A
B. Control is returned to method B
C. Control is returned to method C
D. The program terminates
Yes, it will end the method once a value is returned.
exit() method calls the exit method in class Runtime. It exits the current program by terminating Java Virtual Machine.
Definition and Usage. The return keyword finished the execution of a method, and can be used to return a value from a method.
You can end a Java program by using the “exit()” method of the Java “System” class. It terminates the currently running JVM. Here, the System. exit() method has a parameter 0, which indicates that the program will terminate without any error.
Answer is c, unless method D causes program to terminate, then the answer is d.
The behavior of a method call is well-defined in the definition of invokevirtual
opcode (operation code). From Java Virtual Machine Online Instruction Reference:
invokevirtual
dispatches a Java method. It is used in Java to invoke all methods except interface methods (which useinvokeinterface
), static methods (which useinvokestatic
), and the few special cases handled byinvokespecial
.For example, when you write in Java:
Object x; ... x.equals("hello");
this is compiled into something like:
aload_1 ; push local variable 1 (i.e. 'x') onto stack ldc "hello" ; push the string "hello" onto stack ; invoke the equals method invokevirtual java/lang/Object/equals(Ljava/lang/Object;)Z ; the boolean result is now on the stack
Once a method has been located, invokevirtual calls the method. (...) When the method called by invokevirtual returns, any single (or double) word return result is placed on the operand stack of the current method and execution continues at the instruction that follows invokevirtual in the bytecode.
the only way to terminate (barring an Abnormal Termination) is for execution chain to complete. Your answer makes sense to me.
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