---
# System prepended metadata

title: while/do-while Statements
tags: [Java]

---

[toc]

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

## while
如果敘述成立->執行, 直到條件不成立為止
```java
while (boolean expression)
    // statement
```

Example:
```java
int i = 0;
while (i < 5) {
    System.out.print(i + " ");
    i++;
}
// 0 1 2 3 4
```
迭代Array:
```java
int[] arr = {0, 1, 2, 3, 4};
int i = 0;
while (i < 5) {
    System.out.println(arr[i]);
    i++;
}
// 0 1 2 3 4
```
## do while
執行->如果敘述成立->執行->.., 直到條件不成立為止
```java
do {
    // statements
} while (boolean expression);
```

Example:
```java
int i = 5;
do {
    System.out.print(i + " ");
    i--;
} while (i > 0);
// 5 4 3 2 1
```