View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Looping Statements in Java: Types, Syntax, Examples & Best Practices

Updated on 25/04/20254,885 Views

Introduction to Looping Statements in Java

Looping statements in Java Programming help execute code blocks repeatedly based on conditions. Java offers four main loop types: while loop, do-while loop, for loop, and for-each loop, each with specific syntax and use cases for efficient programming.

Enhance your Java skills with expert-led training. Check out upGrad’s Software Engineering course and learn how to apply Java in real-world projects.

What is looping statement in Java?

Looping statements in Java are essential control flow structures that execute a block of code repeatedly based on conditions. These statements help create efficient, clean code by eliminating redundancy.

Java loops optimize program performance by:

  • Reducing code repetition
  • Processing collections efficiently
  • Automating repetitive tasks
  • Managing data structures systematically
  • Controlling program flow dynamically

Different programming scenarios require different types of looping statements. The right loop choice depends on your specific requirements, expected iterations, and condition evaluation needs.

Loop Type

Initial Condition Check

Minimum Executions

Best For

While

Before execution

0

Unknown iterations

Do-While

After execution

1

Menu systems, input validation

For

Before execution

0

Known iterations

For-Each

N/A

0

Collection traversal

Java developers are in high demand—especially with cloud and DevOps skills. Gain both with this Professional Certificate Program by upGrad.

Types of Loops in Java

Java offers four main types of looping statements in Java. Each has unique characteristics suited for different programming needs.

While Loop in Java

The while loop in Java is a pre-test loop that checks a condition before executing the loop body. It repeats until the condition becomes false.

While Loop Syntax in Java

while (condition) {
    // Code to be executed
}

Example of While Loop in Java

// Problem: Print numbers from 1 to 5 using while loop in Java
public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 1;  // Initialize counter
        
        while (i <= 5) {  // Check condition before executing loop body
            System.out.println(i);  // Print current value
            i++;  // Increment counter
        }
    }
}

Output:

1

2

3

4

5

The while loop first checks if the condition is true, then executes the code block. The loop continues until the condition becomes false.

Take your Java knowledge to the next level. Explore the Executive Diploma in Data Science & AI by IIIT-B to dive into machine learning, AI, and analytics.

Do-While Loop in Java

The do-while loop in Java is a post-test loop. It executes the code block at least once before checking the condition.

Do-While Loop Syntax in Java

do {
    // Code to be executed
} while (condition);

Example of Do-While Loop in Java

// Problem: Create a simple menu system that runs at least once
import java.util.Scanner;

public class DoWhileLoopExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice;
        
        do {
            // Display menu options
            System.out.println("1. Option One");
            System.out.println("2. Option Two");
            System.out.println("3. Exit");
            System.out.print("Enter your choice: ");
            
            choice = scanner.nextInt();  // Get user input
            
            // Process user choice
            System.out.println("You selected option " + choice);
            
        } while (choice != 3);  // Continue until user chooses to exit
        
        System.out.println("Program terminated.");
        scanner.close();
    }
}

Output:

1. Option One

2. Option Two

3. Exit

Enter your choice: 1

You selected option 1

1. Option One

2. Option Two

3. Exit

Enter your choice: 3

You selected option 3

Program terminated.

The do-while loop guarantees that the menu is displayed at least once, making it perfect for menu-driven applications.

For Loop in Java

The for loop in Java provides a compact way to iterate when you know the number of iterations in advance.

For Loop Syntax in Java

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

Example of For Loop Program in Java

// Problem: Calculate sum of first n natural numbers
public class ForLoopExample {
    public static void main(String[] args) {
        int n = 5;
        int sum = 0;
        
        // For loop to calculate sum
        for (int i = 1; i <= n; i++) {
            sum += i;  // Add current number to sum
        }
        
        System.out.println("Sum of first " + n + " natural numbers is: " + sum);
    }
}

Output:

Sum of first 5 natural numbers is: 15

The for loop efficiently calculates the sum by initializing, checking conditions, and updating in a single line.

For-Each Loop in Java

The for-each loop (enhanced for loop) in Java simplifies iterating through arrays and collections.

For-Each Loop Syntax in Java

for (dataType item : array/collection) {
    // Code to be executed
}

Example of For-Each Loop in Java

// Problem: Calculate average of elements in an array using for-each loop
public class ForEachLoopExample {
    public static void main(String[] args) {
        // Array of numbers
        int[] numbers = {5, 10, 15, 20, 25};
        
        int sum = 0;
        int count = 0;
        
        // For-each loop to iterate through array elements
        for (int number : numbers) {
            sum += number;  // Add current element to sum
            count++;  // Count elements
        }
        
        // Calculate and display average
        double average = (double) sum / count;
        System.out.println("Average of array elements: " + average);
    }
}

Output:

Average of array elements: 15.0

The for-each loop eliminates the need for index manipulation, making array traversal more readable and less error-prone.

Nested Loops in Java

Nested loops in Java occur when one loop is placed inside another. They're useful for working with multi-dimensional data structures or generating complex patterns.

// Problem: Print a multiplication table using nested loops
public class NestedLoopExample {
    public static void main(String[] args) {
        int size = 5;  // Size of multiplication table
        
        // Outer loop for rows
        for (int i = 1; i <= size; i++) {
            // Inner loop for columns
            for (int j = 1; j <= size; j++) {
                // Print product with formatting
                System.out.printf("%4d", i * j);
            }
            System.out.println();  // New line after each row
        }
    }
}

Output:

The nested loops work together to create the multiplication table. The outer loop controls rows while the inner loop handles columns.

When to Use Nested Loops in Java

  • Working with multi-dimensional arrays
  • Generating patterns and shapes
  • Matrix operations
  • Game board traversal
  • Complex data processing tasks

Infinite Loops in Java

Infinite loops continue indefinitely without termination. They can be intentional (for server processes) or accidental (logic errors).

// Examples of infinite loops in Java

// 1. While loop infinite loop
while (true) {
    // Code that never stops
    // Must include a break statement somewhere to exit
    if (exitCondition) {
        break;  // Safe exit strategy
    }
}

// 2. For loop infinite loop
for (;;) {
    // Code that runs forever
    if (exitCondition) {
        break;  // Safe exit point
    }
}

// 3. Do-while infinite loop
do {
    // Code that always executes
    if (exitCondition) {
        break;  // Exit mechanism
    }
} while (true);

Common Causes of Unintended Infinite Loops

Issue

Example

Prevention

Missing update

while (i < 10) { /* no i++ */ }

Always update counter variables

Incorrect condition

while (i >= 0) { i++; }

Ensure condition can become false

Logic errors

while (x != 10) { x += 2; } (when x starts at 1)

Test boundary conditions

Float comparison

while (x != 1.0) { x += 0.1; }

Use tolerance ranges for floats

To prevent unintended infinite loops:

  • Ensure proper condition initialization
  • Update loop variables correctly
  • Include valid termination conditions
  • Consider using break statements when needed
  • Implement timeout mechanisms for safety

Real-World Applications of Loops in Java

File Processing System

Problem Statement: A data processing application needs to read a large CSV file line by line, parse each record, and perform data validation before storage.

// Problem: Process CSV file data line by line
public class FileProcessor {
    public static void main(String[] args) {
        String filePath = "customer_data.csv";
        int validRecords = 0;
        int invalidRecords = 0;
        
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            boolean isHeader = true;
            
            // Use while loop to process unknown number of lines
            while ((line = reader.readLine()) != null) {
                if (isHeader) {
                    System.out.println("Processing file with header: " + line);
                    isHeader = false;
                    continue;
                }
                
                if (validateRecord(line)) {
                    processRecord(line);
                    validRecords++;
                } else {
                    logInvalidRecord(line);
                    invalidRecords++;
                }
            }
            
            System.out.println("Processing complete!");
            System.out.println("Valid records: " + validRecords);
            System.out.println("Invalid records: " + invalidRecords);
            
        } catch (IOException e) {
            System.err.println("Error processing file: " + e.getMessage());
        }
    }
    
    private static boolean validateRecord(String record) {
        // Validation logic here
        return record.split(",").length >= 3;
    }
    
    private static void processRecord(String record) {
        // Processing logic here
        System.out.println("Processed: " + record.substring(0, Math.min(20, record.length())) + "...");
    }
    
    private static void logInvalidRecord(String record) {
        // Logging logic here
        System.out.println("Invalid record: " + record);
    }
}

Output:

Processing file with header: id,name,email,purchase_amount

Processed: 1,Rajesh Kumar,raj...

Processed: 2,Priya Sharma,pri...

Invalid record: 3,Amit Patel

Processed: 4,Sunita Verma,sun...

Processing complete!

Valid records: 3

Invalid records: 1

This real-world example demonstrates using a while loop to process files of unknown size, a common application in data processing systems. The while loop is perfect here because we don't know how many records the file contains beforehand.

Inventory Management System

Problem Statement: A retail store needs to process their inventory items, calculate the value of each product line, and determine the total inventory value for accounting purposes.

// Problem: Process inventory items and calculate total value
public class InventorySystem {
    public static void main(String[] args) {
        // Product inventory (name, price, quantity)
        String[] productNames = {"Laptop", "Phone", "Tablet", "Monitor", "Keyboard"};
        double[] prices = {45999.99, 32999.99, 15499.99, 12499.99, 2999.99};
        int[] quantities = {5, 10, 15, 8, 20};
        
        double totalInventoryValue = 0;
        System.out.println("INVENTORY REPORT");
        System.out.println("---------------");
        
        // Process each inventory item using for loop
        for (int i = 0; i < productNames.length; i++) {
            // Calculate value of current product line
            double lineValue = prices[i] * quantities[i];
            totalInventoryValue += lineValue;
            
            // Print product details
            System.out.printf("%-10s: %2d units × ₹%.2f = ₹%.2f\n", 
                productNames[i], quantities[i], prices[i], lineValue);
        }
        
        System.out.println("---------------");
        System.out.printf("Total Inventory Value: ₹%.2f\n", totalInventoryValue);
    }
}

Output:

INVENTORY REPORT

Laptop : 5 units × ₹45999.99 = ₹229999.95

Phone : 10 units × ₹32999.99 = ₹329999.90

Tablet : 15 units × ₹15499.99 = ₹232499.85

Monitor : 8 units × ₹12499.99 = ₹99999.92

Keyboard : 20 units × ₹2999.99 = ₹59999.80

Total Inventory Value: ₹952499.42

This real-world example demonstrates how loops efficiently process inventory data for business applications, calculating line values and totals without repetitive code.

Common Loop Applications in Java

Application

Best Loop Type

Example Use Case

Array Processing

For/For-each

Iterating through elements

Collection Traversal

For-each

Processing list items

File Reading

While

Reading lines until EOF

Menu Systems

Do-while

Displaying options at least once

Database Operations

For

Processing query results

Pattern Generation

Nested For

Creating visual patterns

Event Handling

While

Waiting for user events

Conclusion

Looping statements in Java are like tools in a toolbox - each has its own purpose. The while loop checks conditions first, do-while ensures code runs at least once, for loop is great when you know how many times to repeat, and for-each makes working with collections easy.

Learning these loops is like learning to ride different bicycles - once you master them, you can tackle any problem efficiently. The key is knowing which loop fits which situation. With practice, you'll write cleaner code that runs faster and solves complex problems step by step.

Next time you need to repeat code, remember that loops are your best friends. They save time, reduce mistakes, and make your programs work smarter, not harder. Start with simple examples, practice regularly, and soon you'll be looping like a pro!

FAQs

1. What is looping statement in Java?

Looping statements in Java are control flow structures that execute code repeatedly based on conditions. They reduce redundancy and increase efficiency in programs. Think of loops as shortcuts that help you avoid writing the same code multiple times, making your programs shorter and easier to maintain.

2. What is while loop in Java?

The while loop in Java executes code repeatedly as long as a condition remains true. It checks the condition before executing the loop body. It's like checking if it's raining before deciding to take an umbrella - if the condition is false initially, the loop code never runs even once.

3. What is do-while loop in Java?

The do-while loop in Java executes code at least once before checking the condition, making it ideal for scenarios requiring guaranteed execution. It's similar to trying a new recipe first and then deciding if you want to make it again so, you always cook it at least once regardless of your future decision.

4. What is for-each loop in Java?

The for-each loop in Java simplifies collection traversal by automatically accessing each element without requiring explicit indexing. It's like going through each book on your shelf without needing to count their positions & you just handle one book at a time until you've seen them all.

5. What is the difference between while and do-while loop in Java?

While loop checks conditions before execution and may skip entirely. Do-while executes at least once before checking conditions. This is similar to the difference between "Look before you leap" (while) and "Try it first, then decide" (do-while) approaches to problem-solving.

6. What is the do-while loop syntax in Java?

The do-while loop syntax in Java is:

do {
    // Code to be executed
} while (condition);

Note that unlike other loops, do-while requires a semicolon after the condition. The structure ensures the code block executes before the condition is evaluated, guaranteeing at least one execution cycle.

7. How do I choose which loop to use in Java?

Use for loops for known iterations, while loops for condition-based repetition, do-while for at-least-once execution, and for-each for collections. Your choice depends on whether you know the number of iterations in advance and whether the loop body should always execute at least once.

8. Can loops be nested in Java?

Yes, loops can be nested in Java by placing one loop inside another, allowing for complex iterations like matrix traversal or pattern generation. Think of nested loops like a clock - the minute hand (inner loop) completes a full cycle for each movement of the hour hand (outer loop).

9. How do I break out of a loop in Java?

Use the break statement to exit a loop immediately. The continue statement can skip the current iteration and proceed to the next one. These control statements give you fine-grained control over loop execution, letting you handle special cases or early termination conditions efficiently.

10. What is an infinite loop in Java?

An infinite loop in Java continues indefinitely because its termination condition never becomes false. It can be created using while(true) or for(;;). While sometimes useful for server processes, infinite loops are often the result of logical errors and can cause programs to freeze or crash.

11. How can I optimize loops for large datasets in Java?

Optimize by minimizing operations inside loops, using appropriate collections, avoiding unnecessary object creation, and considering parallel streams. For very large datasets, consider batch processing, lazy evaluation techniques, or database-specific optimization strategies like indexed queries.

12. Why does my for loop not execute?

Your for loop might not execute if the initial condition is false. For example, for(int i=10; i<5; i++) will never run because 10 is not less than 5. Always check your loop conditions and initialization values, especially when loops appear to be skipped entirely during execution.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.