¿Qué hace la palabra clave return en un método void en Java?


Estoy mirando un tutorial de búsqueda de rutas y noté una instrucción return dentro de un método void (clase PathTest, línea 126):

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

Soy un novato en Java. ¿Alguien puede decirme por qué está ahí? Por lo que yo sabía, return dentro de un método vacío no está permitido.

Author: Boann, 2009-04-13

7 answers

Simplemente sale del método en ese punto. Una vez que se ejecuta return, el resto del código no se ejecutará.

Eg.

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

Tenga en cuenta que el compilador es lo suficientemente inteligente como para decirle que no se puede alcanzar algún código:

if (n == 3) {
    return;
    youWillGetAnError(); //compiler error here
}
 102
Author: CookieOfFortune,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-29 20:21:48

Puedes tener return en un método void, simplemente no puedes devolver ningún valor (como en return 5;), por eso lo llaman un método void. Algunas personas siempre terminan explícitamente los métodos void con una declaración return, pero no es obligatorio. se puede usar para dejar una función antes, aunque:

void someFunct(int arg)
{
    if (arg == 0)
    {
        //Leave because this is a bad value
        return;
    }
    //Otherwise, do something
}
 23
Author: Pesto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-22 11:07:56

La palabra clave simplemente saca un frame de la pila de llamadas devolviendo el control a la línea que sigue a la llamada a la función.

 15
Author: MahdeTo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-13 17:36:00

La especificación del lenguaje Java dice que puede tener return sin expresión si su método devuelve void.

 12
Author: John Ellinwood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-13 17:32:53

Funciona igual que una función return for con un parámetro especificado, excepto que no devuelve nada, ya que no hay nada que devolver y el control se devuelve al método que llama.

 2
Author: Chris Ballance,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-13 17:33:16

Sale de la función y no devuelve nada.

Algo como return 1; sería incorrecto ya que devuelve el entero 1.

 2
Author: Albert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-04-13 17:33:48

Vea este ejemplo, desea agregar a la lista condicionalmente. Sin la palabra "return", todos los ifs se ejecutarán y se añadirán a la 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
Author: iali87,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-20 12:25:58