ในการเขียนโปรแกรม การรันโค้ดทำทีละบรรทัด เพื่อเปลี่ยนแปลงการไหลนี้ Java (และ C++) มีคำสั่ง break และ continue ซึ่งใช้หลักเพื่อข้ามโค้ดบางส่วนในบรรทัดเฉพาะ
ความแตกต่างสำคัญระหว่าง continue และ break:
| ลำดับ | หัวข้อ | Break | Continue |
|---|---|---|---|
| 1 | หน้าที่ | ใช้ยุติลูปที่ครอบคลุม เช่น while, do-while, for หรือ switch statement ที่ประกาศ break ไว้ | ใช้ข้ามส่วนที่เหลือของลูปที่ประกาศ continue ไว้ และทำการวนรอบถัดไปทันที |
| 2 | กระแสการทำงาน | Break ย้ายการควบคุมไปยังท้ายลูป ทำให้กระแสการทำงานอยู่นอกลูป | Continue ย้ายการควบคุมไปยังรอบถัดไปของลูปที่ครอบคลุม ทำให้กระแสการทำงานอยู่ในลูปต่อ |
| 3 | การใช้งาน | ใช้สำหรับยุติลูปที่ครอบคลุม | ทำให้รอบถัดไปของลูปที่ครอบคลุมทำงานเร็วขึ้น |
| 4 | ความเข้ากันได้ | ใช้กับ 'switch', 'label' ได้ | ใช้กับ 'switch', 'label' ไม่ได้ (ไม่เข้ากันได้) |
ตัวอย่าง Continue vs Break
JavaTester.java
ตัวอย่าง
public class JavaTester {
public static void main(String args[]) {
// Illustrating break statement (execution stops when value of i becomes 4)
System.out.println("Break Statement\n");
for (int i = 1; i <= 5; i++) {
if (i == 4) break;
System.out.println(i);
}
// Illustrating continue statement (execution skipped when value of i becomes 1)
System.out.println("Continue Statement\n");
for (int i = 1; i <= 5; i++) {
if (i == 1) continue;
System.out.println(i);
}
}
}
ผลลัพธ์
Break Statement 1 2 3 Continue Statement 2 3 4 5