For Loop Java | For Each Loop Java [Easy Examples]


JAVA

Author: Bashir Alam
Reviewer: Deepak Prasad

 

Introduction to for loop in Java

While writing code, sometimes, there might be a situation when we need to execute a block of code several times. In general, these statements execute in a sequential manner: The first statement in a function executes first, followed by the second, and so on. But this makes the process very complicated as well as lengthy and therefore time-consuming. However, programming languages provide various control structures that allow for such complex execution statements. One of such control structures is java for a loop.

In this tutorial, we will learn about for loop java from very basics to advance level concepts. We will cover the initializer, condition, and post iteration in for loop java by taking various examples.

We will also discuss the break and continue statements and see how we can use them in for loop java. Moreover, we will also learn about for each loop Java and see how it actually works. In a nutshell, this tutorial is going to be one of the best and informative tutorials about java for loops.

 

Getting started with for loop Java

The for loop in Java is an entry-controlled loop that allows a user to execute a block of a statement(s) repeatedly with a fixed number of times on the basis of the test expression or test condition. See the pictorial representation of for loop java below:

For Loop Java | For Each Loop Java [Easy Examples]

In this section, we will discuss the basics of java for a loop including the initializer, condition, and post increments. But first, let us start from the syntax of for loop java.

 

Syntax of for loop in Java

All the loop-control elements of for loop java are gathered at one place, on the top of the loop within the round brackets(). See the simple syntax of java for loop below:

for( initializer; condition; update){
    // for loop statements
}

Notice that there is a semi colon after the initializer and condition. All the three elements are written inside round brackets, separated by semi-colons. Now let us see what those three elements are and what they do in java for a loop.

 

Java for loop initializer

The loop initializer statement is only executed once before the for loop begins. The loop initializer statement is typically used to initialize variables or objects that are used by the loop condition statement. See the example below which uses int type variable to initialize the loop by defining the variable to be equal to zero.

for( int num = 0; condition; update){
    // for loop statements
}

It is important to have an initializer but is not required. We can have a for loop without the initializer as well which we will discuss later.

 

Java loop condition

The condition statement is the second statement inside the for loop java parentheses. This statement is an expression that should evaluate as either true or false. If the statement evaluates to true, the for loop will be evaluated one more time. If the statement evaluates to false, the for loop is not executed anymore.

See the example below which provides a condition that the num should be less than 5, otherwise the loop will not be executed.

for( int num = 0; num<5; update){
    // for loop statements
}

The above loop will be executed until the num becomes equal to or greater than five.

 

Post iteration operation in for loop Java

The third statement in the for loop java is the post iteration statement or update. This statement is executed after each iteration and is typically used to update the variables that control the condition statement. For instance, it increments numbers each time.

Now let us see the following example where we update the condition each time the loop iterates.

for( int num = 0; num<5; num++){
    // for loop statements
}

Now our for loop is complete, we initialized an integer value and defined it to be equal to zero. Then we provide the condition that this loop should be executed until the num is less than 5 and in each iteration, we update the num and increment by 1.

 

Example and syntax of Java empty for loop

A Java empty for loop is a loop that does not contain any statements. It is usually used to pause the program for some time. The simple syntax of java empty for loop looks like this:

for(initializer; condition; update){
    ;
}

Notice that there is nothing inside of the java empty for loop. It only contains a semi-colon which specifies that this loop is an empty loop. Now let us take an example of java empty for loop. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // for loop java
        for (int i = 0; i<5; i++){
            // empty for loop
            ;
        }
    }
}

If we run the code, it will do nothing, because the loop is empty and there are not any statements to execute.

 

Example and syntax of java infinite for loop

An infinite loop is a loop that never stops because the condition is always true. We can create a java infinite loop by providing a condition that never becomes false. The following is the simple syntax of java infinite for loop.

for(initializer; always true condition; update){
    // statements
}

Now there are many ways to form an infinite for loop java. One of the simplest ways is to create a for loop without any of the three ( initializer, condition, and update) inside the brackets. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // java infinite for loop
        for (; ;){
            System.out.println("Infinite loop");    
        }
    }
}

This is totally a correct way of writing for loop java, if we will not provide any of the parameters ( initializer, condition, and update), the loop will be considered to be an infinite loop. If we run the above program, the loop will execute infinite times.  Another way to implement java infinite for loop is to provide a condition that is always true. For example, see the program below:

// class
public class Main  { 
    public static void main(String[] args){
        // java infinite for loop
        for (int i =5;i>3 ;i++){
            System.out.println("Infinite loop");    
        }
    }
}

Notice that the condition is always true in the above case because we are incrementing the value of I each time. Such a loop will be also an infinite loop. We can terminate or stop the infinite loop by pressing ctrl+C on keyboard.

 

For loop in Java with break statement

The break is a keyword that is used to stop the execution of for and while loop even if the condition is true. It is helpful if we want to stop the for loop at some specific point.

See the example below which stops the execution of for loop even the condition is still true.

// class
public class Main  { 
    public static void main(String[] args){
        // java infinite for loop
        for (int i =0;i<10 ;i++){
            // if statement
            if(i==7){
                // break statement
                break;
            }  
            System.out.println("counting..."+i);
        }
    }
}

Output:

counting...0
counting...1
counting...2
counting...3
counting...4
counting...5
counting...6

Notice that we stop the execution of for loop java when the initial condition was true by using the break statement.

 

For loop Java with continue statement

The continue statement is used in java while and for loop which simply skips the specific condition and continues with another iteration. It is useful when we need to skip some part of code when a condition is satisfied. For example, we want to print the numbers from 1 to 9 without printing the number 7. See the example which uses the continue statement to skip number 7.

// class
public class Main  { 
    public static void main(String[] args){
        // for loop java
        for (int i =1;i<10 ;i++){
            // if statement
            if(i==7){
                // continue statement
                continue;
            }  
            System.out.println("counting..."+i);
        }
    }
}

Output:

counting...1
counting...2
counting...3
counting...4
counting...5
counting...6
counting...8
counting...9

Notice that the number 7 was not printed, because we skipped it using java continue statement.

 

Java nested for loop

A nested loop is a loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: while, do-while, or for. In this section, we will discuss the java nested for loop which is simply a java for loop written inside another for loop. The inner for loop totally depends on the outer loop, if the first condition is false then the inner loop will never execute. Before going into the details and examples of nested for loop, let us first see the syntax.

 

Syntax of Java nested for loop

The syntax of nested for loop is very similar to simple for loop with a difference that the body of outer for loop contains another loop. The simple syntax looks like this:

for(initializer;condition; update){
    // inner for loop
    for(inttializer; condition; update){
        // statements
    }
}

We can use as many for loops as we want inside one another.

Example of Java nested for loop

Let us now take an example and see how we can use nested for loops in java. See the example below which print the table of numbers from 1 to 5 using nested for loop.

// class
public class Main  { 
    public static void main(String[] args){
        // for loop java
        for (int i =1; i<6; i++){
            // printing the number
            System.out.println("Table of "+i);
            // inner loop
            for(int j =1; j<11; j++){
                // printing the table
                System.out.print("  "+(i*j));
            }
            // new line
            System.out.println("");
        }
    }
}

Output:

Table of 1
1   2   3   4   5   6   7   8   9   10
Table of 2
2   4   6   8   10   12   14   16   18   20
Table of 3
3   6   9   12   15   18  21   24   27   30
Table of 4
4   8   12   16   20   24   28   32   36   40
Table of 5
5   10   15   20   25   30   35   40   45   50

 

For each loop Java

The Java for-each loop provides an alternative approach to traverse the array or collection in Java. The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code more readable. It is known as the for-each loop because it traverses each element one by one. The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order.

In this section we will look at the syntax of for each loop Java and then will solve an example using it.

 

Syntax of for each loop Java

The syntax of for each loop Java is a little bit different from java for loop. It starts with the keyword "for" like a normal for loop. But instead of declaring and initializing a loop counter, we declare a variable that is the same type as the base type of the array followed by a colon which is then followed by the array name.

See the simple syntax of for each loop Java below:

for(dataType variable : array){  
    //body of for-each loop  
    }  

Notice that there are no any initializers and conditions.

 

Example of for each loop Java

As we discussed that for each loop Java is mainly used to iterate an array. Here we will take an array and will use for each loop Java to iterate it. But before using for each loop Java, let us first iterate the array using the normal for loop java.

See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // array
        int array[] = {1, 2, 3, 4, 5};
        // for loop java
        for (int i =0; i< array.length; i++){
            // printing the elements
            System.out.println(array[i]);
        }
    }
}

Output:

1
2
3
4
5

Now let us iterate the array using for each loop Java and print out all the elements. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // array
        int array[] = {1, 2, 3, 4, 5};
        // for each loop Java
        for (int i:array){
            // printing the elements
            System.out.println(i);
        }
    }
}

Output:

1
2
3
4
5

Notice that it is more simple and easy to iterate an array using for each loop Java rather than using for loop.

 

Summary

The for loop is used to repeat a section of code known number of times. Sometimes it is the computer that knows how many times, not we, but it is still known. In this tutorial, we learned about for loop java. We covered everything that you need to know in order to start working with java for loops.

We learned about empty for loop, infinite for loop, and how we can use the break and continue statements to control the flow of iteration. Moreover, we also discussed each loop which helps us to iterate over arrays and collections. All in all, this tutorial contains all the information along with examples for beginners.

 

Further Reading

for loop java 
Java for-each loop
Java while loop

 

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment