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.
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
}
Diagram
Here is a simple flowchart to understand how the while loop works:
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
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--;
}
GO TO FULL VERSION