Loops in Java

Level : Beginner
Mentor: Shailendra Chauhan
Duration : 00:03:00

What are Loop Statements in Java?

In Java, loops are used to iterate over a block of statements a set number of times or until a specific condition evaluates to false, allowing the code to be executed continuously until the provided expression becomes false.

Types of Loop Statements

Java supports the following types of looping statements:

  • While loop
  • Do-while loop
  • For loop
  • Foreach loop

While Loop

The while loop executes a block of statements until the provided expression evaluates to false. It is useful when you don't know the exact number of iterations.

While loop flowchart

  • Test Condition.
  • Statement execution.
  • Loop termination.

Do-While Loop

A do-while loop is used to repeatedly execute a block of statements at specific intervals. It continues to execute until the given expression evaluates to false.

Do-While loop flowchart

  • Statement execution.
  • Test Condition.
  • Loop termination.

For Loop

Index declaration, condition, and update statement are the three sections that make up a for loop. Typically, a for loop is beneficial when you know the number of iterations.

For loop flowchart

  • Initialization condition.
  • Test Condition.
  • Statement execution.
  • Update Statement.
  • Loop termination.

ForEach Loop

In Java, the foreach loop is mostly used to traverse an array or collection. It reduces the possibility of problems and improves code readability. Traverses each element one by one.


Infinite loops in Java

Infinite for loop in Java

An infinite for loop is created if the for loop condition remains true or if the programmer fails to apply the test condition/terminating statement within the for loop statement.

Infinite while loop in Java

If a loop's condition is always true, the loop will be infinite.

Infinite do-while loop in Java

It's formed when the test condition remains true.

Nested Loops in Java

Nested for loop in Java

It refers to any loop that is contained within a for loop.


Nested While Loop in Java

It refers to any loop that is contained within a while loop.


Nested Do-While Loop in Java

It is a do...while loop within another do...while loop.

Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this