for keyword in java
The ” for
” keyword specifies a loop which is used to iterate over a range of values, items of an array or a collection In for loop, condition is checked before each iteration and if it returns true then only loop will continue with next iteration.
There are two types of for loop
1) classic/traditional for loop
2) enhanced for loop (for-each)
1) classic/traditional for loop
General Syntax of the classic/traditional for loop is as follows:
- for (initialization; terminate condition; increment/decrement) {
- // code
- }
for (initialization; terminate condition; increment/decrement) { // code }
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 on every iteration and it should evaluate to true, if the condition is false, the loop is terminated.
increment/decrement: contains code that increments/decrements a value of the counter variable. This code is executed on every iteration.
Example:
- for (int i = 1; i <= 100; i++) {
- System.out.println("Number: " + i);
- }
for (int i = 1; i <= 100; i++) { System.out.println("Number: " + i); }
The above code example iterates over a range of integers from 1 to 100 and output each number to the console.
2) Enhanced for loop
The enhanced for loop (also known as for-each) has been introduced since Java 5.
Its frequently used for iterating over an array or a collection.
General Syntax of the enhanced for loop(also called for-each) is as follows:
- for (T var : collection<T> or T[] array) {
- // statements
- }
for (T var : collection<T> or T[] array) { // statements }
where T is the data type of the array or collection, and var is name of the variable refers to the current item in the collection or array.
Example 1
Iterate list of integer numbers using for-each loop as below
- for (int number : numbers) {
- System.out.println("Number: " + number);
- }
for (int number : numbers) { System.out.println("Number: " + number); }
Example 2
Iterate list of String using for-each loop as below
- List<String> hobbies = new ArrayList<String>();
- hobbies.add("playing cricket");
- hobbies.add("listening to music");
- hobbies.add("reading books");
- System.out.println("Hobbies are ");
- for (String hobby : hobbies) {
- System.out.println(hobby);
- }
List<String> hobbies = new ArrayList<String>(); hobbies.add("playing cricket"); hobbies.add("listening to music"); hobbies.add("reading books"); System.out.println("Hobbies are "); for (String hobby : hobbies) { System.out.println(hobby); }