Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the program terminate after a called method finishes, or does it return control to the calling function?

Tags:

java

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

like image 333
Chris Albert Avatar asked Mar 07 '14 21:03

Chris Albert


People also ask

Does a return statement end a method?

Yes, it will end the method once a value is returned.

Which method terminates the program?

exit() method calls the exit method in class Runtime. It exits the current program by terminating Java Virtual Machine.

Does return end a method Java?

Definition and Usage. The return keyword finished the execution of a method, and can be used to return a value from a method.

How do you terminate a program in Java?

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.


2 Answers

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 use invokeinterface), static methods (which use invokestatic), and the few special cases handled by invokespecial.

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.

like image 81
Adam Stelmaszczyk Avatar answered Oct 23 '22 23:10

Adam Stelmaszczyk


the only way to terminate (barring an Abnormal Termination) is for execution chain to complete. Your answer makes sense to me.

like image 43
T McKeown Avatar answered Oct 23 '22 23:10

T McKeown