Java while loop

A Java while loop tests its condition before each iteration. If the initial condition is false, the body never runs.

A simple example

Print while the number is at most 3

  1. Start with n starts at 1
  2. Do this Print n, add 1
  3. Result Stop at 4
The test happens before each print. It succeeds for 1, 2 and 3. At 4 it fails, so 4 is never printed.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        int n = 1;
        while (n <= 3) {
            System.out.println(n);
            n++;
        }
    }
}
Output
1
2
3
Apples at the start: 17. Bag size: 5 apples. Packed: 3 bags ยท 2 left.
Fill complete snack bags

The canteen has 17 apples and packs five in each bag. Check the remaining pile before filling each bag. Three full bags leave two apples for the next delivery.