NOTA: La traducción de esta documentación es un esfuerzo personal y voluntario, no es un documento oficial de Sun Microsystems ni Oracle ni está patrocinado por ninguna de estas empresas. Los documentos originales (en inglés) están disponibles en: http://java.sun.com/docs/books/tutorial/.
Dirija cualquier comentario, petición, felicitación, etc. a tutorialesjava_@RROBA_codexion.com.
Si desea ayudar a mantener en funcionamiento esta web, colaborar con la traducción de estos documentos o necesita que se traduzca algĂșn capĂ­tulo en concreto puede realizar una donación directa mediante Paypal:
La sentencia for (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
La sentencia for
Página inicial > El lenguaje Java > Lo básico del lenguaje
La sentencia for
La sentencia for proporciona una forma compacta de recorrer un rango de valores. Los programadores a menudo se refieren a ella como el «bucle for» por la forma en la que recorre su bloque hasta que se satisfaga la condición indicada. La forma general de la sentencia for se puede expresar del siguiente modo:
for (inicialización; terminación; incremento) {
    sentencia(s)
}
 
Al usar esta versión de la sentencia for tenga en cuenta que:

El siguiente programa, ForDemo, utiliza la forma general de la sentencia for para mostrar los números del 1 al 10 en la salida estándar:

/*
 * 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 ForDemo {
     public static void main(String[] args){
          for(int i=1; i<11; i++){
               System.out.println("Número: " + i);
          }
     }
}
 
La salida de este programa es:
Número: 1
Número: 2
Número: 3
Número: 4
Número: 5
Número: 6
Número: 7
Número: 8
Número: 9
Número: 10
 
Fíjese en cómo el código declara una variable dentro de la expresión de inicialización. El ámbito de esta variable se extiende desde su declaración hasta el final del bloque perteneciente a la sentencia for, por lo tanto también se puede usar en las expresiones de terminación e incremento. Es mejor declarar la variable que controla una sentencia for en la expresión de inicialización si ésta no es necesaria fuera del bucle. A menudo se utilizan los nombres i, j y k para controlar los bucles for; al declararlas dentro de la expresión de inicialización se limita su tiempo de vida y se reduce la posibilidad de error.

Las tres expresiones del bucle for son opcionales; se puede crear un bucle inifinto del siguiente modo:

for ( ; ; ) {    // bucle infinito
    
     // el código va aquí
}

La sentencia for también tiene otra forma diseñada para la iteración a través de Colecciones y arrays. A esta forma a veces se la denomina for mejorado («enhanced for») y se puede utilizar para compactar más sus bucles y facilitar su lectura. Como ejemplo, fíjese en el siguiente array, que contiene los números del 1 al 10:

int[] numeros = {1,2,3,4,5,6,7,8,9,10};

El siguiente programa, EnhancedForDemo, utiliza el bucle for mejorado para recorrer el array:

/*
 * 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 EnhancedForDemo {
     public static void main(String[] args){
          int[] numeros = {1,2,3,4,5,6,7,8,9,10};
          for (int elemento : numeros) {
            System.out.println("Número: " + elemento);
          }
     }
}
 
En este ejemplo la variable elemento contiene el valor actual del array «numeros». La salida de este programa es igual a la anterior:
Número: 1
Número: 2
Número: 3
Número: 4
Número: 5
Número: 6
Número: 7
Número: 8
Número: 9
Número: 10
 
Se recomienda el uso de esta forma de la sentencia for en vez de la forma general siempre que sea posible.
Pagina anterior: Las sentencias while y do-while
Página siguiente: Sentencias de ramificación