What does the return keyword do in a void method in Java?

后端 未结 7 1569
Happy的楠姐
Happy的楠姐 2020-11-28 21:34

I\'m looking at a path finding tutorial and I noticed a return statement inside a void method (class PathTest, line 126):



        
相关标签:
7条回答
  • 2020-11-28 22:34

    You can have return in a void method, you just can't return any value (as in return 5;), that's why they call it a void method. Some people always explicitly end void methods with a return statement, but it's not mandatory. It can be used to leave a function early, though:

    void someFunct(int arg)
    {
        if (arg == 0)
        {
            //Leave because this is a bad value
            return;
        }
        //Otherwise, do something
    }
    
    0 讨论(0)
提交回复
热议问题