In Java, for loops serve as a key control mechanism for carrying out a set of instructions repeatedly for a defined count or for traversing through a series of values. They prove to be highly advantageous for handling repetitive operations like handling elements in an array, producing recurring results, or running a set of commands for a set quantity of iterations.
The for loop in Java is utilized to repeat a section of the code multiple times. When the number of iterations is predetermined, it is advisable to implement a for loop.
There are the following three types of for loops in Java.
- Simple for Loop
- For-each or Enhanced for Loop
- Labelled for Loop
Java Simple for Loop
A simple for loop is the same as C / C++ . We can initialize the variable , check condition and increment/decrement value. It consists of four parts:
- Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition.
- Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition.
- Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
- Statement: The statement of the loop is executed each time until the second condition is false.
Syntax of the for loop
It has the following syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
Flowchart of the for loop
Displayed below is a flowchart demonstrating the functionality of the for loop.
for Loop Example 1: Printing Numbers from 1 to 10
To illustrate the usage of a for loop in Java for printing numbers between 1 to 10, we can consider the following example.
Example
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class Main {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
for Loop Example 2: Finding Factorial
Let's consider a different instance to illustrate the process of calculating the factorial of a number by utilizing a for loop.
Example
// Java Program to print factorial of 5
public class Main {
public static void main(String[] args) {
// Declare an integer variable 'number' and initialize it to 5. This is the number whose factorial is to be calculated.
int number = 5;
// Declare an integer variable 'factorial' and initialize it to 1. This variable will hold the result of the factorial calculation.
int factorial = 1;
// Start a for loop with the loop variable 'i' initialized to 1.
for (int i = 1; i <= number; i++) {
// Multiply the current value of 'factorial' by 'i' and store the result back in 'factorial'.
factorial *= i; // This is equivalent to factorial = factorial * i;
}
// After the loop has completed, print the calculated factorial to the console.
System.out.println("Factorial of " + number + " is: " + factorial);
}
}
Output:
Factorial of 5 is: 120
Java Nested for Loop
When a for loop is placed inside another loop, it is referred to as a nested for loop. The inner loop runs in its entirety every time the outer loop runs.
Utilizing nested for loops enables the execution of intricate iterations by iterating through a for loop within each iteration of the outer for loop. This technique proves valuable when handling multi-dimensional data structures such as arrays or when conducting tasks that demand multiple layers of looping, like creating a matrix or table.
Syntax of the Java Nested for Loop
It has the following syntax:
for (initialization; termination; increment) {
// Outer loop block
for (initialization; termination; increment) {
// Inner loop block
}
}
Nested for Loop Example 1: Demonstrating Loop inside Loop
In this section, we will illustrate the concept of nested for loops in Java with an example.
Example
//Java program to understand the use of nested for loop
public class Main {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Nested for Loop Example 2: Printing Left-Aligned Star Triangle
In this instance, we will demonstrate how to create a triangle of stars aligned to the left by utilizing a nested for loop.
Example
//Java program to print pyramid using for loop
public class Main {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *
Nested for Loop Example 3: Printing Inverted Right-Angled Star Pyramid
In this instance, we will demonstrate how to create an inverted right-aligned triangle made of stars by utilizing a nested for loop.
Example
//Java program to print pyramid or star pattern using for loop
public class Main {
public static void main(String[] args) {
int term=6;
for(int i=1;i<=term;i++){
for(int j=term;j>=i;j--){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Output:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Java for-each Loop
The for-each construct in Java is utilized for iterating over an array or a collection. It offers a simpler alternative to the traditional for loop as it eliminates the need for manually incrementing a value and utilizing subscript notation.
The functionality operates by focusing on elements rather than indexes. It retrieves each element individually and assigns it to the specified variable.
Syntax of the Java for-each Loop
It has the following syntax:
for(data_type variable : array_name){
//code to be executed
}
for each Loop Example: Printing Array Elements
Let's illustrate how to display elements of an array in Java with an example.
Example
//Java For-each loop example which prints the
//elements of the array
public class Main {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12
23
44
56
78
Java Labelled for Loop
In Java, a labeled for loop is a loop that has been given a specific identifier. Labels in Java serve as markers for a code block, enabling the ability to break out of or continue an outer loop from inside a nested loop. This functionality becomes valuable when dealing with nested loops and needing to manage the behavior of the outer loop within an inner loop. Labels improve the control flow within intricate loop arrangements, enabling more accurate and adaptable loop handling.
Each Java for loop can be assigned a name by using a label preceding the loop declaration. This feature comes in handy when working with nested for loops, allowing for the ability to break or continue a specific loop within the nested structure.
Note: The break and continue keywords breaks or continues the innermost for loop respectively.
Syntax of the Java Labelled for Loop
It has the following syntax:
labelname:
for(initialization; condition; increment/decrement){
//code to be executed
}
Example 1:
Consider the following example to illustrate the Java labeled for loop.
Example
//A Java program to demonstrate the use of labeled for loop
public class Main {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
Example 2:
When utilizing the statement break followed by the label bb;, it will specifically terminate the inner loop, adhering to the typical behavior of loops.
Example
public class Main {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Java Infinitive for Loop
In Java, an infinite for loop is a loop that lacks a termination condition or has a condition that is perpetually true. This results in the loop executing endlessly until it is halted manually by the user, through a break statement, or due to an exception being thrown. These loops are employed when there is a need to establish a loop that runs continuously until an external factor or user input prompts its cessation.
When a pair of semicolons (;;) is utilized within a for loop, it creates an infinite loop.
Syntax of the Java Infinitive for Loop
It has the following syntax:
for(;;){
//code to be executed
}
Example: Java infinitive for Loop
Let's illustrate the Java infinite for loop with an example.
//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println("infinitive loop");
}
}
}
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
Next, in order to exit the program, we should press the Ctrl+C key combination.
Java for Loop vs while Loop vs do-while Loop
Distinguishing Java's for loop, while loop, and do-while loop reveals various dissimilarities. Here are some contrasts:
| Comparison | for loop | while loop | do-while loop |
|---|---|---|---|
| Introduction | The Java for loop is a control flow statement that iterates a part of theprogramsmultiple times. | The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition. | The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition. |
| When to use | If the number of iteration is fixed, it is recommended to use for loop. | If the number of iteration is not fixed, it is recommended to use while loop. | If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop. |
| Syntax | for(init;condition;incr/decr){// code to be executed} | while(condition){//code to be executed} | do{//code to be executed}while(condition); |
| Example | //for loopfor(int i=1;i<=10;i++){System.out.println(i);} | //while loopint i=1;while(i<=10){System.out.println(i);i++;} | //do-while loopint i=1;do{System.out.println(i);i++;}while(i<=10); |
| Syntax for infinitive loop | for(;;){//code to be executed} | while(true){//code to be executed} | do{//code to be executed}while(true); |