Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

java - Return statement in void method

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, just do this:

public void doSomething() { }

public void myMethod()
{
    doSomething();
}

or in the second case:

public void doSomething() { }

public void myMethod()
{
    // ...
    if (somethingHappens)
    {
        doSomething();
        return;
    }
    // ...
}

"Returning void" means returning nothing. If you would like to "jump" out of myMethod's body, use return; The compiler does not allow writing return void; ("illegal start of expression") or return 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 like return doSomething(); would think there is something to return.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...