Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.11. The for statement

3.11. The for statement
Last updated: 23 January 2013.

The for statement allows you to repeat the execution of the same statements a given number of times. For example, if you want to print 5 times "Hello World" to the standard output, a for statement is the solution. A for statement uses an iterator variable to control the repetition of the statements (the loops) it has to execute. Here is the syntax of the for statement:

for ( <initialization> ; <repetition condition> ; <incrementation>){

   
// the statements that are to be executed repeatedly go here

}

Syntax explanation:
Create a class named JavaLoops and a method named forLoop as shown below. The method forLoop prints 5 times "Hello World" to the standard output:

public class JavaLoops {

   
public void forLoop(){

         
final int MAX_LOOPS = 5;
         
int i;

         
for(i=0; i<MAX_LOOPS; ++i){
               
System.out.println("Hello World");
         
}
    }

}

Let's take a closer look at the for statement:

Create a class named App and call the method forLoop:

public class App {

   
public static void main(String[] args) {

         
new JavaLoops().forLoop();

   
}

}

The output is:

Hello World
Hello World
Hello World
Hello World
Hello World

The Java language allows you to declare the iterator variable i within the for statement:

public class JavaLoops {

   
public void forLoop(){

         
final int MAX_LOOPS = 5;

         
for(int i=0; i<MAX_LOOPS; ++i){
               
System.out.println("Hello World");
         
}
    }

}

To take another example, the method forLoop2 shown below declares and initializes an array of characters and prints all of its elements to the standard output:

public class JavaLoops {

   
public void forLoop2(){

         
char[] myArray = { 'a', 'b', 'c', 'd', 'e' };

         
for(int i=0; i<myArray.length; ++i){
               
System.out.println(myArray[i]);
         
}
    }

}

The output is:

a
b
c
d
e


You are here :  JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.11. The for statement
Next tutorial :  JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.12. The for-each statement

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7