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

8

86

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.

Latten answered 13/4, 2009 at 17:27 Comment(0)
B
154

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
}
Bootjack answered 13/4, 2009 at 17:30 Comment(4)
I understand your code is illustrative, but for the parent's info; I've worked with people that believe each method should only have a single return statement. I'm not one of them, but do believe in minimizing the number of returns as much as possible without making the code ugly in doing it.Precipitation
Yeah, it's definitely not something to overuse, but sometimes it just makes it a lot easier and can still be very readable.Bootjack
My favorite way of breaking from nested loops :)Viewy
Without a return value return works a lot like break in a loop and simply exits the code in question. There have been many flame wars about multiple exit points from functions and a few languages force you one way or the other. I don't take a position on multiple exit points, but I will point out that leaving a function cleans up the local stack.Kathline
D
32

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
}
Diaz answered 13/4, 2009 at 17:32 Comment(2)
Why can't we use break instead?Monometallism
@Monometallism break only works inside a loop. There is no loop here.Halley
H
29

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

Hatband answered 13/4, 2009 at 17:36 Comment(3)
Haha. This is great answer but I doubt beginners in java would really grasp what you're trying to say.Grimy
@ElliotMok Fair enough. We all start out as beginners!Grimy
Is this a good practice or doesn't matter whether we write return; or not?Astraddle
L
15

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

Larvicide answered 13/4, 2009 at 17:32 Comment(0)
S
5

It exits the function and returns nothing.

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

Supreme answered 13/4, 2009 at 17:33 Comment(0)
S
3

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.

Surpassing answered 13/4, 2009 at 17:33 Comment(0)
D
3

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;
    }
}
Defraud answered 26/11, 2015 at 3:53 Comment(1)
The ArrayList should have been initialized as: ArrayList<String> list = new ArrayList<>();Enlighten
D
0

void methodName() {

// body }

} ``

} The return statement should not be present within a void method, as a return value cannot be specified.

Discussant answered 19/5, 2023 at 9:29 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Referent

© 2022 - 2025 — McMap. All rights reserved.