🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

Java Looping Statements with Examples  


Introduction

  • Looping Statements are also know as "Iteration Statements".
  • Looping Statements allow us to repeat a block of code multiple times, making our programs more efficient and reducing redundancy.
  • Loops are essential for handling repetitive tasks like:
    • printing data multiple times
    • executing tasks until a specific condition is met
    • iterating through arrays
    • and many more....
  • Examples of Looping Statements in Java:
    1. for: Repeats a block of code a specific number of times.
    2. while: Executes a block of code as long as a specified condition is true.
    3. do-while: Executes a block of code once, then repeats it as long as the condition is true.
    4. for-each (Enhanced For Loop): Iterates over elements in an array or collection.
    These are explained deeply as below:

"for" Loop in Java
  • The for loop is used to repeat a block of code a specific number of times.
  • The for loop is useful when the number of iterations is known beforehand (i.e. we know exactly how many times we need to repeat a task), like when working with arrays or running a piece of code a specific number of times.
  • Syntax:
    for (initialization; condition; increment/decrement)
    {
        // statements (code to execute)
    }
    
  • Below is syntax explanation:
    • Initialization: Variable is initialized before the loop starts. This part runs only once at the beginning.
    • Condition: Checks the condition before each iteration. If the condition is true, the loop continues to execute the for block statements.
    • Increment/Decrement: Updates the loop variable, helping the loop move toward finishing.
    • Statements: Statements which are executed when the for loop condition is true.
  • Program:
    public class ForLoopExample
    {
        public static void main(String[] args)
        {
            // Print numbers from 1 to 5 using a for loop
            for (int i = 1; i <= 5; i++)
            {
                System.out.println("Number: " + i);
            }
        }
    }
    Output:
    Number: 1
    Number: 2
    Number: 3
    Number: 4
    Number: 5

"while" Loop in Java
  • The while loop is used to repeat a block of code as long as a specific condition is true.
  • The while loop is useful when we don’t know how many times we need to repeat the task, and the loop will continue as long as the condition holds true.
  • Syntax:
    while (condition)
    {
        // statements (code to execute)
    }
  • Below is syntax explanation:
    • Condition: Checks the condition before each iteration. If the condition is true, the loop continues to execute the while block statements.
    • Statements: The statements inside the loop are executed repeatedly as long as the condition remains true.
  • Program:
    • Task : Print all the even numbers between 1 and 17
    • Solution : Since we don't know the exact number of even numbers within this range, we should avoid using a for loop and instead use a while loop.
    public class WhileLoopExample
    {
        public static void main(String[] args)
        {
            int no = 2; // Start from the smallest even number
    
            while (no <= 17)
            {
                System.out.println("Even Number: " + no);
    
                no = no + 2; // Skip directly to the next even number
            }
        }
    }
    Output:
    Even Number: 2
    Even Number: 4
    Even Number: 6
    Even Number: 8
    Even Number: 10
    Even Number: 12
    Even Number: 14
    Even Number: 16

"do-while" Loop in Java
  • The do-while loop is used to repeat a block of code at least once and then repeatedly as long as the condition is true.
  • The do-while loop is useful when we want the code to run at least once, even if the condition is false initially.
  • Syntax:
    do
    {
        // statements (code to execute)
    } while (condition);
  • Below is syntax explanation:
    • Statements: The block of code that will be executed at least once, regardless of the condition.
    • Condition: After executing the statements, the condition is checked. If it evaluates to true, the loop continues to execute the statements. If it's false, the loop terminates.
  • Program:
    • Task : The user will provide an input, and we need to check whether it is a positive or negative number.
    • Solution : Since the user will always provide input, we need to check the number. We have to ensure that the code for taking input is always executed first, so we have to use do-while loop.
    import java.util.Scanner;
    
    public class DoWhileExample
    {
        public static void main(String[] args)
        {
            Scanner scanner = new Scanner(System.in);
            int number;
    
            // Prompting user for a positive number
            do
            {
                System.out.print("Enter a positive number: ");
                number = scanner.nextInt();
            } while (number <= 0);
    
            System.out.println("You entered a valid positive number: " + number);
        }
    }
    Here we have used Scanner class for User Input, Click Here to read Scanner Class deeply with Program.
    Output:
    Enter a positive number: -20
    Enter a positive number: 0
    Enter a positive number: 5
    You entered a valid positive number: 5

"for-each" Loop (Enhanced For Loop) in Java
  • The for-each loop (also called Enhanced For Loop) in Java is used to iterate over elements in an array or collection without needing an index variable.
  • It's commonly used when we don’t need to know the index of the element and simply want to process each element in the collection.
  • Syntax:
    for (dataType variable : collection)
    {
        // statements (code to execute)
    }
  • Below is syntax explanation:
    • dataType: Specifies the type of the elements in the collection (e.g. int, String).
    • variable: Represents each element in the collection during each iteration.
    • collection: The array or collection (i.e. List, Set etc.) we want to iterate over.
  • Program:
    public class EnhancedForLoopExample
    {
        public static void main(String[] args)
        {
            String[] fruits = {"Apple", "Banana", "Cherry"};
    
            // Using Enhanced For Loop (For-each loop)
            for (String fruit : fruits)
            {
                System.out.println(fruit);
            }
        }
    }
    Output:
    Apple
    Banana
    Cherry
  • Advantages:
    • Simplifies code by removing the need to manually manage the loop index.
    • Suitable for iterating over arrays and collections.
    • Helps avoid ArrayIndexOutOfBoundsException by iterating directly over elements.