กำหนดลำดับที่คำสั่งจะถูกดำเนินการ Java มีเงื่อนไข (, ), ลูป (, , ) และคำสั่งการสาขา (, , ) — บวกกับการปรับปรุงสมัยใหม่เช่น switch expressions
ifswitchforwhiledo-whilebreakcontinuereturnif (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "F";
}
// ternary — concise if/else for a value
String status = (age >= 18) ? "adult" : "minor";
switch (day) {
case 1: name = "Mon"; break; // ⚠️ break needed — else it FALLS THROUGH
case 2: name = "Tue"; break;
default: name = "Unknown";
}
switch แบบคลาสสิกต้องมี break หลังจากแต่ละ case — การลืมสิ่งนี้ทำให้เกิด fall-through (การดำเนินการจะดำเนินต่อไปยัง case ถัดไป) ซึ่งเป็นแหล่งบั๊กที่มีชื่อเสียง
// arrow syntax: no fall-through, returns a value, more concise
String name = switch (day) {
case 1 -> "Mon";
case 2 -> "Tue";
case 6, 7 -> "Weekend"; // multiple labels
default -> "Unknown";
};
switch expression สมัยใหม่ช่วยกำจัด fall-through สามารถส่งคืนค่าได้ และสะอาดกว่า — ได้รับความนิยมในโค้ดใหม่
// for — known iteration count
for (int i = 0; i < 10; i++) { ... }
// enhanced for-each — iterate a collection/array
for (String item : items) { ... }
// while — condition checked BEFORE each iteration
while (condition) { ... }
// do-while — body runs at least ONCE (condition checked after)
do { ... } while (condition);
for (int i = 0; i < 10; i++) {
if (i == 5) break; // exit the loop entirely
if (i % 2 == 0) continue; // skip to the next iteration
}
return result; // exit the method
// labeled break — exit nested loops
outer:
for (...) {
for (...) {
if (found) break outer; // breaks BOTH loops
}
}
break ออกจากลูป continue ข้ามไปยังการวนซ้ำถัดไป return ออกจากเมธอด และ breaks ที่ติดป้ายกำกับสามารถออกจากลูปแบบซ้อนได้ในคราวเดียว
การควบคุมการไหลของข้อมูลเป็นกลไกพื้นฐานสำหรับการแสดงลอจิกและการตัดสินใจในโปรแกรมใดๆ — ทุกวิธีที่ไม่ไม่สำคัญจะใช้มัน
การทำความเข้าใจโครงสร้างและความสูกสำลักเหล่านี้เป็นสิ่งจำเป็น: fall-through gotcha ของ switch (และ switch expression ที่ปลอดภัยกว่า) ความแตกต่างระหว่าง while และ do-while (รัน-อย่างน้อย-หนึ่งครั้ง) for-each สำหรับการวนซ้ำคอลเลกชันที่สะอาด และคำสั่งการสาขา (รวมถึง breaks ที่ติดป้ายกำกับสำหรับลูปแบบซ้อน)
การเรียนรู้สิ่งเหล่านี้ — และการลงนามาในรูปแบบสมัยใหม่ที่มีแนวโน้มข้อผิดพลาดน้อยกว่า (switch expressions, for-each) — เป็นสิ่งจำเป็นพื้นฐานสำหรับการเขียนลอจิก Java ที่ถูกต้องและอ่านง่าย และเพื่อหลีกเลี่ยงบั๊กการควบคุมการไหลของข้อมูลทั่วไป