Control Flow and Decision-
Making in Java
If-Else Statements, Switch Cases,
Loops (for, while, do-while)
If-Else Statements
• Used for decision-making
• Executes code based on conditions
Example:
if (number > 0) {
[Link]("Positive");
} else if (number < 0) {
[Link]("Negative");
} else {
[Link]("Zero");
}
Switch Cases
• Cleaner alternative to multiple if-else
• Compares a variable with multiple values
Example:
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
default: [Link]("Invalid day");
}
For Loop
• Best when number of iterations is known
Example:
for (int i = 1; i <= 5; i++) {
[Link]("Iteration: " + i);
}
While Loop
• Runs while condition is true
• Useful when iterations are not known
Example:
int i = 1;
while (i <= 5) {
[Link]("Iteration: " + i);
i++;
}
Do-While Loop
• Similar to while loop but runs at least once
Example:
int i = 1;
do {
[Link]("Iteration: " + i);
i++;
} while (i <= 5);
Summary
• If-Else → Conditional decision-making
• Switch → Multiple choices
• For Loop → Known iterations
• While Loop → Condition-based iterations
• Do-While Loop → Executes at least once