views:

175

answers:

5

Is there any difference between explicitly returning at the end of doGet or doPost-methods, and just letting the method return "by itself"?

public void doGet(HttpSerlvetRequest req, HttpServletResponse resp) {
    <my code here>
    return;
}

public void doGet(HttpSerlvetRequest req, HttpServletResponse resp) {
    <my code here>
}
+3  A: 

No. As a regular void method, it does not require a return

Bozho
A: 

There is no difference at all, a return is implicit at the end of a method.

Alexander Reifinger
Its only implicit for a `void` method.
Stephen C
A: 

No difference at all, the return statement is unnecessary.

Jim Ferrans
+2  A: 

Utterly unnecessary; doesn't add any style points, either.

mfx
A: 

There are however cases where you see the return statement in a servlet method which might be at first glance confusing for starters. Here's an example:

protected void doPost(request, response) {
    if (someCondition) {
        response.sendRedirect("page");
        return;
    }
    doSomethingElse();
    request.getRequestDispatcher("page").forward(request, response);
}

Here the return statement is necessary because calling a redirect (or forward) does not cause the code to magically jump out of the method block as some starters seem to think. It still continues to run until the end which would cause an IllegalStateException: response already committed at the point when the forward is called.

BalusC