JavaControl Statements

Loops in Java

Learn Java loops to execute code repeatedly, including for loop, while loop, do-while loop, syntax, flow, examples, and best practices.

Loops in JavaLink to this section

Loops in Java are control statements that allow a block of code to be executed multiple times based on a condition. They help reduce code duplication and make programs efficient and readable.

Loops are widely used for tasks such as iterating over arrays, processing user input, and performing repeated calculations.

Why Loops Are NeededLink to this section

Without loops, programmers would have to write the same code repeatedly. Loops automate repetition and improve performance.

Examples of loop usage:
  • Printing numbers from 1 to 100
  • Traversing arrays and collections
  • Validating input until it is correct

Types of Loops in JavaLink to this section

p> Java provides three main types of loops:

  • for loop
  • while loop
  • do-while loop

for LoopLink to this section

p> The for loop is used when the number of iterations is known in advance. It consists of initialization, condition, and update expressions.

tip

Use for loop when iteration count is fixed or predictable.

while LoopLink to this section

The while loop executes a block of code as long as the condition remains true. The condition is checked before each iteration.

warning

Forgetting to update the loop variable can cause an infinite loop.

do-while LoopLink to this section

The do-while loop executes the loop body at least once, even if the condition is false. The condition is checked after the loop body.

note

do-while is useful when the loop must run at least once.

Infinite LoopsLink to this section

An infinite loop occurs when the loop condition never becomes false. While sometimes intentional, it can cause program crashes if not handled properly.

Loops in Java
Question 1 of 5

Which loop is best when the number of iterations is known beforehand?

Loops in Java

medium
  1. Write a program to print all even numbers between 1 and 50 using a loop.
  2. Create a program that calculates the factorial of a number using a for loop.
  3. Use a while loop to reverse a number.
  4. Write a do-while loop that asks the user for input until a valid value is entered.
  5. Modify an infinite loop so that it stops when a specific condition is met.