While loops

Intermediate Java

Jim White

Java Developer

How while loop works

  • First check condition
    • If true, we run the code provided
    • If not, the loop ends
  • Repeat: check condition and then decide

Schema for while loop

Intermediate Java

while loop syntax

while (condition) {

  // Run this code

}
  • Syntax similar to if statement
  • Unlike if statement, can run multiple times
Intermediate Java

while loop example

// Prints numbers smaller than 5
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter + 1;
}
1
2
3
4
Intermediate Java

Infinite while loop

  • Forgot to update variable
int counter = 1;

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

 

➡ Causes program to hang

  • Condition is always true
int counter = 1;

while (counter < 5){
  System.out.println(counter);
  counter = counter - 1;
}
Intermediate Java

Updating operators

int counter = 0;

// Same as counter = counter + 3
counter += 3;

Similar to -=, *=, /=, ...

Intermediate Java

Break

  • We can use break to exit while loop early, but not best coding practice
int counter = 0;
while (counter < 5){
    System.out.println("Counter: " + counter);
    if (counter == 3) {
        break; // Exit the loop when counter is 3
    }
    counter+=2;
}
Counter: 1
Counter: 3
Intermediate Java

Recap

// while loop that prints even numbers smaller than 20
int counter = 2;

while (counter < 20){
  System.out.println(counter);
  counter *= 2;

  // Exit while loop if counter is odd
  if (counter % 2 == 1){ // counter % 2 is counter modulo 2
    System.out.println("Something went wrong, counter is odd.");
    break;
  }
}
Intermediate Java

Let's practice!

Intermediate Java

Preparing Video For Download...