Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 03 / Topic 4 of 8

while loops

A while loop repeats its body as long as its condition stays true. Java checks the condition before each run, so the body might run zero times.

int cupsOfChai = 1;
while (cupsOfChai <= 5) {
    System.out.println("Cup number " + cupsOfChai);
    cupsOfChai++;
}
System.out.println("Done, cupsOfChai is now " + cupsOfChai);

Output:

Cup number 1
Cup number 2
Cup number 3
Cup number 4
Cup number 5
Done, cupsOfChai is now 6

The most common real use of while is "keep asking until the answer is right, or we run out of chances" — exactly what the capstone needs for PIN entry:

final String correctPin = "1234";
int attemptsLeft = 3;
boolean unlocked = false;

while (attemptsLeft > 0 && !unlocked) {
    System.out.print("Enter PIN: ");
    String typed = scanner.nextLine();
    if (typed.equals(correctPin)) {
        unlocked = true;
        System.out.println("PIN correct. Card unlocked.");
    } else {
        attemptsLeft--;
        System.out.println("Wrong PIN. Attempts left: " + attemptsLeft);
    }
}
if (!unlocked) {
    System.out.println("Card blocked: too many wrong attempts.");
}

Real transcript (typed input was 9999, then 1111, then 1234):

Enter PIN: Wrong PIN. Attempts left: 2
Enter PIN: Wrong PIN. Attempts left: 1
Enter PIN: PIN correct. Card unlocked.

The condition attemptsLeft > 0 && !unlocked stops the loop either way: correct PIN, or no attempts left. That is the exact shape the ATM menu in Section 8 reuses.

while (true) loops forever on its own — you stop it from inside, with break (Section 7):

int balance = 1000;
int month = 1;
while (true) {
    balance += 100; // interest credited every month
    System.out.println("Month " + month + ": balance Rs " + balance);
    if (balance >= 1400) {
        System.out.println("Target reached, stopping.");
        break;
    }
    month++;
}

Output:

Month 1: balance Rs 1100
Month 2: balance Rs 1200
Month 3: balance Rs 1300
Month 4: balance Rs 1400
Target reached, stopping.

Full program: examples/03_while_loops.java.

Done here? The practice set for Part 3 — including the solutions — is on the part page.

Search the guide