CodeGym /Courses /JAVA 25 SELF /While Loop: Introduction and Practical Nuances

While Loop: Introduction and Practical Nuances

JAVA 25 SELF
Level 4, Lesson 1
Available

1. Introduction

In programming, you regularly have to perform the same actions many times in a row. For example:

  • Iterate over all elements of a list.
  • Read values from the keyboard until the user enters the required one.
  • Calculate the sum of all numbers from 1 to 100.
  • Ask the user for a password until it becomes correct.

If you try to implement all this without loops, it will be long, boring, and not scalable. Imagine you are writing a calculator program and decide to add the numbers from 1 to 10 manually:

int sum = 0;
sum = sum + 1;
sum = sum + 2;
sum = sum + 3;
// ... and so 10 times. Yikes.
Manual repetition without a loop — inconvenient!

You'll get bored before you finish! The solution is loops. They let you describe repetition concisely and clearly. Today we’ll get to know the most basic yet extremely useful loop — while.

2. Getting to know the while loop

Syntax and basic pattern

The while loop is a “parrot” in the programming world: it repeats the same fragment of code as long as some condition holds. As soon as the condition stops being true, the parrot falls silent (the loop ends).

Syntax:

while (condition)
{
    // Loop body
}
While loop with a block of statements

Diagram

Here is a simple flowchart to understand how the while loop works:

uml-while

3. Examples: the while loop in action

Classic counter

Let’s make a simple program that counts from 1 to 5 and prints the numbers:

int i = 1;
while (i <= 5)
{
    System.out.println("Step # " + i);
    i++; // Don’t forget to increment the counter!
}
// Output:
// Step # 1
// Step # 2
// Step # 3
// Step # 4
// Step # 5

Note: if you forget to increment the variable i, the loop will never finish (our parrot becomes immortal and repeats forever). This is called an infinite loop — a scary thing.

Input from the keyboard until the required value

Quite often a loop is used to keep prompting the user until they give the correct answer:

String password = "";
while (!password.equals("qwerty"))
{
    System.out.print("Enter password: ");
    password = console.nextLine();
}
System.out.println("Welcome!");

Here the program asks for a password until you type the magic "qwerty". Don’t forget: if you remove the line password = console.nextLine();, the loop becomes infinite again (it will ask for the password but won’t read input — it will hang forever like a broken robot).

4. Types and use cases of the while loop

Regular while loop

This loop, as shown above, checks the condition before the first iteration. If the condition is false right away, the loop body won’t execute even once.

Example: the condition is false immediately

int i = 10;
while (i < 5)
{
    System.out.println(i); // Will never execute!
}

Which is perfectly logical. Exactly as written.

Nested while loops

Sometimes you need a loop inside a loop. For example, iterate over all lines and check all characters in each. At this stage it’s more of a venture, but here is a simple example:

int i = 1;
while (i <= 3)
{
    int j = 1;
    while (j <= 2)
    {
        System.out.println("i = " + i + ", j = " + j);
        j++;
    }
    i++;
}

// i = 1, j = 1
// i = 1, j = 2
// i = 2, j = 1
// i = 2, j = 2
// i = 3, j = 1
// i = 3, j = 2

We’ll dive deeper into nested loops in a couple of lectures — for now I just wanted to spook you a little :)

Infinite loop

The while loop in real life: While Barney is in the bar — Moe throws him out. But Barney always returns... The condition never changes = infinite loop!

Sometimes loops end, and sometimes — they live forever.

while (true)
{
    System.out.println("I am eternal!");
}

Used rarely, usually for some background processes (for example, a server), but it’s used in practice too.

5. How not to write nonsense: common mistakes with while

In programming, a loop is like electricity: it’s great, but you need to know the safety rules.

Pitfall 1: unintended infinite loop due to inattention

Very often beginners forget to update the variable on which the condition depends. As a result, the loop runs “forever,” and you have to stop the program forcibly (for example, with Ctrl + C).

int i = 1;
while (i <= 5)
{
    System.out.println(i);
    // i++;  // Oops! Forgot to increment i
}

Pitfall 2: incorrect condition

Sometimes a developer digs their own hole: the condition, on the contrary, is never true. As a result, the loop doesn’t execute at all.

int i = 10;
while (i < 5)
{
    System.out.println(i); // This code will never run.
    i++;
}

Pitfall 3: data type error

The loop condition must always be a boolean expression — that is, the result must be true or false.

int number = 5;
while (number) // Error! Expected boolean, not int.
{
    number--;
}
1
Task
JAVA 25 SELF, level 4, lesson 1
Locked
Countdown Before Launch 🚀
Countdown Before Launch 🚀
1
Task
JAVA 25 SELF, level 4, lesson 1
Locked
Unlocking the smartphone 📱
Unlocking the smartphone 📱
1
Task
JAVA 25 SELF, level 4, lesson 1
Locked
Display available seats in the movie theater 🎞️
Display available seats in the movie theater 🎞️
1
Task
JAVA 25 SELF, level 4, lesson 1
Locked
Coffee expense tracking ☕
Coffee expense tracking ☕
Comments (1)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Hoist Level 1, San Diego, United States
25 November 2025

Enter the cost of a cup of coffee (negative number to stop):
Enter the cost of a cup of coffee (negative number to stop):
Enter the cost of a cup of coffee (negative number to stop):
Enter the cost of a cup of coffee (negative number to stop):
Enter the cost of a cup of coffee (negative number to stop):
Enter the cost of a cup of coffee (negative number to stop):
Total spent on coffee: $15.50
3.50 4.00 2.25 0.00 5.75 -1