Java return Statement - Quiz

Total: 5 questions

1. 

What does the return statement do in Java?

It ends the execution of the current method and returns control to the caller. Any statements placed after return in the same block are not executed, and the program continues from the point where the method was called. If the method has a return type, return also passes a value back to the caller.

2. 

What are the two forms of the return statement and where is each used?

return; ends the method without returning a value and is used in void methods (and constructors) for an early exit. return expression; ends the method and returns the value of the expression; it is used in methods that declare a return type other than void. In both forms the method stops immediately.

3. 

Is the return statement required in a void method?

No. A void method does not return a value, so return is optional — the method ends on its own after its last statement. However, return; (without a value) is useful for leaving a method early, for example to validate input at the top of a method: if the data is invalid, the method returns right away and the main logic is skipped.

4. 

What is the difference between return and break?

break terminates only the nearest loop or switch statement, after which the method keeps running. return terminates the entire method: if it is called inside a loop, it ends both the loop and the method at once.

5. 

What does the compile-time error "missing return statement" mean?

It means the method is declared with a return type, but there is an execution path that does not end in a return statement. The most frequent cause is an if without an else branch: the compiler cannot guarantee the condition is true, so it demands a return for the case when the condition is false. Every possible path must end in a return (or throw an exception).

Page 1 of 1