Java Control Flow Statements
Control flow statements in Java allow you to decide the direction in which the program should execute. These statements are essential to create logic, repeat actions, and make decisions. Java offers various control flow tools such as conditional statements and looping structures.
This document covers the following control flow statements:
- if Statement
- if-else Statement
- switch Statement
- for Loop
- while Loop
- do-while Loop
- break Statement
- continue Statement
Each section includes theory and practical examples for better understanding.
Java Conditions and If Statements
You already know that Java supports the usual logical conditions from mathematics:
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
- Equal to a == b
- Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
Java has the following conditional statements:
- Use if to specify a block of code to be executed, if a specified condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
- Use switch to specify many alternative blocks of code to be executed
1. if Statement
The if statement in Java is used to make decisions based on a specific condition. It helps the program to choose a path of execution by evaluating whether an expression (usually a boolean condition) is true or false. If the condition evaluates to true, the statements inside the if block are executed. If it's false, the code inside the block is skipped.
This statement is fundamental in controlling the flow of a program and is widely used in decision-making situations such as checking user input, validating conditions, or controlling access.
Syntax:
if (condition) {
// code to be executed if condition is true
}
Example:
int age = 20;
if (age >= 18) {
System.out.println("You are eligible to vote.");
}
Explanation: Since age is 20 (which is greater than 18), the message "You are eligible to vote." will be printed.
2. if-else Statement
The if-else statement in Java is used when a program needs to execute one block of code if a condition is true, and a different block if the condition is false. This enables a two-way decision-making structure. If the evaluated expression returns true, the statements under if are executed. Otherwise, the statements under else will run.
This construct is very useful when there are only two possibilities and you want to choose between them based on a condition.
Syntax:
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example:
int marks = 45;
if (marks >= 50) {
System.out.println("You passed.");
} else {
System.out.println("You failed.");
}
Explanation: Since 45 is less than 50, the output will be "You failed."
3. switch Statement
The switch statement in Java provides a more readable and cleaner way to handle multiple conditional branches that compare a single variable or expression to several constant values. Instead of writing multiple if-else-if blocks, you can use a switch to simplify and organize your code.
Each case defines a possible value, and the code block under that case is executed if the expression matches. A break statement is used to exit the switch block, and default is executed when none of the cases match.
Syntax:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default block
}
Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Another day");
}
Explanation: The value of day is 3, so the program will output "Wednesday".
4. for Loop
The while loop is a control structure that repeatedly executes a block of code as long as the given condition evaluates to true. It is ideal when the number of iterations is not known in advance, and the loop may not run at all if the condition is false at the start.
All loop control elements—initialization, condition check, and update—are placed outside or inside the loop body as needed, offering more flexibility.
Syntax:
for (initialization; condition; update) {
// code to be executed
}
Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
Explanation: This will print numbers from 1 to 5. i++ increases the value of i by 1 after every iteration.
5. while Loop
The do-while loop is a variation of the while loop that always executes the code block at least once, regardless of the condition. This is because the condition is checked after the loop body is executed.
It is particularly useful when you want the code to run at least one time—for example, prompting a user for input at least once before validating it.
Syntax:
while (condition) {
// code to be executed
}
Example:
int i = 1;
while (i <= 5) {
System.out.println("Number: " + i);
i++;
}
Explanation: It works the same as the for loop above, but initialization and update are done outside the loop.
6. do-while Loop
The do-while loop is a variation of the while loop that always executes the code block at least once, regardless of the condition. This is because the condition is checked after the loop body is executed.
It is particularly useful when you want the code to run at least one time—for example, prompting a user for input at least once before validating it.
Syntax:
do {
// code to be executed
} while (condition);
Example:
int i = 1;
do {
System.out.println("Value: " + i);
i++;
} while (i <= 5);
Explanation: The code inside do is executed once before the condition is checked.
7. break Statement
The break statement in Java is used to terminate a loop (for, while, or do-while) or a switch case prematurely. When the program encounters a break inside a loop or switch, it exits the current block and proceeds with the code following it.
This is especially useful when a condition is met and continuing the loop or switch becomes unnecessary or even incorrect, helping optimize performance and avoid unintended logic.
Example:
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
System.out.println(i);
}
Explanation: The loop stops executing when i becomes 6, so it prints 1 to 5.
8. continue Statement
The continue statement in Java is used to skip the current iteration of a loop and move to the next one. Unlike break, which exits the entire loop, continue only bypasses the remaining code in that iteration and resumes with the loop condition.
It is helpful when you want to ignore specific values or conditions during loop execution without ending the loop entirely.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
Explanation: When i is 3, continue skips the print statement, so the output will be 1, 2, 4, 5.
Advantages of Control Flow Statements in Java
- Decision Making:
- With if, if-else, and switch, programs can make decisions based on conditions.
- This allows the program to adapt its behavior according to user input or data.
- Repetition and Automation:
- for, while, and do-while loops help in automating repetitive tasks.
- Reduces redundancy and improves code efficiency.
- Better Code Organization:
- Code becomes more structured and easier to read.
- You can separate logic into different branches or loops, improving maintainability.
- Flow Control:
- With break and continue, you can manage the flow inside loops or switch blocks precisely.
- Helps avoid unnecessary iterations or exit conditions early.
- Real-World Logic Implementation:
- Allows implementation of practical logic like login systems, game loops, payment verification, etc.
Conclusion
Control flow statements allow you to make decisions, repeat tasks, and control the behavior of your program. By mastering if, switch, and loops like for, while, and do-while, you can build dynamic and intelligent Java applications.
Practice writing these structures in different combinations to develop logical thinking and strengthen your programming fundamentals.