Introduction to Java · Introduction to Java Programming

While Loop

Watch lectures

While Loop

1. When to Use (beginner)

While = "check first, then do" — repeats while condition true, may run zero times. Best when rounds unknown (read until -1, retry password).

// CLASSIC 1: password retry (unknown tries!)
Scanner sc = new Scanner(System.in);
String pw;
while (true) { // infinite until break!
    System.out.print("password: ");
    pw = sc.nextLine();
    if (pw.equals("java123")) break; // correct → exit
    System.out.println("try again");
}
// CLASSIC 2: sum until -1 (sentinel!)
int sum = 0, x;
System.out.println("enter numbers (-1 ends):");
x = sc.nextInt();
while (x != -1) { sum += x; x = sc.nextInt(); }
System.out.println("sum=" + sum);

4. Traps

  • No update → infinite loop (most common crash! press Ctrl+C).
  • while(true) needs break inside (else infinite).
  • ; after while(...) = empty loop bug: while(i<5); { ... } (semicolon ends loop!).

5. Exam Points

  • Sentinel/retry program + trace — 5 marks, very frequent.
  • Infinite-loop cause + parts — 3 marks, frequent.
Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.

← All Introduction to Java Programming modules