We use looping statements in Java to execute the same statement multiple times until it satisfies a certain condition. There are different types of looping statements in Java. In this tutorial, we will understand about Java for
loop.
Table of Contents
What is a For Loop
We use Java for loop to execute a set of statements for a repeated number of times based on a certain condition. Using for loop, we know how many times we need to execute the same set of code. For example, when we want to print numbers from 1 to 100, we can use a single statement within for loop to achieve this.
Syntax of Java For Loop
for(initialization;condition;increment/decrement) { //code }
The syntax of Java for loop contains 4 parts as mentioned below:
- initialization – It declares and initializes the loop variable. This is the first statement that executes in a
for
loop. It ends with a semicolon - condition – This is a boolean expression which it evaluates after initialization of the variable. If the condition returns true, it executes the body of for loop, else the control comes out of the for loop
- body of for loop – When the condition is true after evaluation, it executes the body or set of code inside of for loop.
- increment/decrement – The variable value to increment or decrement. This step executes every time after the code inside for loop is executed
Types of For Loop in Java
There are different types of Java for
loop as mentioned below. The working of for loop is the same for all the types and varies only in the syntax.
- Simple
for
loop - Enhanced
for
loop – for each loop - Nested
for
loop - Labeled
for
loop
Flowchart of For loop
Explanation:
- The first step in the java for loop is initialization and executes only once. It declares and initializes a variable.
- The next step is to evaluate the condition which is a boolean expression. The condition contains the variable which we have initialized in the previous statement. This step controls the entire execution of Java
for
loop. It iterates through thefor
loop as long as the condition is true. If the condition is false, the execution of the for loop stops. - When the condition is true, it executes the body of the
for
loop. - Each time it executes the body, the variable value increments or decrements which is the next step.
- This cycle repeated until the condition or boolean expression returns false.
- The scope of the variables declared inside for loop is within the loop. We cannot access these variables outside the
for
loop.
Simple Java For Loop example
public class SimpleForLoop { public static void main(String[] args) { for(int i=0;i<=10;i=i+2) { System.out.println(i); } } }
0 2 4 6 8 10
This is a simple java program to print even numbers from 0 10 10. Let’s understand in detail step by step.
int i = 0.Here we have declared and initialized the variable i with value 0.
i<=10. This is the condition
i=i+2. It increments i value by 2 in every iteration.
So for the 1st iteration, i value is 0 and hence the condition is true(0<=10). It prints the value 0. Next i value increments by 2 which means i=2(0+2=2). This condition is also true(2<=10) and prints the value 2. Again i value increments by 2 and now i value is 4(2+2=4). This continues until the condition returns false. When i=10, it prints 10, and now i increments by 2 which means i=12. At this stage, 12<=10 condition returns false and exits the for loop.
Example Java For Loop using array
We can use java for loop to print array elements as well as we can see in the below example. To understand the array concept, you can refer to our arrays in java tutorial. Here, the for loop executes starting from array index 0(i=0) until the size of the array(i=6).
public class SimpleForLoop { public static void main(String[] args) { int[] numbers = {45,23,78,12,56,90}; for(int i=0;i<numbers.length;i++) { System.out.println(numbers[i]); } } }
45 23 78 12 56 90
Infinite for loop
When we set a condition that never returns false, the java for loop iterates infinitely and never terminates. Hence it is very important to set the condition or boolean expression right. This may cause out of memory exception.
for(int i=1;i>=1;i++) { System.out.println("Infinite"); }
In this case, it prints the output “Infinite” infinitely and never terminates the execution.
Another method of the infinite for
loop is as below:
for(;;) { System.out.println("Infinite"); }
Enhanced Java For loop
We use enhanced java for
loop to iterate through an array or collection in java. We also call it a for-each loop. In this type, we don’t need to mention any condition or increment/decrement value.
Syntax
datatype[] arrname = {}; for(datatype variable: arrname) { //code }
Example java program using for each loop
public class EnhancedForLoopDemo { public static void main(String[] args) { String[] lang = {"Java","C","C++","PHP","VBScript","Javascript"}; for(String names: lang) { System.out.println(names); } } }
Java C C++ PHP VBScript Javascript
In the above example, we have an array of String values. In the for-each loop, we mention the array data type which is String followed by the variable used within for loop which is names and then a colon (:) followed by array name lang. Inside for loop, we use the variable names to print the array values.
Nested For Loop
When there is a for loop within another for loop, we call it as a nested for loop. When there is more than 1 for loop, the inner loop executes completely for every iteration of the outer for
loop. Let’s understand this with an example below.
Example of simple nested for loop
public class NestedForLoopDemo { public static void main(String[] args) { for(int i=1;i<=3;i++) { for(int j=1;j<=3;j++) { System.out.println("i:"+i+ " " +"j:"+j); } } } }
i:1 j:1 i:1 j:2 i:1 j:3 i:2 j:1 i:2 j:2 i:2 j:3 i:3 j:1 i:3 j:2 i:3 j:3
We have 2 for loops, outer for
loop with variable i, and inner for loop with variable j. The inner for
loop executes completely for every outer for
loop until the condition is false. This means when i=1 for the outer for loop, the inner for
loop executes 3 times i.e j=1,j=2 and j=3. After this, when j=4, condition becomes false(4<=3), hence it exits the inner for loop and starts the 2nd iteration of outer for loop with i=2. This cycle continues until i=3. When i=4, the condition becomes false and it exits the entire for
loop. We can understand this process clearly from the output displayed above.
Example of nested for loop to display pattern
public class NestedForLoopDemo { public static void main(String[] args) { for(int i=1;i<=4;i++) { for(int j=1;j<=i;j++) { System.out.print("* "); } System.out.println(); } } }
* * * * * * * * * *
Labeled For loop
When we use a label or give a name for the java for loop, we call it as labeled for
loop. This is mainly useful in nested for
loop when we want to break or continue the loop execution.
Syntax of labeled for loop
labelname: for(initialization;condition;increment/decrement) { //code }
Labeled for loop with the break statement
When we use break keyword with the outer for loop, it stops the entire execution of for loop.
public class Labeledforloop { public static void main(String[] args) { loop1: for(int i=3;i>=0;i--) { loop2: for(int j=1;j<=3;j++) { System.out.println(i + " " + j); if(i==2 && j ==2) break loop1; } } } }
3 1 3 2 3 3 2 1 2 2
In this example, we have given a name for the outer for loop as loop1 and inner for loop as loop2. When the if condition of inner for loop returns true, it exits the outer for loop, and the entire for loop execution stops. This is why the remaining iteration with i=2 and i=1 is not executed.
Labeled for loop with continue statement
When we use continue keyword with outer for loop, it ignores the remaining iteration of the inner for loop and executes the next iteration in outer for loop.
public class Labeledforloop { public static void main(String[] args) { loop1: for(int i=3;i>=0;i--) { loop2: for(int j=1;j<=3;j++) { if(i==2 && j ==2) continue loop1; System.out.println(i + " " + j); } } } }
3 1 3 2 3 3 2 1 1 1 1 2 1 3 0 1 0 2 0 3
In the above example, we can see that iterations with values i=2,j=2 & i=2,j=3 are not executed. This is because, when i=2 and j=2, we have given continue loop1, which means it stops the inner for loop execution and directly updates the i value(in this case i– which means i=1) and starts execution with i=1 value and continues.
Java for loop with multiple variables
We can also declare and use more than 1 variable in a for loop. But when we use multiple variables in a for loop, we should ensure that all these variables are of the same type. We cannot declare variables of different data types. We use comma(,) as a separator between multiple variables.
Below is an example java program that use 2 variables(i & j) in for loop. We have declared and initialized i and j variables as an integer with values 0 and 1. Then it checks the condition whether i<2 and j<3. It executes the statement inside the for loop as long as this condition is true.
public class MultipleVariables { public static void main(String[] args) { for(int i=0,j=1; i<2 && j<3 ; i++,j++) { System.out.println("i:" + i + "j:" + j); } } }
i:0j:1 i:1j:2
Let’s see another example of multiple variables in a for loop where we don’t update the 2nd variable value. From the output, we can see that, we are not updating the value of j and hence it always remains the same(j=1)
public class MultipleVariables { public static void main(String[] args) { for(int i=1,j=1; i<=3;i++) { System.out.println("i:" + i + "j:" + j); } } }
i:1j:1 i:2j:1 i:3j:1
Reinitializing variables in for loop
If we have initialized a variable outside for loop and try to reinitialize the same variable with different values, it will result in a compilation error. Let’s understand this with an example. Hence we cannot try to reinitialize already initialized variables inside a java for loop.
public class SimpleForLoop { public static void main(String[] args) { int i=4; for(int i=0;i<=10;i=i+2) { System.out.println(i); } } }
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Duplicate local variable i at SimpleForLoop.main(SimpleForLoop.java:9)
In the next tutorial, we will learn in detail about Enhanced for loop or for-each loop.