Java Control Statements
Java Control Statements
Control statements are instructions that control the flow of execution in a program. provides control flow
statements in three main categories:
🚥 1. Decision-Making Statements
🔹 if Statement
✅ Syntax:
if (condition) {
💡 Explanation:
🧠 When to Use:
🌍 Real-Life Example:
🔧 Example:
🔹 if-else Statement
✅ Syntax:
if (condition) {
// code if true
} else {
// code if false
🧠 When to Use:
When there are two possibilities, and you want one to execute based on the condition.
🌍 Real-Life Example:
🔧 Example:
System.out.println("Pass");
} else {
System.out.println("Fail");
🔹 if-else if Ladder
✅ Syntax:
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// default block
🧠 When to Use:
When there are multiple conditions and only one block needs to execute.
🌍 Real-Life Example:
If it’s morning, drink coffee; if it’s afternoon, have lunch; else, go to bed.
🔧 Example:
System.out.println("Grade A");
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
🔹 switch Statement
✅ Syntax:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default block
🧠 When to Use:
When you have to compare a single variable against multiple constant values.
Works better than if-else-if when comparing equals values (like menu options, days, grades).
🌍 Real-Life Example:
🔧 Example:
int choice = 2;
switch (choice) {
🔁 2. Looping Statements
✅ Syntax:
// block to execute
🧠 When to Use:
🌍 Real-Life Example:
🔧 Example:
🔹 while Loop
✅ Syntax:
while (condition) {
// code to execute
🧠 When to Use:
🌍 Real-Life Example:
🔧 Example:
int i = 1;
while (i <= 5) {
i++;
🔹 do-while Loop
✅ Syntax:
do {
// code to execute
} while (condition);
🧠 When to Use:
When the loop must execute at least once, regardless of the condition.
🌍 Real-Life Example:
🔧 Example:
int i = 1;
do {
i++;
⛔ 3. Jump Statements
🔹 break
if (i == 3) break;
System.out.println(i);
🔹 continue
if (i == 3) continue;
System.out.println(i);
📝 Summary Table
Statement Use When… Executes At Least Once Known Iterations