Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are loops in java?
3.
Types of loops in Java
4.
While loop in Java
4.1.
Syntax
4.2.
Implementation in Java
4.2.1.
Flowchart
5.
Do while loop in Java
5.1.
Syntax
5.2.
Implementation in Java
5.2.1.
Flowchart
6.
For loop in Java
6.1.
Syntax
6.2.
Implementation in Java
7.
Types of For Loops in Java
7.1.
Simple For Loop in Java
8.
Syntax
8.1.
Implementation in Java
8.2.
Foreach loop in Java
8.3.
Implementation in Java
8.4.
Labeled For Loop in Java
8.5.
Implementation in Java
9.
Difference Between For Loop - While Loop - Do-While Loop
10.
Frequently Asked Questions
10.1.
Why is it called looping?
10.2.
What are loops in Java with examples?
10.3.
What is the syntax of a for loop?
10.4.
What are the 4 parts of loops?
11.
Conclusion
Last Updated: Aug 6, 2024
Easy

Loops in Java With Examples and Syntax

Introduction

In Java, loops are like magic wands that let programmers repeat certain bits of code over and over, as long as a specific condition stays true. Think of it like a playlist on repeat. Normally, a program just follows instructions one after the other in order. But with loops, you can jump back and do some steps again if you need to. This is super handy for doing things multiple times without writing the same code again and again. Plus, loops work hand-in-hand with conditions to decide when to keep going or stop, making your code smarter and more efficient.

what are loops in java

What are loops in java?

Loops is a feature in Java that is commonly used to perform a particular part of the program frequently if a given condition evaluates to be true.

Loops are undoubtedly an important feature of any program, and mastering the concept of controlled repetition is an important part of becoming a programmer.

Since this blog is in continuation of decision making in Java, it is recommended to read
decision making in Java using if, else-if and switch statements before moving further in this
blog.

Types of loops in Java

In the Java programming language, there are primarily four types of loops.

  • While loop
  • Do while loop
  • For loop
Types of loops in java

We’ll explain them one by one.

While loop in Java

The most fundamental loop statement in Java is while. It repeats the execution of a statement or block while its controlling expression is true. 

Here's how it looks in its most basic form:

Syntax

while(condition) {
	// body 
}


Any boolean expression can be used as the condition. Until the conditional expression is true, the code inside the loop will execute. When the condition becomes false, control is passed to the next line of code after the loop. 

Note: If only a single statement is inside the loop, the curly braces are not needed.

Program to demonstrate the while loop:

Implementation in Java

public class While { 
	public static void main(String args[]) { 
		int n = 5; 
		while(n > 0) { 
			System.out.println("Coding Ninjas " + n); n--; 
		} 
	}  
}


Output:

Coding Ninjas 5
Coding Ninjas 4
Coding Ninjas 3
Coding Ninjas 2
Coding Ninjas 1 


When we run the above program, it will print “Coding Ninjas” five times because n is 5.

Flowchart

  • The value ofis increased, whereas that of j is decreased. 
  • These values are then compared to one another. 
  • The loop repeats if the new value of i is still smaller than the new value of j
  • The loop ends if i is equal to or greater than j.  
  • In the end, i will hold a value that is halfway between the initial values of i and j when the loop ends. 

Do while loop in Java

The do-while loop in Java is used to repeatedly iterate a portion of a program until the specified condition is met. A do-while loop is recommended if the number of iterations is not fixed, and the loop must be executed at least once.

The do-while loop is also known as an exit control loop. Unlike while and for loop, the do-while loop checks the condition at the end of the loop. That’s why the do-while loop is executed at least once.

The generalised form of do-while loop is given below:

Syntax

do {    
	//body
	//iteration statement   
} while (condition);    


Every iteration of the do-while loop first executes the loop's body and then evaluates the condition. If the condition holds, the loop will repeat. Otherwise, the loop terminates.

A simple program to demonstrate do while loop in Java is given below:

Learn about Data Structure

Implementation in Java

class DoWhile {
	public static void main(String args[]) {
		int n = 5;
		do {
			System.out.println("Coding Ninjas " + n);
			n--;
		} while(n > 0);
	}
}


Output:

Coding Ninjas 5
Coding Ninjas 4
Coding Ninjas 3
Coding Ninjas 2
Coding Ninjas 1

Flowchart

  • Inside do, it prints “Coding Ninjas” with the counter variable and then the value of n decreases by 1. 
  • After that, the value is compared to zero. If it's greater than zero, the loop will continue, otherwise, it'll terminate.

For loop in Java

The Java for loop is the most powerful and versatile of iterative statements.

The generalised form of for loop is given below:

Syntax

for(initialisation; condition; iteration) { 
	// body 
}


When the loop starts, the initialisation part of the loop is executed. The initialisation is an expression that sets the loop control variable's value, which acts as a counter that controls the loop.

The mechanism of for loop is as follows:

  • The initialisation expression is only executed once. Next, the condition is evaluated. 
  • The condition should be a boolean expression. It tests the loop control variable with a given value. 
  • If the condition holds, then the loop's body is executed. 
  • If the condition doesn't hold, the loop terminates. 
  • Then the iteration part of the loop is executed. Iteration expression increases or decreases the value of the loop control variable. 
  • The loop then evaluates the conditional expression, then executes the loop's body.
  • Then the loop executes the iteration expression with every pass. 

Implementation in Java

public class ForTest {
	public static void main(String args[])  {
    	int n;
    	for(n=5; n>0; n--)
        	System.out.println("Coding Ninjas " + n);
	}
}


When we run this program, it will print “Coding Ninjas” along with the counter variable five times.

Output:

Coding Ninjas 5
Coding Ninjas 4
Coding Ninjas 3
Coding Ninjas 2
Coding Ninjas 1


Points to remember:

  • The variable inside the initialization portion can be initialized in place as well. 
    For example, for(int n=10; n>0; n--)
    Note: The scope of the variable is limited to the for loop.
     
  • We can include more than one statement in the initialization and iteration portions of the for loop. This can be done using the comma ",”.
    For example, for(a=1, b=4; a<b; a++, b--)
    Note: The initialization portion sets the values of both a and b simultaneously.

Types of For Loops in Java

The for loop supports several variations that increase its power and applicability. The reason for flexibility is that it has three parts:

  • Simple For Loop in Java
  • For-each Loop in Java
  • Labeled For Loop in Java
     

Simple For Loop in Java

A Simple For Loop in Java contains three main components: initialisation, condition, and update statement. The initialisation step declares loop variables before the loop iterations begin. The condition is checked at the beginning of each iteration, and the loop continues executing only if it is true. The update statement executes at the end of each iteration and updates the loop variables. The update statement usually increments/decrements the loop variable.

Syntax

for (initialisation; condition; update) {
    // Loop body
}
You can also try this code with Online Java Compiler
Run Code


A java program for printing a pattern using nested loops is as follows: 

Implementation in Java

public class Nested { 
	public static void main(String args[]) { 
		int i, j; 
		int n = 5;
		for(i=0; i<n; i++) { 
			for(j=i; j<n; j++) 
				System.out.print(". "); 
			System.out.println(); 
		} 
	} 
}


Output:

. . . . . 
. . . . 
. . . 
. . 
. 

 

In the above code, we have initialized a variable n=5 to enter the number of rows for the pattern. The range of the outer for loop will be 0 to 4.

  • The iteration of the inner for loop depends on the outer loop. The inner loop is used to print the number of columns.
  • In the first iteration, the value of i is 0, so j starts from 0 and until j is less than 5 a dot will get printed with space.
  • This gets repeated n number of times.
  • The last print statement prints a line after each row.

Foreach loop in Java

In JDK 5, a new variation of for loop was introduced known as for each loop. A for each loop in Java is used to iterate through a set of objects, such as an array, from beginning to end in a strictly sequential manner.

The general form of the for-each version is given below: 

Syntax

for(type var : collection) 
statement-block
You can also try this code with Online Java Compiler
Run Code


Here, type specifies the type of collection, and var is the name of an iteration variable that will receive elements from a collection one by one from start to end. 

In every iteration of the loop, the next element in the collection is fetched in var. The loop is repeated until the entire collection has been retrieved.

A simple program to demonstrate the Java for each loop is given below:

Implementation in Java

public class For_Each {
    public static void main(String[] arg) {
		int[] marks = { 15, 13, 19, 16, 10 };
		// for each loop
		for (int num : marks) {
			System.out.println(num); 
 		}
    }
}


Output:

15
13
19
16
10


Try it on Java Compiler.

Let’s see the difference between for and for each via a comparison.

int collect[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int sum = 0;

for(int i=0; i < 10; i++) 

sum += collect[i];

int collect[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 

int sum = 0; 

for(int x: collect) 

sum += x;

Limitations of for each loop are as follows:

  • More overhead cost than simple iteration methods.
  • Used to iterate in the forward direction only.
  • They cannot modify the collection.
     

Note: Unlike some languages that implement a for-each loop using the keyword foreach, Java added the for-each capability by enhancing the for statement.

Do you want to boost your self-esteem by solving problems and earning points?

Check out the Iterative Statement problems in Studio and put in some serious practise time, champ.

Never Quit! It might look hard initially, but remember that practice makes perfect. 

The adrenaline rush you will get when the idea of a problem clicks in mind after struggling for many hours is worth the effort. So push yourself to be one of the best programmers.

Labeled For Loop in Java

A labeled for loop in Java is a way to give a loop a user-defined identifier, or label, that allows it to be referenced elsewhere in the code. This allows you to break out of multiple nested loops at once or continue to the next iteration of a specific loop. The label is placed before the loop, followed by a colon, and can be used with the break and continue statements to specify which loop to exit or continue.

Implementation in Java

public class LabeledForLoopExample {
   public static void main(String[] args) {
       outerloop:
       for (int i = 1; i <= 3; i++) {
           innerloop:
           for (int j = 1; j <= 3; j++) {
               System.out.println("i = " + i + ", j = " + j);
               if (i == 2 && j == 2) {
                   break outerloop;
               }
           }
       }
   }
}
You can also try this code with Online Java Compiler
Run Code

Difference Between For Loop - While Loop - Do-While Loop

Difference

For Loop

While Loop

Do-While Loop

Syntax

for(initialization; condition; increment/decrement) while(condition) do { ... } while(condition) 

Condition Checked 

Checked at the beginning of each iterationChecked at the beginning of each iterationChecked at the end of each iteration

Execution

Can be used when the number of iterations is knownUsed when the number of iterations is unknownExecutes at least once before checking the condition

Loop Variable

The loop variable is updated within the loop initialisationThe loop variable is manually updated within the loop bodyThe loop variable is manually updated within the loop body

Minimum number of iterations

The loop body does not execute if the condition is already false at the beginning (Entry controlled loop)The loop body does not execute if the condition is already false at the beginning (Entry controlled loop)The loop body executes once even if the condition is already false at the beginning (Exit controlled loop)

Frequently Asked Questions

Why is it called looping?

It's called "looping" because, in programming, it refers to the process of repeatedly executing a block of code, creating a cycle. This cycle, much like a loop in a physical sense, continues until a specific condition is met, hence the term.

What are loops in Java with examples?

In Java, loops are programming constructs that allow you to repeat a block of code a specified number of times or until a certain condition is met. Loops help to reduce redundant code and improve the efficiency of the program.

What is the syntax of a for loop?

The syntax of a for loop is as follows:
for (initialisation; condition; update) {
   // Code to be executed in each iteration
}

The initialisation condition executes once. The condition is checked before each iteration. The update statement executes after each iteration.

What are the 4 parts of loops?

The four parts of loops are initialisation, condition, execution and updation. The initialisation part initialises the variables used in the for loop. The condition is checked before each iteration. The execution of the loop body then occurs. At the end of an iteration, the updation statements update the loop variables and prepare them for the next iteration.

Conclusion

This article unfolds the concept of various loops in Java. These looping statements have great importance in programming. 

Also, if you wish to learn more about looping statements in various other languages, Here's a quick guide to follow:

  • Loops in C++
  • Loops in Python

Java is one of the most popular languages, it finds wide applications in Android development and server development, and learning Java in-depth will definitely get you a lucrative placement.

To learn more about Java, take a look at various courses offered by Coding Ninjas. 

Happy Learning!

Live masterclass