Introduction to Java Loops for Beginners

Sep 19, 2024

Java Series for Beginners: Loops

Introduction to Loops

  • Loops make Java dynamic by allowing code to repeat.
  • Different actions can be performed on each iteration.

Types of Loops in Java

1. While Loop

  • Syntax: Similar to the if statement.
    while (condition) {
        // code to be repeated
    }
    
  • Functionality:
    • Uses a boolean condition.
    • Repeats the code block as long as the condition is true.
    • Example: Infinite loop using while (true).
    • Practical example: Incrementing a variable until it reaches a value.

Example:

int a = 0;
while (a < 100) {
    System.out.println(a);
    a++;
}
System.out.println("Loop finished");
  • Prints numbers from 0 to 99 and then outputs "Loop finished".

2. For Loop

  • Syntax:
    • Takes three parameters: initialization, condition, and increment/decrement.
    for (initialization; condition; increment/decrement) {
        // code to be executed
    }
    
  • Functionality:
    • Initializes a variable, checks a condition, and increments/decrements in one line.
    • Useful for iterating over arrays.

Example:

for (int a = 0; a < 100; a++) {
    System.out.println(a);
}
  • Prints numbers from 0 to 99.
  • Increment can use a += 2 to skip numbers.

3. Do-While Loop

  • Syntax:
    do {
        // code to be executed
    } while (condition);
    
  • Functionality:
    • Ensures the code inside runs at least once, regardless of the condition.
    • Condition is checked after the code runs.

Example:

int a = 10;
do {
    System.out.println("Hello World");
} while (a < 10);
  • Prints "Hello World" once even if the condition a < 10 is false.

Summary

  • While Loop: Repeats as long as the condition is true, checks condition first.
  • For Loop: Combines initialization, condition, and increment in one line.
  • Do-While Loop: Executes code at least once before checking the condition.

Understanding these loops allows for creating dynamic and flexible Java programs.