制御フロー(Control flow) は、ステートメントが実行される順序を決定します。Javaは条件文(、)、ループ(、、)、分岐文(、、)を提供します — さらに、switch式のような現代的な拡張機能も含まれています。
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 は各caseの後に break が必要です — それを忘れると 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式は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はメソッドを終了し、ラベル付きbreakは複数レベルのループを一度に終了できます。
制御フローは、プログラム内のロジックと判断を表現するための基本的なメカニズムです — すべての非自明なメソッドがこれを使用します。
これらの構文とその微妙な違いを理解することは重要です:switchのfall-throughの落とし穴(およびより安全なモダンswitch式)、whileとdo-whileの違い(少なくとも1回実行)、コレクション反復のためのクリーンな for-each、および分岐文(ネストされたループ用のラベル付きbreakを含む)。
これらをマスターし、モダンでエラーが少ない形式(switch式、for-each)を優先することは、正確で読みやすいJavaロジックを書き、制御フローの一般的なバグを回避するための基本です。