Java for loop


Home - Tutorials - Basics

Examples and details of Java for loop usage are covered in this article. You can learn every details about how to use for loops in Java.

Tutorial info:


Name:Java for loop
Total steps:1
Category:Basics
Date:2011-04-14
Level:Beginner
Product:See complete product
Viewed:10577

Bookmark Java for loop



AddThis Social Bookmark Button

Step 1 - Using for loop in Java


Java for loop

One of the most commonly used control flow statement is the for loop in programming languages. You can use it to iterate over a list of values. 

The for loop syntax:

for (initialization; termination; increment) {

    statement(s)

}

Now let’s see an explanation to the syntax. 

 

 

For loop example: 

Code:
  1. for (int i=0; i<10; i++ ) {
  2.     System.out.println("The i is: " + i);
  3. }

Here the initialisation part creates and sets a new int variable and the termination part checks if the actual value of the i is smaller than 10 and at the end the increment part always increments the value of i by one after every println() call.

The above example results the following output: 

Code:
  1. The i is: 0
  2. The i is: 1
  3. The i is: 2
  4. The i is: 3
  5. The i is: 4
  6. The i is: 5
  7. The i is: 6
  8. The i is: 7
  9. The i is: 8
  10. The i is: 9

You can have multiple expressions in the initialisation and incrementation block. For example you can use the following code:

Code:
  1. for (int i=0, j=10; i<10; i++, j-- ) {
  2.     System.out.println("The i is: " + i + " and j is: " + j);
  3. }

This code generates the following output:

Code:
  1. The i is: 0 and j is: 10
  2. The i is: 1 and j is: 9
  3. The i is: 2 and j is: 8
  4. The i is: 3 and j is: 7
  5. The i is: 4 and j is: 6
  6. The i is: 5 and j is: 5
  7. The i is: 6 and j is: 4
  8. The i is: 7 and j is: 3
  9. The i is: 8 and j is: 2
  10. The i is: 9 and j is: 1

If you want to iterate over an array with for loop you can use the code like this:

Code:
  1. String[] myColors = {"White", "Green", "Blue", "Yellow", "Black"};
  2. for (int i=0; i < myColors.length; i++) {
  3. 	System.out.println("Color is: " + myColors[i]);
  4. }

The output is:

Code:
  1. Color is: White
  2. Color is: Green
  3. Color is: Blue
  4. Color is: Yellow
  5. Color is: Black

You can also create a for loop with an Iterator as in this example:

Code:
  1. Set mySet = new HashSet();
  2.  
  3. mySet.add("White");
  4. mySet.add("Green");
  5. mySet.add("Blue");
  6. mySet.add("Yellow");
  7. mySet.add("Black");
  8.  
  9. for (Iterator iter = mySet.iterator(); iter.hasNext();) {
  10. 	String element = (String) iter.next();
  11. 	System.out.println("Color is: " + element);
  12. }






Tags: java for loop, for loop, java for, java, for, loop

Java for loop - Table of contents
Step 1 - Using for loop in Java



Total time: 0.18