简体   繁体   中英

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

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

if ((x < 0) || (y < 0) || (x >= map.getWidthInTiles()) || (y >= map.getHeightInTiles())) {
    return;
}

I'm a novice at Java. Can anyone tell me why it's there? As far as I knew, return inside a void method isn't allowed.

It just exits the method at that point. Once return is executed, the rest of the code won't be executed.

eg.

public void test(int n) {
    if (n == 1) {
        return; 
    }
    else if (n == 2) {
        doStuff();
        return;
    }
    doOtherStuff();
}

Note that the compiler is smart enough to tell you some code cannot be reached:

if (n == 3) {
    return;
    youWillGetAnError(); //compiler error here
}

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
}

关键字只是从调用堆栈中弹出一个帧,将控件返回到函数调用之后的行。

Java语言规范说如果方法返回void,则可以返回没有表达式。

它的功能与带有指定参数的函数返回相同,但它不返回任何内容,因为没有任何内容可以返回,并且控制权被传递回调用方法。

It exits the function and returns nothing.

Something like return 1; would be incorrect since it returns integer 1.

See this example, you want to add to the list conditionally. Without the word "return", all ifs will be executed and add to the ArrayList!

    Arraylist<String> list =  new ArrayList<>();

    public void addingToTheList() {

    if(isSunday()) {
        list.add("Pray today")
        return;
    }

    if(isMonday()) {
        list.add("Work today"
        return;
    }

    if(isTuesday()) {
        list.add("Tr today")
        return;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM