Home Java Tutorial Java for Loop

Java for Loop

by Anup Maurya
34 minutes read

In this tutorial, we will learn how to use for loop in Java with the help of examples and we will also learn about the working of Loop in computer programming.

In Java, the for loop is a control statement used for iterative execution of a block of code. It is used when you know how many times you need to execute a block of code. The syntax for a for loop in Java is as follows:

for (initialization; condition; increment/decrement) {
   // code to be executed
}

Here’s what each part of the for loop means:

  • initialization: This is where you declare and initialize the loop counter variable. It is executed only once, at the beginning of the loop.
  • condition: This is the expression that is evaluated before each iteration of the loop. If the condition is true, the loop continues; otherwise, the loop ends.
  • increment/decrement: This is where you increment or decrement the loop counter variable. It is executed at the end of each iteration of the loop.
  • code to be executed: This is the block of code that is executed repeatedly until the condition is false.

Here’s an example of a for loop in Java:

for (int i = 0; i < 5; i++) {
   System.out.println("The value of i is: " + i);
}

In this example, the loop counter variable i is initialized to 0. The condition is that i must be less than 5. At the end of each iteration, i is incremented by 1. The loop continues until i is no longer less than 5. The output of this program is:

The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4

Here are some other examples of for loops in Java:

Example 1: Printing Even Numbers

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

In this example, we are using the i+=2 statement in the increment section to increment i by 2 at the end of each iteration. The output of this program is:

The value of i is: 0
The value of i is: 2
The value of i is: 4
The value of i is: 6
The value of i is: 8
The value of i is: 10

Example 2: Printing a String in Reverse

String str = "Hello, world!";
for (int i = str.length() - 1; i >= 0; i--) {
   System.out.print(str.charAt(i));
}

In this example, we are using the str.length() - 1 statement in the initialization section to initialize i to the last character of the string str. We are using the i-- statement in the increment/decrement section to decrement i by 1 at the end of each iteration. The output of this program is:

!dlrow ,olleH

In summary, the for loop in Java is a powerful tool for performing iterative execution of a block of code. With the for loop, you can easily execute a block of code multiple times with the help of a loop counter variable.

related posts

Leave a Comment