Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+19 votes

What would happen if I call a method that has two return statements? Only one could be returned, correct?

asked in CSC211_Winter2018 by (8 points)
edited by

1 Answer

+15 votes

This question is kind of vague, but if I'm interpreting it correctly, it would not be possible to have two return statements on the same path in the same method. The method would return the first value and then immediately return back to the method which called it, leaving the second return statement unreachable. In fact, if you try this in your own code, it will throw an Unresolved compilation problem: Unreachable code error at you.

The bottom line is that each path in a method should either return exactly one item (if your method is not returning type void), or nothing (if it is returning type void).

answered by (462 points)
+2

It is, however, possible to have multiple return statements IF you are using some sort of loop to determine which statement is returned. This can be tricky, however, as you must be careful to insure each possible path has a return statement. You also would need to factor in that once a variable is returned the loop will end and it will return back to the method that called it.

...