Sentencias de ramificación (Los tutoriales Java™ > El lenguaje Java > Lo básico del lenguaje)
Ruta: El lenguaje Java
Lección: Lo básico del lenguaje
Sección: Sentencias de control de flujo
Sentencias de ramificación
Página inicial > El lenguaje Java > Lo básico del lenguaje
Sentencias de ramificación

La sentencia break

La sentencia break tiene dos formas: etiquetada y sin etiquetar. Hemos visto la forma sin etiquetar en la sección anterior en la que se trataba la sentencia switch. Tambień podrá utilizar una sentencia break sin etiquetar para terminar un bucle for, while o do-while, como se muestra en el siguiente programa BreakDemo:
class BreakDemo {
    public static void main(String[] args) {

        int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,
                              2000, 8, 622, 127 };
        int searchfor = 12;

        int i;
        boolean foundIt = false;

        for (i = 0; i < arrayOfInts.length; i++) {
            if (arrayOfInts[i] == searchfor) {
                foundIt = true;
                break;
            }
        }

        if (foundIt) {
            System.out.println("Encontrado " + searchfor
                               + " en el índice " + i);
        } else {
            System.out.println(searchfor
                               + " no está en el array");
        }
    }
}
 
Este programa busca el número 12 en un array. La sentencia break, en negrita, termina el bucle for cuando se encuentra el valor. En ese momento del control de flujo se transfiere a la sentencia «print» al final del programa. La salida de este programa es:
Encontrado 12 en el índice 4
 
Una sentencia break sin etiquetar termina la sentencia switch, for, while o do-while más interna, pero un break etiquetado termina una sentencia externa. El siguiente programa, BreakWithLabelDemo, es parecido al programa anterior pero utiliza bucles for anidados para buscar un valor en un array de dos dimensiones. Un break etiquetado (como «search») termina el bucle for externo cuando se encuentra el valor:
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

class BreakWithLabelDemo {
    public static void main(String[] args) {

        int[][] arrayOfInts = { { 32, 87, 3, 589 },
                                { 12, 1076, 2000, 8 },
                                { 622, 127, 77, 955 }
                              };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length; j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Encontrado " + searchfor +
                               " en " + i + ", " + j);
        } else {
            System.out.println(searchfor
                               + " no está en el array");
        }
    }
}

Esta es la salida del programa.

Encontrado 12 en 1, 0
 
La sentencia break termina la sentencia etiquetada; no transfiere el control de flujo a la etiqueta. El control de flujo se transfiere a la sentencia inmediatamente posterior a la sentencia etiquetada (terminada).

La sentencia continue

La sentencia continue se salta la iteración actual de un bucle for, while o do-while. La forma sin etiquetar salta al final del cuerpo del bucle más interno y evalúa la expresión booleana que lo controla. El siguiente programa, ContinueDemo, recorre un String contando las veces que aparece la letra «p». Si el carácter actual no es una «p» la sentencia continue se salta el resto del bucle y sigue con el siguiente carácter. Si es una «p», el programa incrementa la suma de letras.
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

class ContinueDemo {
    public static void main(String[] args) {

        String searchMe = "peter piper picked a peck of pickled peppers";
        int max = searchMe.length();
        int numPs = 0;

        for (int i = 0; i < max; i++) {
            //interested only in p's
            if (searchMe.charAt(i) != 'p')
                continue;

            //process p's
            numPs++;
        }
        System.out.println("Encontradas " + numPs + " p's en la cadena.");
    }
}
 
Esta es la salida del programa.
Encontradas 9 p's en la cadena.
 
Compile el mismo programa eliminando la sentencia continue para ver el efecto más claramente. Cuando vuelva a ejecutarlo el contador estará equivocado, indicando que ha encontrado 35 p's en lugar de 9.

Una sentencia continue etiquetada se salta la iteración actual de un bucle exterior marcado con la etiqueta indicada. El siguiente programa, ContinueWithLabelDemo, utiliza bucles anidados para buscar una subcadena dentro de otra cadena. Se necesitan dos bucles anidados: uno que recorra la subcadena y otro que recorra la cadena principal. El siguiente programa, ContinueWithLabelDemo, utiliza la forma etiquetada de «continue» para saltarse una iteración del bucle exterior.

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

class ContinueWithLabelDemo {
    public static void main(String[] args) {

        String searchMe = "Look for a substring in me";
        String substring = "sub";
        boolean foundIt = false;

        int max = searchMe.length() - substring.length();

    test:
        for (int i = 0; i <= max; i++) {
            int n = substring.length();
            int j = i;
            int k = 0;
            while (n-- != 0) {
                if (searchMe.charAt(j++)
                        != substring.charAt(k++)) {
                    continue test;
                }
            }
            foundIt = true;
                 break test;
        }
        System.out.println(foundIt ? "Encontrado" :
                                     "No lo encontré");
    }
}

Esta es la salida del programa.

Encontrado

La sentencia return

La última de las sentencias de ramificación es return. La sentencia return sale del método actual y devuelve el control de flujo a donde se había invocado el método. La sentencia return tiene dos formas: una que devuelve un valor y otra que no lo devuelve. Para devolver un valor, simplemente añada el valor (o una expresión que calcule le valor) después de la palabra clave return.
return ++count;
 
El tipo de dato devuelto debe coincidir con el tipo del valor de retorno declarado por el método. Cuando declare un método como void, utilice la forma de return que no devuelva un valor.
return;
 
La lección Clases y objetos cubrirá todo lo que necesite saber acerca de la creación de métodos.
Pagina anterior: La sentencia for
Página siguiente: Resumen de Sentencias de control de flujo

  ATENCIÓN: La traducción de esta documentación es un esfuerzo personal y voluntario. NO es un documento oficial del propietario de la tecnología Java, Oracle, ni está patrocinado por esta empresa.

Los documentos originales y actualizados (en inglés) están disponibles en: http://docs.oracle.com/javase/tutorial/. La versión disponible en este sitio es la publicada en Marzo de 2008 (más información en: "What's new and What's Old? The History of the Tutorial").

Dirige cualquier comentario, petición, felicitación, etc. a tutorialesjava@codexion.com.

Si quieres ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesitas que se traduzca algún capítulo en concreto puedes invitarme a un café: