Open In App

For Loop in Java

Last Updated : 13 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Let us understand Java for loop with Examples.

For Loop in Java

 

Syntax:  

for (initialization expr; test expr; update exp)
{
// body of the loop
// statements we want to execute
}

Parts of Java For Loop

Java for loop is divided into various parts as mentioned below:

  • Initialization Expression
  • Test Expression
  • Update Expression

1. Initialization Expression

In this expression, we have to initialize the loop counter to some value. 

Example:  

int i=1;

2. Test Expression

In this expression, we have to test the condition. If the condition evaluates to true then, we will execute the body of the loop and go to the update expression. Otherwise, we will exit from the for a loop.

Example:  

i <= 10

3. Update Expression:

After executing the loop body, this expression increments/decrements the loop variable by some value. 

Example:  

i++;

How does a For loop work?  

  1. Control falls into the for loop. Initialization is done
  2. The flow jumps to Condition
  3. Condition is tested. 
    • If the Condition yields true, the flow goes into the Body
    • If the Condition yields false, the flow goes outside the loop
  4. The statements inside the body of the loop get executed.
  5. The flow goes to the Updation
  6. Updation takes place and the flow goes to Step 3 again
  7. The for loop has ended and the flow has gone outside.

Flow Chart For “for loop in Java”

Flow chart for loop in Java

Flow chart for loop in Java

Examples of Java For loop

Example 1: (This program will print 1 to 10)

Java




/*package whatever //do not write package name here */
// Java program to write a code in for loop from 1 to 10
 
class GFG {
    public static void main(String[] args)
    {
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}


Output

1
2
3
4
5
6
7
8
9
10


Example 2: This program will try to print “Hello World” 5 times.  

Java




// Java program to illustrate for loop
class forLoopDemo {
    public static void main(String args[])
    {
        // Writing a for loop
        // to print Hello World 5 times
        for (int i = 1; i <= 5; i++)
            System.out.println("Hello World");
    }
}


Output

Hello World
Hello World
Hello World
Hello World
Hello World


The complexity of the method:

Time Complexity: O(1)
Auxiliary Space : O(1)

Dry-Running Example 1

The program will execute in the following manner. 

  1. Program starts.
  2.  i is initialized with value 1.
  3. Condition is checked. 1 <= 5 yields true.
    1.   “Hello World” gets printed 1st time.
    2.   Updation is done. Now i = 2.
  4. Condition is checked. 2 <= 5 yields true.
    1.   “Hello World” gets printed 2nd time.
    2.   Updation is done. Now i = 3.
  5. Condition is checked. 3 <= 5 yields true.
    1.  “Hello World” gets printed 3rd time
    2.  Updation is done. Now i = 4.
  6. Condition is checked. 4 <= 5 yields true.
    1. “Hello World” gets printed 4th time
    2.  Updation is done. Now i = 5.
  7. Condition is checked. 5 <= 5 yields true.
    1.  “Hello World” gets printed 5th time
    2.   Updation is done. Now i = 6.
  8. Condition is checked. 6 <= 5 yields false.
  9. Flow goes outside the loop. Program terminates.

Example 3: (The Program prints the sum of x ranging from 1 to 20)  

Java




// Java program to illustrate for loop.
class forLoopDemo {
    public static void main(String args[])
    {
        int sum = 0;
 
        // for loop begins
        // and runs till x <= 20
        for (int x = 1; x <= 20; x++) {
            sum = sum + x;
        }
        System.out.println("Sum: " + sum);
    }
}


Output

Sum: 210


Nested For Loop in Java

Java Nested For Loop is a concept of using a for loop inside another for loop(Similar to that of using nested if-else). Let us understand this with an example mentioned below:

Java




// Java Program to implement
// Nested for loop
import java.io.*;
 
// Driver Class
class GFG {
    // main function
    public static void main(String[] args)
    {
        // Printing a 1 to 5 (5 times)
        // first loop
        for (int i = 1; i <= 5; i++) {
            // second loop
            for (int j = 1; j <= 5; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}


Output

1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 


To know more about Nested loops refer Nested loops in Java.

Java For-Each Loop

Enhanced For Loop or Java For-Each loop in Java is another version of for loop introduced in Java 5. Enhanced for loop provides a simpler way to iterate through the elements of a collection or array. It is inflexible and should be used only when there is a need to iterate through the elements in a sequential manner without knowing the index of the currently processed element.

Note: The object/variable is immutable when enhanced for loop is used i.e it ensures that the values in the array can not be modified, so it can be said as a read-only loop where you can’t update the values as opposed to other loops where values can be modified. 

Syntax: 

for (T element:Collection obj/array)
{
// loop body
// statement(s)
}

Let’s take an example to demonstrate how enhanced for loop can be used to simplify the work. Suppose there is an array of names and we want to print all the names in that array. Let’s see the difference between these two examples by this simple implementation: 

Java




// Java program to illustrate enhanced for loop
public class enhancedforloop {
 
    // Main Function
    public static void main(String args[])
    {
        // String array
        String array[] = { "Ron", "Harry", "Hermoine" };
 
        // enhanced for loop
        for (String x : array) {
            System.out.println(x);
        }
 
        /* for loop for same function
        for (int i = 0; i < array.length; i++)
        {
            System.out.println(array[i]);
        }
        */
    }
}


Output

Ron
Harry
Hermoine


Complexity of the above method:

Time Complexity: O(1)
Auxiliary Space : O(1)

Recommendation: Use this form of statement instead of the general form whenever possible. (as per JAVA doc.) 

Java Infinite for Loop

This is an infinite loop as the condition would never return false. The initialization step is setting up the value of variable i to 1, since we are incrementing the value of i, it would always be greater than 1 so it would never return false. This would eventually lead to the infinite loop condition.

Example:

Java




// Java infinite loop
class GFG {
    public static void main(String args[])
    {
        for (int i = 1; i >= 1; i++) {
            System.out.println("Infinite Loop " + i);
        }
    }
}


Output

Infinite Loop 1
Infinite Loop 2
...

There is another method for calling the Infinite loop

If you use two semicolons ;; in the for loop, it will be infinitive for a loop.

Syntax: 

for(;;){  
//code to be executed
}

Example:

Java




public class GFG {
    public static void main(String[] args)
    {
        for (;;) {
            System.out.println("infinitive loop");
        }
    }
}


Output

infinitive loop
infinitive loop
....

FAQs for Java for Loop

1. What is a for loop in Java?

For loop in Java is a type of loop used for the repetitive execution of a block code till the condition is fulfilled.

2. What is the syntax of for loop?

Syntax of for loop is mentioned below:

for (initialization expr; test expr; update exp)
{
// body of the loop
// statements we want to execute
}

3. Why is a for loop used?

For loop is used when we need to repeat the same statements for a known number of times.

Must Refer:



Previous Article
Next Article

Similar Reads

Difference Between for loop and Enhanced for loop in Java
Java for-loop is a control flow statement that iterates a part of the program multiple times. For-loop is the most commonly used loop in java. If we know the number of iteration in advance then for-loop is the best choice. Syntax: for( initializationsection ; conditional check ; increment/decrement section) { // Code to be executed } Curly braces i
5 min read
Difference between Open-Loop Control System and Closed-Loop Control System
Control System is a system in which the behavior of the system is determined by a differential equation. It manages the devices and the systems using control loops. There are Open-Loop Control System and Closed-Loop Control System. Open-Loop Control System is used in applications in which no feedback and error handling are required. It is simple an
3 min read
Time Complexity of a Loop when Loop variable “Expands or Shrinks” exponentially
For such cases, time complexity of the loop is O(log(log(n))).The following cases analyse different aspects of the problem. Case 1 : for (int i = 2; i &lt;=n; i = pow(i, k)) { // some O(1) expressions or statements } In this case, i takes values 2, 2k, (2k)k = 2k2, (2k2)k = 2k3, ..., 2klogk(log(n)). The last term must be less than or equal to n, an
1 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list. Create an empty list t
3 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened. Create an empty list to c
3 min read
Difference between for and do-while loop in C, C++, Java
for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. Syntax: for (initialization condition; testing condition; increment/decrement) { statement(s) } Flow
2 min read
Difference between for and while loop in C, C++, Java
In C, C++, and Java, both for loop and while loop is used to repetitively execute a set of statements a specific number of times. However, there are differences in their declaration and control flow. Let's understand the basic differences between a for loop and a while loop. for Loop A for loop provides a concise way of writing the loop structure.
5 min read
Java do-while loop with Examples
Loops in Java come into use when we need to repeatedly execute a block of statements. Java do-while loop is an Exit control loop. Therefore, unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Syntax: do { // Loop Body Update_expression } // Condition check while (test_expression); Note: The
5 min read
Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer one. Working: The first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. A break within either the inner or outer loop would i
2 min read
Generic For Loop in Java
When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes. In normal for loop, we write three statements : for( statement1; statement 2
4 min read
String Array with Enhanced For Loop in Java
Enhanced for loop(for-each loop) was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing arrays or collections. This loop also makes the code more readable and r
1 min read
Java while loop with Examples
Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. While loop in Java comes into use when we need to repeatedly execute a block of statements. The while loop is considered as a repeating if statement. If the number o
4 min read
For-each loop in Java
Prerequisite: Decision making in JavaFor-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. It starts with the keyword for like a normal for-loop.Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by
4 min read
For Loop in Java | Important points
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. In Java, just unlikely any programming language provides four ways for executing the loops namely while loop, for loop, for-each loop, do-while loop or we can call it basically three type
6 min read
Infinite Loop Puzzles in Java
Problem 1 : Insert code in the given code segments to make the loop infinite. class GFG { public static void main(String s[]){ /* Insert code here */ for (int i = start; i &lt;= start + 1; i++) { /* Infinite loop */ } } } Solution: It looks as though it should run for only two iterations, but it can be made to loop indefinitely by taking advantage
3 min read
How to Loop Over TreeSet in Java?
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.  Now the task
4 min read
Difference between while and do-while loop in C, C++, Java
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax : while (boolean condition){ loop statements...}Flowchart: Example: [GFGTABS] C++ #include &lt;iostream&gt; using namespace std; int main() { int i =
2 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
C++ While Loop
While Loop in C++ is used in situations where we do not know the exact number of iterations of the loop beforehand. The loop execution is terminated on the basis of the test condition. Loops in C++ come into use when we need to repeatedly execute a block of statements. During the study of the 'for' loop in C++, we have seen that the number of itera
3 min read
C++ Do/While Loop
Loops come into use when we need to repeatedly execute a block of statements. Like while the do-while loop execution is also terminated on the basis of a test condition. The main difference between a do-while loop and a while loop is in the do-while loop the condition is tested at the end of the loop body, i.e do-while loop is exit controlled where
3 min read
Print a 2D Array or Matrix using single loop
Given a matrix mat[][] of N * M dimensions, the task is to print the elements of the matrix using a single for loop. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}Output: 1 2 3 4 5 6 7 8 9 Input: mat[][] = {{7, 9}, {10, 34}, {12, 15}}Output: 7 9 10 34 12 15 Approach: To traverse the given matrix using a single loop, observe that there
5 min read
While loop with Compile time constants
While loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. It is mostly used in situations where the exact number of iterations beforehand. Below is the image to illustrate the while loop: Syntax: while(test_expression){ // state
6 min read
for Loop in C++
In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for the specified range of values. Basically, for loop allows you to repeat a set of instructions for a specific number of iterations. for loop is generally preferred over while and do-while loops in case the number of iterations is known beforehand. Syn
9 min read
Printing triangle star pattern using a single loop
Given a number N, the task is to print the star pattern in single loop. Examples:  Input: N = 9Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Input: N = 5Output: * * * * * * * * * * * * * * * Please Refer article for printing the pattern in two loops as:Triangle pattern in Java Approach 1:Approach:
10 min read
Print pattern using only one loop | Set 1 (Using setw)
Print simple patterns like below using single line of code under loop. Examples: Input : 5Output : * ** *** *********Input : 6Output : * ** *** **** ***********setw(n) Creates n columns and fills these n columns from right. We fill i of them with a given character, here we create a string with i asterisks using string constructor. setfill() Used to
4 min read
Output of C programs | Set 57 (for loop)
Prerequisite : for loop Q.1 What is the output of this program? #include &lt;iostream&gt; using namespace std; int main() { for (5; 2; 2) printf(&quot;Hello\n&quot;); return 0; } Options a) compilation error b) Hello c) infinite loop d) none of the above ans: c Explanation : Putting a non zero value in condition part makes it infinite. Q.2 What is
3 min read
How to print a number 100 times without using loop and recursion in C?
It is possible to solve this problem using loop or a recursion method but what if both are not allowed? A simple solution is to write the number 100 times in cout statement. A better solution is to use #define directive (Macro expansion) C/C++ Code // CPP program to print &amp;quot;1&amp;quot; 100 times. // Prints 1 only once #define a cout&amp;lt;
1 min read
Print a number 100 times without using loop, recursion and macro expansion in C?
It is possible to solve this problem using loop or a recursion method. And we have already seen the solution using #define directive (Macro expansion) but what if all three are not allowed? A simple solution is to write the number 100 times in cout statement. A better solution is to use concept of Concept of setjump and longjump in C. C/C++ Code //
1 min read