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

后端 未结 7 1568
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:13

    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
    }
    
    0 讨论(0)
  • 2020-11-28 22:20

    The keyword simply pops a frame from the call stack returning the control to the line following the function call.

    0 讨论(0)
  • 2020-11-28 22:21

    The Java language specification says you can have return with no expression if your method returns void.

    0 讨论(0)
  • 2020-11-28 22:22

    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;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 22:24

    It functions the same as a return for function with a specified parameter, except it returns nothing, as there is nothing to return and control is passed back to the calling method.

    0 讨论(0)
  • 2020-11-28 22:25

    It exits the function and returns nothing.

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

    0 讨论(0)
提交回复
热议问题