Loops in java

Loops in Java

April 6th, 2026
1119
15:00 Minutes

In programming, many tasks need to be repeated multiple times such as printing numbers, processing data or checking user input continuously. Writing the same code again and again makes programs long and difficult to manage.

Loops in Java solve this problem by allowing a block of code to run repeatedly based on a condition. Instead of manually repeating instructions, the program automatically executes them until a specified condition becomes false.

Loops help reduce code length, improve readability and make programs more efficient. They are widely used in real applications for calculations, automation, and data handling. It makes them one of the most essential concepts every Java beginner must understand. Let’s begin.

What is a Loop in Java?

A loop is a control structure that repeats a group of statements multiple times depending on a condition.

Every loop works using three main parts:

1. Initialization

A starting value is assigned to a variable.

Example:

int i = 1;

This tells the program where counting begins.

2. Condition

Java checks whether the loop should continue running.

Example:

i <= 5

If the condition is true, the loop runs again.

If false, the loop stops.

3. Update

The variable changes after every iteration.

Example:

i++

This prevents the loop from running forever.

Simple Working Process of a Loop

1. Start execution

2. Check condition

3. Run code if condition is true

4. Update variable

5. Repeat steps again

This cycle continues until the condition becomes false.

Read Also: Java Tutorial for Beginners

Master Oracle Java Certification with Expert Training

Boost your skills in core Java, OOP concepts, and application development.

Explore Now

Types of Loops in Java

Java provides three looping statements. Each one exists because different programming situations require different behavior.

Loop Type Condition Checked Main Purpose
For Loop Before execution Known repetitions
While Loop Before execution Condition-based repetition
Do-While Loop After execution Execute at least once

Let’s understand each in detail.

1. For Loop in Java

The for loop is the most structured and commonly used loop in Java. It combines initialization, condition checking, and updating in one single line, which makes code cleaner and easier to read.

It is mainly used when the number of repetitions is already known.

Syntax

for(initialization; condition; update) {
   // code block
}

Each part has a specific responsibility:

  • Initialization runs only once at the beginning.
  • Condition is checked before every iteration.
  • Update runs after each execution.

Example: Print Numbers from 1 to 5

public class Main {
   public static void main(String[] args) {
       for(int i = 1; i <= 5; i++) {
           System.out.println(i);
       }
   }
}

Output

1
2
3
4
5

Step-by-Step Execution

1. i starts from 1.

2. Java checks if i <= 5.

3. Number prints.

4. i increases by 1.

5. The process repeats until the condition fails.

When i becomes 6, the loop stops automatically.

Why Beginners Prefer For Loop

  • Everything is written in one place.
  • Easy to understand counting logic.
  • Less chance of mistakes.

Common Uses

  • printing tables
  • counting numbers
  • traversing arrays
  • repeating tasks fixed number of times

2. While Loop in Java

The while loop is used when we do not know exactly how many times the loop should run. Instead of counting iterations, execution depends completely on a condition.

The loop continues running as long as the condition remains true.

Syntax

while(condition) {
   // code block
}

Unlike the for loop, initialization and updating must be written separately.

Example

public class Main {
   public static void main(String[] args) {
       int i = 1;

       while(i <= 5) {
           System.out.println(i);
           i++;
       }
   }
}

Output

1
2
3
4
5

How While Loop Executes

1. Condition checked first.

2. If true, code runs.

3. Variable updated manually.

4. Condition checked again.

If the condition becomes false, execution stops immediately.

When While Loop is Useful

  • Waiting for correct user input
  • Running programs until user exits
  • Situations where repetitions are unknown

Example:

A login system that keeps asking for a password until it is correct.

3. Do-While Loop in Java

The do-while loop works differently from the previous two loops. Here, the code executes first and the condition is checked afterward.

This guarantees that the loop runs at least once.

Syntax

do {
   // code block
} while(condition);

Notice the semicolon at the end. Beginners often forget this.

Example

public class Main {
   public static void main(String[] args) {
       int i = 1;

       do {
           System.out.println(i);
           i++;
       } while(i <= 5);
   }
}

Output

1
2
3
4
5

Why Do-While Exists

Sometimes a program must execute once before checking conditions.

Example situations:

  • showing a menu
  • asking user choice
  • running initial setup

Even if the condition is false initially, execution happens one time.

Comparison of Loops in Java

Understanding differences helps you choose the correct loop quickly.

Feature For Loop While Loop Do-While Loop
Condition Check Before Before After
Minimum Execution 0 times 0 times 1 time
Structure Compact Flexible Guaranteed run
Best For Known count Unknown count Must execute once

Practical Examples of Loops in Java

Example 1: Print Even Numbers

for(int i = 2; i <= 10; i += 2) {
   System.out.println(i);
}

Explanation:

The value increases by 2 each time, so only even numbers appear.

Output:

2 4 6 8 10

Example 2: Sum of Numbers

int sum = 0;

for(int i = 1; i <= 5; i++) {
   sum += i;
}
System.out.println(sum);

Explanation:

Each iteration adds the current value to sum.

Output:

15

This logic is commonly used in calculators and data processing.

Example 3: Menu-Based Concept

Many applications repeatedly show options until a user exits. Loops allow programs to continue running without restarting.

Read Also: Java Interview Questions and Answers

Infinite Loop in Java

An infinite loop occurs when the stopping condition never becomes false.

Example:

while(true) {
   System.out.println("Hello");
}

This loop runs forever because the condition is always true.

Common Beginner Mistake

Forgetting to update variables:

int i = 1;
while(i <= 5) {
   System.out.println(i);
}

Since i never changes, Java keeps repeating endlessly.

Loop Control Statements in Java

Loops can be controlled using special keywords.

break Statement

Stops loop immediately.

for(int i = 1; i <= 5; i++) {
   if(i == 3)
       break;
   System.out.println(i);
}

Output:

1
2

continue Statement

Skips current iteration but continues loop.

for(int i = 1; i <= 5; i++) {
   if(i == 3)
       continue;
   System.out.println(i);
}

Output:

1
2
4
5

Common Mistakes Beginners Make

  • Forgetting update statements
  • Writing wrong conditions
  • Mixing loop types unnecessarily
  • Creating infinite loops accidentally
  • Missing semicolon in do-while

When to Choose Which Loop

Quick decision rule:

  • Choose for loop when repetitions are known.
  • Choose while loop when execution depends on a condition.
  • Choose do-while loop when at least one execution is required.

Why Loops Are Important in Java

Loops make programs:

  • shorter
  • faster to write
  • easier to maintain
  • more logical
  • capable of handling large amounts of data automatically

Without loops, modern software development would be extremely inefficient.

FAQs About Loops in Java

Q1. What are loops in Java?

Loops are programming structures that execute a block of code repeatedly based on a condition.

Q2. Which loop is most used in Java?

The for loop is most commonly used because it is compact and easy to manage.

Q3. Difference between while and do-while loop?

While checking conditions before execution. Do-while checks after execution.

Q4. Can loops run forever?

Yes, if the condition never becomes false, an infinite loop occurs.

Explore Our Trending Articles-

Course Schedule

Course NameBatch TypeDetails
Java TrainingEvery WeekdayView Details
Java TrainingEvery WeekendView Details
About the Author
Author Nehal Sharma
About the Author

Nehal Sharma is a skilled Data Analyst with expertise in Java, mobile development, and data analytics. She transforms complex data into actionable insights and has experience in business intelligence, data science, and Salesforce. She also simplifies technical concepts into clear, engaging content for learners and professionals.

Drop Us a Query
Fields marked * are mandatory
Recent Post
×

Your Shopping Cart


Your shopping cart is empty.