Skip to content

For loop

You have a task that requires executing a certain block of code repeatedly, or you need to traverse through elements in a collection like an array or a list. That's where for loops come into play! allowing you to automate repetitive tasks with ease and efficiency.

Understanding For Loops

In Java, a for loop provides a concise way to iterate over a range of values or elements in a collection. It consists of three main parts: initialization, condition, and iteration expression, all enclosed within parentheses and separated by semicolons.

Syntax of For Loop:

java
for (initialization; condition; iteration) {
        // Code to be executed repeatedly
        }

Example:

Let's say we want to print numbers from 1 to 5:

java
class ForLoop{
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

Foreach Loop

The foreach loop, also known as the enhanced for loop, provides a simplified way to iterate over elements in an array or a collection without the need for explicit indexing. It's perfect for situations where you want to iterate through each element sequentially without worrying about index management.

Syntax of Foreach Loop:

java
for (type variableName : array/collection) {
    // Code to be executed for each element
}

Example:

Let's iterate over elements in an array and print each element:

java
class ForLoop{
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

Java for loops, along with the foreach loop, Whether you're iterating over a range of values or traversing through elements in a collection, for loops provide a concise and efficient way to automate repetitive tasks.

So, the next time you find yourself needing to repeat a block of code or iterate through elements, remember the power of for loops. With a little creativity and practice, you'll be able to tackle a wide range of programming challenges with ease.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.