For loop In Java: Syntax, Flowchart, and Practical Examples

A for loop in Java is a looping statement that executes a block of code repeatedly for a specified number of times.

For loop is a popular and convenient loop. The for loop is used in situations where the coder or programmer knows in advance how many times the statement will be executed.

Unlike while and do while, variable initialization, condition checking, and increment or decrement operations can all be done in the same statement in a for loop.

This means, 3 loop control elements (initialization expression, test condition, and increment/decrement expression) are present in one location(for loop).

Syntax

for (initialization; condition; update) {
    // Code to be executed
}

Explanation:

  1. Syntax starts with a for keyword.
  2. initialization is used to initialize the loop variable followed by a semicolon (;). The loop variable is the local variable of the for loop. we can not access the loop variable (local variable) outside the for loop.
  3. condition is used to check the test condition followed by a semicolon (;).
  4. update is used for increment and decrement operations.
  5. Three expressions are separated by a semicolon(;) in the for loop header.
  6. After that {} curly braces are used.
Note : The variable in a for-loop is initialized only once, before the loop runs for the first time.

Flowchart

flowchart for loop in java

let’s understand the for-loop flowchart with the help of the explanation below:

Explanation:

  1. The first control starts from the top of the flowchart.
  2. Then, the control moves to the initialization part, Here variable initialization is done.
  3. After variable initialization control goes to the test condition part and checks the condition, if the condition is true then the body of the loop (code inside for loop) will be executed.
  4. When the body of the loop is executed successfully then control goes to the increment/decrement expression. After the increment/decrement expression control goes to the test condition for checking the condition. If the condition is true again then the same process repeats again until the condition becomes false.
  5. When the condition becomes false then the control skips the loop body and goes to the next statement in the program.

For Loop and Its Optional Parts in Java

All three expressions (initialization expression, test condition, and increment/decrement expression) in the for loop are optional. we can remove these expressions from the for-loop header.

for loop optional parts
  • Initialization expression (for-loop local variable) can be removed if the variable has already been initialized earlier in the program.
  • If the test condition is omitted then the for-loop becomes an infinite loop in java. In that case, we use a break statement or throw an exception to stop the loop.
  • Increment and decrement expressions can be removed if not required. If it is required then we can place that expression(i++) inside the body loop.
Note : Semicolon(;) is necessary. We can not remove semicolon from the for-loop header.

We can write for-loop in Java in different ways without any errors. See example below:

different ways of writing for loop in java

Sample for-loop Program in Java

public class SampleForLoopProgram {
    public static void main(String[] args) {
        // For loop to print numbers from 1 to 15
        for (int j = 1; j <= 15; j++) {
            System.out.println("Number is: " + j);
        }
    }
}

Explanation:

  1. Our class name is SampleForLoopProgram, This is called class declaration.
  2. public static void main(String[] args) is the main method, Execution starts from the main method.
  3. Then control jumps to the for-loop header for(int j=1; j<=15; j++)
  4. First, the initialization part int j=1; value of j is 1.
  5. j is initialized only once then the control moves to the test condition(j<=15) and checks the condition (1<=15), which means true.
  6. Condition is true then the loop body System.out.println statement executes and prints the value Number is 1.
  7. After the loop body execution is complete, the control moves to the update expression j++
  8. Increment the value of j now the value of j is 2 and the control moves to the condition expression and checks the condition and the condition is (2<=15) again true, again loop body executes.
  9. This process repeats until the condition becomes false.
  10. When the condition becomes false then the loop body will be skipped and the control moves to the next statement in the program if present.

Output:

Output
Number is: 1
Number is: 2
Number is: 3
Number is: 4
Number is: 5
Number is: 6
Number is: 7
Number is: 8
Number is: 9
Number is: 10
Number is: 11
Number is: 12
Number is: 13
Number is: 14
Number is: 15

Program Reverse a string in Java using for loop

public class ReverseStringProgram {
    public static void main(String[] args) {
       String originalString = "moc.yarhcetia";
       String reversedString = "";

        // Loop through the string from end to start
        for (int j = originalString.length() - 1; j >= 0; j--) {
            reversedString += originalString.charAt(j);
        }

        System.out.println("The Original String is: " + originalString);
        System.out.println("The Reversed String is: " + reversedString);  
        }
}

Explanation:

  1. In this program we have two variables, one is the originalString with the value “moc.yarhcetia" and the second is the reveresedString with no value (empty).
  2. In this for loop, variable j is initialized with the value originalString.length()-1 means 12.
  3. length() is the function, this function gives the length of the string, moc.yarhcetia string total length is 13.
  4. In string, characters start from 0 index which means m is on 0 index, o is on 1 index, c is on 2 index, and so on, that’s why value 1 is minus from the total length of originalString.length()-1 means 12.
  5. Now the value of j is 12 after the initialization, the condition is checked and the test condition is (12>=0) which means true.
  6. Condition true and control moves to the body of the loop.
  7. In the loop body, originalString.charAt(j) evaluated, charAt() is a function that returns the character at the specified index in the string and the value is “a” because the value of j is 12 and on 12 index character “a” is present.
  8. After originalString.charAt(j) evaluation, value is assigned to the variable reversedString with the help of the addition assignment operator (+=). It is used to add a value to a variable and then assign the result back to that variable.
  9. After loop body execution is complete the control moves to the decrement expression j– and decrement the value of j now the value is 11 and the control moves to the condition now the condition is (11>=0) which means true.
  10. Again loop body executes until the condition becomes false.
  11. At the end, print the values.
Note :In this program, for loop starts from the end value that’s why we use a decrement expression(j- -).

Output:

Output
The Original String is: moc.yarhcetia
The Reversed String is: aitechray.com

If you want to make an infinite loop in Java with the help of a for loop then use the below program

Program infinite for loop in Java

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

Explanation:

  1. All expressions in the for loop header are left blank.
  2. If we omit the condition from the for-loop, then it becomes an infinite loop, running continuously without stopping.
Note :To stop an infinite loop, use Ctrl+C in the terminal or add a break statement in the loop based on certain conditions.

Conclusion

The for loop in Java is a powerful tool for handling repetitive tasks and working with ranges of values efficiently. Mastering its use will help you write cleaner, more effective code. Practice with different examples and explore additional resources to strengthen your skills and apply them to real-world programming challenges.

We’d Love to Hear From You!

Do you have questions or feedback about the for loop in Java? We’re here to help! Whether you need further clarification, have suggestions, or just want to share your thoughts, please leave a comment below. Your feedback is invaluable in helping us improve our content and support others. Don’t hesitate to reach out—we’re excited to hear from you!

Related Articles:

While Loop In Java: Syntax, Flowchart, and Practical Examples

do while loop in Java: Syntax, Flowchart, and Practical Examples

Additional Resources

For more information on Java for loops and other control flow statements, check out the official Java Documentation. It provides clear explanations and examples to help you understand how to use these features effectively.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Aitechray