Java For Loop

Home / Core Java / Java For Loop

Java For Loop


Java For Loop :

The for loop in Java is a fundamental control flow structure that allows you to execute a block of code repeatedly. It's particularly useful when you know the number of iterations you want to perform.

Syntax:

The syntax of a for loop in Java looks like this :

  • initialization:  It's typically used to initialize a counter variable. This part is executed only once before the loop begins.
  • condition:  It's a boolean expression that is evaluated before each iteration. If true, the loop continues; if false, the loop terminates
  • update:  It's used to update or increment the counter variable. This part is executed at the end of each iteration, just before re-evaluating the condition
  • The code inside the curly braces {} is the body of the loop, containing the code that will be executed repeatedly as long as the condition remains true.


Example:

Let's consider an example to understand the for loop in action:

In this example:

  • int i = 1 initializes the variable i to 1.
  • i <= 5 is the condition that checks if i is less than or equal to 5.
  • i++ increments i by 1 after each iteration.

The loop will execute five times. During each iteration, "Count is: " followed by the value of i will be printed. Once i becomes 6 (i.e., i <= 5 condition becomes false), the loop stops.


Key Points:

  • Initialization, Condition, and Update: The for loop brings together the initialization of the loop variable, the condition to check for each iteration, and the way to update the loop variable in a single line.
  • Predefined number of iterations: It's ideal when you know the number of times you want to execute a block of code.
  • Versatility: The for loop is very versatile and flexible, allowing complex conditions and expressions in each part (initialization, condition, and update).

It's essential to avoid infinite loops by ensuring that the condition provided in the for loop will eventually become false to exit the loop. The for loop is widely used in various programming scenarios due to its concise and structured nature.