Java – return statement in void method
I have the following method to return void. I need to use it in another method that also returns void
@H_ 403_ 9@
@H_ 403_ 9@
public void doSomething(){}
public void myMethod()
{
    return doSomething();
}
Thank you for all your comments, but let me be more specific @ H_ 403_ 9@
If something happens, I only do something, otherwise I do something else @ H_ 403_ 9@
@H_ 403_ 9@
public void doSomething(){}
public void myMethod()
{
    for(...)
        if(somethingHappens)
        {
            doSomething();
            return;
        }
    doOtherStuff();
}
Instead of the above code, I can only write return dosomething(); In the if statement@ H_ 403_ 9@ @H_ 301_ 4@
resolvent
Solution
No, just do this:
@H_ 403_ 9@
@H_ 403_ 9@
public void doSomething() { }
public void myMethod()
{
    doSomething();
}
Or in the second case: @ h_ 403_ 9@
@H_ 403_ 9@
public void doSomething() { }
public void myMethod()
{
    // ...
    if (somethingHappens)
    {
        doSomething();
        return;
    }
    // ...
}
"Invalid return" means nothing is returned If you want to "jump out" of the body of mymethod, please use return; The compiler does not allow writing to return void; ("illegal start expression") or return dosomething(); ("cannot return a value from a method with result type void") I understand that it seems logical to return "void" or "void result" of a method call, but such code can be misleading I mean, most programmers have read something like return dosomething(); I think there will be a return@ H_ 403_ 9@ @H_ 301_ 4@ @H_ 301_ 4@
