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

I am looking at a path-finding tutorial , and I noticed a return inside the void method ( PathTest class, line 126):

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

I am new to Java. Can someone tell me why this is there? As far as I know, return inside the void method is not allowed.

+48
java methods return void
Apr 13 '09 at 17:27
source share
7 answers

It just exits the method at this point. After return executed, the rest of the code will not 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 that code cannot be reached:

 if (n == 3) { return; youWillGetAnError(); //compiler error here } 
+93
Apr 13 '09 at 17:30
source share

You may have return in the void method, you simply cannot return any value (as in return 5; ), so they call it the void method. Some people always explicitly close invalid methods with the return statement, but this is not necessary. It can be used to leave the function earlier, but:

 void someFunct(int arg) { if (arg == 0) { //Leave because this is a bad value return; } //Otherwise, do something } 
+22
Apr 13 '09 at 17:32
source share

The keyword simply pops the frame out of the call stack, returning the control to the line following the function call.

+14
Apr 13 '09 at 17:36
source share

The Java language specification says that you can return without an expression if your method returns void.

+12
Apr 13 '09 at 17:32
source share

It functions in the same way as returning for a function with the specified parameter, except that it does not return anything, since there is nothing to return and control is transferred back to the calling method.

+2
Apr 13 '09 at 17:33
source share

It exits the function and returns nothing.

Something like return 1; would be wrong, since it returns an integer.

+2
Apr 13 '09 at 17:33
source share

See this example, which you want to add to the list conditionally. Without the word "return", all ifs will be executed and added 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; } } 
+1
Nov 26 '15 at 3:53 on
source share



All Articles