I have the following method that returns void and I need to use it in another method that also returns void.
Can I do the following?
public void doSomething(){}
public void myMethod()
{
return doSomething();
}
Thanks for all your comments, but let me be more specific
I only doSomething if something happens, otherwise I do other things
public void doSomething(){}
public void myMethod()
{
for(...)
if(somethingHappens)
{
doSomething();
return;
}
doOtherStuff();
}
Instead of the code above, can I just write return doSomething(); inside the if statement?
No, just do this:
or in the second case:
“Returning void” means returning nothing. If you would like to “jump” out of
myMethod‘s body, usereturn;The compiler does not allow writingreturn void;(“illegal start of expression”) orreturn doSomething();(“cannot return a value from method whose result type is void”). I understand it seems logical to return “void” or the “void result” of a method call, but such a code would be misleading. I mean most programmers who read something likereturn doSomething();would think there is something to return.