La sentencia
La sentenciabreakbreaktiene dos formas: etiquetada y sin etiquetar. Hemos visto la forma sin etiquetar en la sección anterior en la que se trataba la sentenciaswitch. Tambień podrá utilizar una sentenciabreaksin etiquetar para terminar un buclefor,whileodo-while, como se muestra en el siguiente programaBreakDemo:Este programa busca el número 12 en un array. La sentenciaclass 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"); } } }break, en negrita, termina el bucleforcuando 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:Una sentenciaEncontrado 12 en el índice 4breaksin etiquetar termina la sentenciaswitch,for,whileodo-whilemás interna, pero unbreaketiquetado termina una sentencia externa. El siguiente programa,BreakWithLabelDemo, es parecido al programa anterior pero utiliza buclesforanidados para buscar un valor en un array de dos dimensiones. Unbreaketiquetado (como «search») termina el bucleforexterno 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, 0La sentenciabreaktermina 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
La sentenciacontinuecontinuese salta la iteración actual de un buclefor,whileodo-while. La forma sin etiquetar salta al final del cuerpo del bucle más interno y evalúa la expresiónbooleanaque lo controla. El siguiente programa,ContinueDemo, recorre unStringcontando las veces que aparece la letra «p». Si el carácter actual no es una «p» la sentenciacontinuese salta el resto del bucle y sigue con el siguiente carácter. Si es una «p», el programa incrementa la suma de letras.Esta es la salida del programa./* * 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."); } }Compile el mismo programa eliminando la sentenciaEncontradas 9 p's en la cadena.continuepara 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
continueetiquetada 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.
EncontradoLa sentencia
La última de las sentencias de ramificación esreturnreturn. La sentenciareturnsale del método actual y devuelve el control de flujo a donde se había invocado el método. La sentenciareturntiene 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 clavereturn.El tipo de dato devuelto debe coincidir con el tipo del valor de retorno declarado por el método. Cuando declare un método comoreturn ++count;void, utilice la forma dereturnque no devuelva un valor.La lección Clases y objetos cubrirá todo lo que necesite saber acerca de la creación de métodos.return;
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é: