Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...