For Loop

The for loop in Java is one of the most commonly used loops. It’s ideal when you know in advance how many times you need to iterate through a block of code.

Syntax

  • Initialization: Initializes a variable, executed once at the beginning.
  • Condition: Expression evaluated before each iteration. If it’s true, the loop continues; if false, it stops.
  • Update: Updates the variable after each iteration.

Types of for loops

  • Basic for Loop: Used when the number of iterations is known ahead of time.

Output

  • Basic for Loop to iterate over Arrays: An index is used variable to access each element of the array.

Output

  • Enhanced for Loop (for-each loop): Used to iterate through arrays or collections.

Output

  • Infinite for Loop: An infinite for loop is typically used in scenarios where you need the loop to run continuously until some external condition occurs, such as a user input, a specific event, or a system signal to break the loop. It’s commonly used in:
    • Server Applications: For waiting and handling incoming requests continuously (e.g., a web server listening for requests).
    • Game Loops: In games, where the loop continues to run until the game ends or the user decides to quit.
    • Monitoring Systems: For constantly checking sensors or user inputs without a predetermined stop condition.
    • Embedded Systems: Often used in microcontrollers and devices where the program runs continuously and only stops when manually reset or powered off.