Java for loop
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: | 5431 |
Bookmark Java for loop
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.
- The initialisation part is executed only once when the loop begins. This part usually sets the loop counter to a default value.
- The termination is an expression which is evaluated before the loop body is executed. If it is false then the loop ends.
- The increment part is executed after every run of the loop body. Here can be the loop counter incremented.
For loop example:
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:
The i is: 0
The i is: 1
The i is: 2
The i is: 3
The i is: 4
The i is: 5
The i is: 6
The i is: 7
The i is: 8
The i is: 9
You can have multiple expressions in the initialisation and incrementation block. For example you can use the following code:
for (int i=0, j=10; i<10; i++, j-- ) {
System.out.println("The i is: " + i + " and j is: " + j);
}
This code generates the following output:
The i is: 0 and j is: 10
The i is: 1 and j is: 9
The i is: 2 and j is: 8
The i is: 3 and j is: 7
The i is: 4 and j is: 6
The i is: 5 and j is: 5
The i is: 6 and j is: 4
The i is: 7 and j is: 3
The i is: 8 and j is: 2
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:
String[] myColors = {"White", "Green", "Blue", "Yellow", "Black"};
for (int i=0; i < myColors.length; i++) {
System.out.println("Color is: " + myColors[i]);
}
The output is:
You can also create a for loop with an Iterator as in this example:
Set mySet = new HashSet();
mySet.add("White");
mySet.add("Green");
mySet.add("Blue");
mySet.add("Yellow");
mySet.add("Black");
for (Iterator iter = mySet.iterator(); iter.hasNext();) {
String element = (String) iter.next();
System.out.println("Color is: " + element);
}
Tags: java for loop, for loop, java for, java, for, loop
| Java for loop - Table of contents |
|---|
| Step 1 - Using for loop in Java |