Skip to main content

Java For Loop

Java, like many other programming languages, provides several control flow statements. One of them is the For Loop. This type of loop is frequently used when you have a block of code which you want to repeat a fixed number of times.

What is a For Loop?

A For loop is a control flow statement that allows code to be executed repeatedly. These loops are often used when the number of iterations is known before entering the loop.

The For Loop consists of three parts:

  1. Initialization: This is where we initialize our counter to a starting value. The initialization statement is executed only once.

  2. Condition: This is tested each time before going through the loop. If it's true, the statements inside the loop are executed. If it's false, the loop ends, and the program continues with the remaining code.

  3. Increment/Decrement: It is used to increment or decrement the counter.

The syntax of for loop in Java is as follows:

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

Example of a For Loop

Let's consider a simple example:

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

In the above example, the loop will start from 0 as we have initialized i to 0. Then it will check the condition, if i is less than 5, it will enter into the loop and print the statement. After executing the code inside the loop, it will then increment i by 1. This process will keep repeating until i is no longer less than 5.

For-Each Loop

Java also provides a For-Each loop, which is mainly used to traverse array or collection elements. The advantage of a For-Each loop is that it eliminates the possibility of bugs and makes the code more readable.

The syntax of the For-Each loop is:

for (type variableName : arrayName) {
// code block to be executed
}

Here is an example:

String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Elderberry"};

for (String fruit : fruits) {
System.out.println(fruit);
}

In this example, the Java For-Each loop goes through each element of the array fruits, and assigns the current element to the fruit variable, then executes the code inside the loop.

Practice these examples and try to modify the code to get a better understanding of how For Loops work in Java. Remember, practice is crucial when learning a new programming language.