Control Statements in Java
Control statements decide which instructions run, how often they run, and when a loop should stop or skip a step. Without them, a simple program would mainly follow its statements from top to bottom.
Why Do We Need This?
A shop may give a discount only when a bill reaches a certain amount. A program may also need to print every item on that bill. The condition chooses an action, and the loop repeats an action.
Main Ideas
| Concept | What it means |
|---|---|
| if and if-else | Choose actions using a condition |
| switch | Choose between cases for a value |
| for, while, and do-while | Repeat a block of code |
| break | Exit a loop or switch |
| continue | Skip to the next loop iteration |
Simple Working Example
Run this program on its own. All required imports and classes are included.
public class HelloWorld {
public static void main(String[] args) {
for (int lesson = 1; lesson <= 3; lesson++) {
if (lesson == 2) {
System.out.println("Lesson 2 needs revision");
} else {
System.out.println("Lesson " + lesson + " completed");
}
}
}
}Output
Lesson 1 completed
Lesson 2 needs revision
Lesson 3 completedThe for loop runs three times. On each turn, the if condition checks the lesson number and chooses which message to print.
Topics in This Section
Easy Way to Remember
Use a condition to choose, a loop to repeat, and a jump statement to change the flow inside a loop or switch.
See you in next page....??