Java for keyword examples
- Details
- Written by Nam Ha Minh
- Last Updated on 19 August 2019   |   Print Email
In Java, the for keyword is used to iterate over a range of values, items of an array or a collection. The code that uses for keyword is called as for loop.
In Java, there are two types of for loop: classic for loop and enhanced for loop (for-each).
1. Java Classic for loop
Syntax of the classic for loop is as follows:
for (initialization; terminate condition; incrementation) {
// statements
}
where:
- initialization: contains code that initializes the loop, usually by declaring a counter variable. This code is executed only once.
- terminate condition: contains code that checks for a condition to terminate the loop. This code is executed every iteration, if the codition is met, the loop is terminated.
- incrementation: contains code that increments value of the counter variable. This code is executed every iteration.
The following code example iterates over a range of integer numbers from 0 to 9 and output the current number to the standard output:
for (int i = 0; i < 10; i++) { System.out.println("Number: " + i); }
2. Java Enhanced for loop
The enhanced for loop (also known as for-each) has been introduced since Java 5.
This kind of for statement is a convenient way to iterate over an arry or a collection. Syntax of enhanced for loop is as follows:
for (T var : collection<T> or T[] array) {
// statements
}
where T is actual type of the array or collection, and var is name of the variable refers to the current item in the collection or array. The following code example uses enhanced for loop to iterate over an array of integers:
for (int number : nums) { System.out.println("Number: " + number); }
And the following code iterates over an collection of Strings:
Collection<String> names = new ArrayList<String>(); names.add("Tom"); names.add("Bill"); names.add("Jack"); for (String name : names) { System.out.println("Name: " + name); }
See all keywords in Java.
Related Topics:
- Java do-while construct
- Java break keyword
- The 4 Methods for Iterating Collections in Java
- Some notes about execution control statements in Java
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments