Al contrario deif-theneif-then-else, la sentenciaswitchpermite cualquier cantidad de rutas de ejecución posibles.. Unswitchfunciona con los datos primitivosbyte,short,chareint. También funciona con tipos enumerados (tratados en Clases y herencia) y con unas cuantas clases especiales que «envuelven» a ciertos tipos primitivos:Character,Byte,Short, andInteger(tratado en Clases y objetos ).El siguiente programa,
SwitchDemo, declara unintllamadomonthcuyo valor representa un mes del año. El programa muestra el nombre del mes, basado en el valor de «month», mediante la sentenciaswitch./* * 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 SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System.out.println("Enero"); break; case 2: System.out.println("Febrero"); break; case 3: System.out.println("Marzo"); break; case 4: System.out.println("Abril"); break; case 5: System.out.println("Mayo"); break; case 6: System.out.println("Junio"); break; case 7: System.out.println("Julio"); break; case 8: System.out.println("Agosto"); break; case 9: System.out.println("Septiembre"); break; case 10: System.out.println("Octubre"); break; case 11: System.out.println("Noviembre"); break; case 12: System.out.println("Diciembre"); break; default: System.out.println("Mes no válido.");break; } } }En este caso se mostrará «Agosto» en la salida estándar.
El cuerpo de una sentencia
switchse conoce como el bloque switch. Cualquier sentencia contenida directamente por el bloqueswitchpuede estar marcada por una o más etiquetascaseodefault. La sentenciaswitchevalúa su expresión y ejecuta el caso (case) adecuado.También es posible, por supuesto, conseguir el mismo resultado con sentencias
if-then-else:La decisión de usar una sentenciaint month = 8; if (month == 1) { System.out.println("Enero"); } else if (month == 2) { System.out.println("Febrero"); } . . . // etcéteraif-then-elseoswitcha menudo es simplemente una cuestión de criterio propio. Podrá decidir cuál usar basándose en la legibilidad y otros factores. Se puede utilizar una sentenciaif-then-elsepara tomar decisiones basadas en rangos de valores o condiciones, mientras que una sentenciaswitchsolamente puede tomar decisiones basadas en un solo valor entero o enumerado.También es interestante la sentencia
breakque va detrás de cadacase. Cada sentenciabreaktermina la sentenciaswitchque la envuelve. El control de flujo continúa con la primera sentencia a continuación del bloqueswitch. Las sentenciasbreakson necesarias porque sin ellas las sentenciascasefallarían, es decir, sin unbreakel flujo del programa seguiría secuencialmente a través de todas las sentenciascase. El siguiente programa,SwitchDemo2, ilustra por qué podría ser útil hacer que una sentenciacasefalle:/* * 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 SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) numDays = 29; else numDays = 28; break; default: System.out.println("Mes no válido."); break; } System.out.println("Número de días = " + numDays); } }Esta es la salida del programa.
Número de días = 29Técnicamente el último
breakno es necesario ya que el flujo se saldría de la sentenciaswitchde todos modos. Sin embargo recomendamos usar unbreakpara evitar errores al modificar el código. La seccióndefaultgestiona los valores que no sean tratados explícitamente por una de las seccionescase.
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é: