How To Write Java Loops

Loops are an important part of any computer application.

Similarly, learning the syntax for writing loops is a crucial step in learning a new programming language. Java is no exception.

In this tutorial, you’ll learn about the different types of loops in Java and how to write loops in the Java programming language.

Table of Contents

You can skip to a specific section of this Java tutorial using the table of contents below:

Java Fundamentals

Before we dive into the loops, I wanted to start this tutorial by reminding you of some Java fundamentals that you should understand before proceeding.

  1. Java is an object oriented language. Every line of code that runs in Java must be inside a class.

  2. A class should always start with an uppercase first letter, because Java is case-sensitive.

  3. The name of the Java file must match the class name. When saving the file, save it using the class name and add .java to the end of the filename.

  4. Every program must contain the main() method.

  5. The curly braces {} marks the beginning and the end of a block of code.

  6. Each code statement must end with a semicolon.

In Java, loops are used to execute a block of code repeatedly until a specified condition is met. Said differently, loops will continue to execute until a test statement is false.

In this lesson, we shall learn about each of the three Java loop statements. To start, let’s define a loop.

What is a Java Loop?

Unlike humans, computers are very capable of performing repetitive tasks tirelessly.

Every programming language gives you a feature - called loops - that instructs the computer to perform repetitive tasks through the use of some special syntax.

Looping, therefore, is the process of executing a statement repeatedly based on a given condition.

Let’s consider an example.

Imagine you need your computer to carry out the same task 10 times. You could just write the same code statement 10 times.

What if you want it to perform a task 60 times? Well, you could also do that by repeating the statement 60 times.

How about you need a task be carried out a million (1,000,000) times?

As you can see, with sufficient complexity it becomes unreasonable to write the same code numerous times. This is why you need to use loops. With Java loops, you only need to write one statement and then instruct it to run a given number of times.

Java loops are useful since they reduce errors, save time, and make your code more readable. The Java programming language supports many looping features that enable you to develop programs with repetitive processes. We’ll explore these next.

The 3 Types of Java Loops

There are 3 types of loops available in the Java programming language:

  1. Java for loop

  2. Java while loop

  3. Java do while loop

The three types of Java loops are each slightly different and are useful in different situations. We will explore each loop one-by-one throughout the rest of this article.

Java for Loops

The first type of Java loop is the for loop. We use the Java for loop when we want to execute a block of code a known number of times. If you are familiar with C and C++, the basic Java for loop is almost identical to the equivalent loop in those languages.

The Java for loop takes a variable as its iterator and assigns it an initial value. It then iterates through the loop body as long as a test condition is true.

The most important thing to know about this type of Java loop is that it is used when you know exactly how many times you want to loop through a block of statements.

The Syntax of the Java for Loop


for(initialization; condition; incr/decr)

{

 

  //loop body or statements to be executed

 

}

Let’s define what is contained in this code block:

  • Initialization statement - executed before the code block.

  • Condition statement - this defines the condition for executing the code block. The condition statement is evaluated. If it is true, the loop body is executed. If it is false, the loop will end.

  • Incr/decr (Update) Statement - this updates the variable for next iteration. It increases/decreases a value each time the code block in the loop has been executed. It is executed everytime the loop runs, but after the code block has been executed.

A Flow Chart for Java for Loops

A Flow Chart Depicting The Logic of a Java For Loop

Example 1

To understand the syntax of a Java for loop, let’s consider an example.

Let’s say we want a Java program to print numbers 1 through 5. The code will be as follows:


public class Number

{

	public static void main (String [] args)

           {

           	System.out.println("MY FIRST LOOP");

        	          for(int ctr=1; ctr<=5; ctr++) 

                           {

            	              System.out.println(ctr);

         	              }

       	}

}

The output of this code is below:

MY FIRST LOOP

1

2

3

4

5

In the above example, we have;

  • Initialization statement: int ctr=1

  • Condition statement: ctr<=5

  • Incr/decr Statement: ctr++

Initially, the value of ctr is 1 and the test condition evaluates to true. The print statement is therefore executed. Then the increase statement is executed.

The update statement ctr++ increases the value of ctr by 1. The process iterates.

The test condition repeats and if the new value is less than 5, the print statement is executed.

This process iterates until ctr>5. For instance, when the ctr=6, the test condition (ctr<=5) becomes false and the loop stops.

Example 2

Let’s have another example that will find the sum of natural numbers from 1 to 500.

public class Number

{

    public static void main(String[] args)

      {

         	System.out.println("MY SECOND LOOP");

         	int sum = 0;

  	       for (int ctr = 1; ctr <= 500; ++ctr)

                 {

        	         sum += ctr;         // This is a simpler form of “sum = sum + ctr”

             	}

         	 ("Sum of natural numbers from 1 to 500 is " + sum);

       }

}

The output of this code is below:

MY SECOND LOOP

Sum of natural numbers from 1 to 500 is 125250

In this example, int sum=0 means we have a variable named sum whose initial value is 0.

Inside our java for loop, we have variable ctr whose value is 1.

When the program runs, the variable sum is updated with the increment statement sum +1.

Then the value of ctr is increased by 1.

The execution of for loop body continues until ctr>500.

Java while Loops

Java while loop is another type of Java loop. The loop executes a block of statements as long as a specified condition remains true.

The Syntax of Java while Loops

The generic syntax of a Java while loop is below:

initialization;

while(condition)

	{

   	//loop body

          incr/decr;

	}

The important thing to note here is that Java while loops will never execute loop if condition is false.

Flow Chart for Java while Loops

A Flow Chart Depicting The Logic of a Java While Loop

Java while Loop Example

Let’s consider an example. Specifically, let’s build a loop that prints even numbers from 0 to 10.

public class Number

  {

   	public static void main (String [] args)

       	{

            	int ctr=0;

            	int maxCtr=10;

            	System.out.println("MY THIRD LOOP");

 

            	while (ctr<=maxCtr)

                {

                	System.out.println(ctr);

                	ctr=ctr+2;

            	}

        	}

}

Note: There is no semicolon at the end of while statement

The output of the above third program is:


MY THIRD LOOP

0

2

4

6

8

10

Java do while Loops

Java do while loops are the other type of loops in the Java programming language. The do while loop is a variant of the Java while loop.

This loop executes loop statements once and then continues to test if the condition statement is true. The next iteration is executed as long as the condition is true.

The main difference is that the do while loop must execute the statement at least once. The while loop doesn’t necessarily have to execute the statement at all.

Syntax for Java do while Loops

initialization;

do

{

  // loop body	

 

  Incr/decr;

}

   while (condition);

Here, the most important thing to note is that unlike while loops, Java do while loops will execute the loop at least once when the initial condition is false.

Flow Chart for Java do while Loops

A Flow Chart Depicting The Logic of a Java Do While Loop

Java do while Loop Example

Let’s consider another example where we build a do while loop that prints the numbers 1 to 10.


public class Main

   {

    	public static void main (String [] args)

       	{

          	int ctr=1;

          	int maxCtr=10;

          	System.out.println("MY FOURTH LOOP");

          	do

             	{

                	System.out.println(ctr);

                	ctr=ctr+1;

             	}

          	while (ctr<=maxCtr);

    	}

  }

Note: There is semicolon at the end of while statement.

Once we run the above program, we see the following output:


MY FOURTH LOOP

1

2

3

4

5

6

7

8

9

10

As mentioned, this type of Java loop will always be executed at least once, even if the condition is false. This is because the code block is executed before the condition is tested.

Let’s look at another example to see this concept in action. Specifically, we’ll use the same code as our last example but set our initial counter (int ctr=11) to be greater than our maximum counter (int maxCtr=10).


public class Main

   {

    	public static void main (String [] args)

       	{

          	int ctr=11;

          	int maxCtr=10;

          	System.out.println("MY FIFTH LOOP");

          	do

             	{

                	System.out.println(ctr);

                	ctr=ctr+1;

             	}

          	while (ctr<=maxCtr);

    	}

  }

You will notice that the program will still print out the initial counter, 11 (even if it is greater than 10). This is because it executes it before testing the condition, which would have turned false. However, the loop will end immediately after the first test of the condition, because it tests false.

The output of this code is below:


MY FIFTH LOOP

11

Other Types of Java Loops

As we have seen, the main types of loops available in Java are Java for loops, Java while loops and Java do while loops.

However, it is important to mention that Java provides other types of for loops that are very significant in programming. These Java loops are

  1. Java Nested for loop

  2. Java for-each loop /Java Enhanced for loop

  3. Java Labelled for loop

Java Nested for Loops

This is a specific type of Java loop that is used when the programmer wants to have a for loop inside another for loop.

Java Nested for Loop Example

public class Main { 

  public static void main(String[] args)

    {

     //loop of i 

           	 for(int i=1;i<=2;i++)

           	   { 

           	    //loop of ctr 

           	    for(int ctr=1;ctr<=2;ctr++)

          	{ 

           	        System.out.println(i+" "+ctr); 

           	       } //end of i 

           	   }//end of ctr 

    } 

}

The output of this nested loop example is:


1 1

1 2

2 1

2 2

Another example is the pyramid example:


public class Main { 

           	public static void main(String[] args)

  { 

           	for(int i=1; i<=5; i++)

  	{ 

           	for (int ctr=1; ctr<=i; ctr++)

     	{ 

           	        System.out.print("@ "); 

           	  } 

           	System.out.println();  //new line 

      } 

   } 

}

The output of this code is below:


@

@ @

@ @ @

@ @ @ @

@ @ @ @ @

Java for-each Loop

Java for-each loop is another type of Java loop. It is used in Java to traverse through elements in a collection or array.

It is preferred to use when dealing with arrays since it is simpler than the normal Java for loop. This type of Java for loop does not work on an index but on an elements basis. Once the loop is executed, it returns elements one by one in the defined array.

This enhanced for loop is inflexible and hence should be used only when the loop needs to execute in a sequential manner. The incrementor variable in Java enhanced for loops is immutable, making it impossible to modify. Unlike other Java loops, in enhanced for loops, this immutability means that the incrementor value cannot be updated.

Syntax of a Java for-each Loop

 for(Type var:array)

	{ 

           	//body loop 

    }

Java for-each Loop Example

Let’s have an example that prints the elements of an array.

public class Main { 

           	public static void main(String[] args) { 

           	     

           	    int ar[]={22,33,46,51,72}; 	//declaration of an array

           	  	

           	    for(int ctr:ar){ 

           	        System.out.println(ctr); 

           	    } 

           	} 

} 

The output of this code is below:


22

33

46

51

72

Java Labelled for Loop

This is another type of Java loop. This is used when we want to name every for loop. We usually use the key words “break” and “continue”. This only breaks or continues the most inner for loop.

Syntax for Java Labelled for loop


labelname: 

           	for(initialization; condition; incr/decr)

    	{ 

 

           	//code to be executed 

 

           	 }

Java Labelled for Loop Example 2

We shall label a nested for loop example to illustrate a java labelled for loop.

public class Main { 

           	public static void main(String[] args) { 

           	    //Using Label  

           	    outer: 

           	        for(int i=1;i<=4;i++){ 

           	            inner: 

           	                for(int ctr=1;ctr<=4;ctr++){ 

           	                    if(i==3&&ctr==3)

           	                	{ 

           	                        break outer; 

           	                    } 

                System.out.println(i+" "+ctr); 

           	                } 

           	        } 

           	} 

           	} 
		

The output of this code is below:


1 1

1 2

1 3

1 4

2 1

2 2

2 3

2 4

3 1

3 2

Final Thoughts

I have taken you through all types of Java loops, from the main three ones to other forms of Java for loops. The lesson was thorough to ensure you fully comprehend Java loops. Take note of each type of Java loop and when to use each of these types.

If you enjoyed this article, be sure to join my Developer Monthly newsletter, where I send out the latest news from the world of Python and JavaScript:
Written on May 9, 2020