- Control flow statement decide which statement runs, how many times runs, which order have to runs.
- Control flow statements make Java programs dynamic, logical, and efficient.
- This blog explains control flow statements in Java in a beginner-friendly and professional manner, suitable for exams, interviews, and blog writing.
Types of Control Flow Statements in Java
Java control flow statements are broadly classified into three categories:
- Decision-Making Statements
- Looping Statements
- Jump Statements
1) Decision making statement
Decision making statement take decision based on the value.
If statement
- if is a java keyword.
- Execute code only if contdition is true.
Syntax:
if (condition) {
// Code to be executed if the condition is true
}
Else statement
- else is a java keyword.
- Execute code only if contdition is false.
Syntax:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Else-if statement
- else if is a java keyword.
- If we want to check multiple condition, we go for else if statement.
Syntax:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if none of the conditions are true
}
2) Looping statement :
Looping statements allow a block of code to execute repeatedly as long as a condition is satisfied.
While loop :
The loop needs to continue as long as a specific condition remains true
Syntax:
while (condition) {
// code to be executed
}
- The initialization happens outside the loop.
- The condition is a boolean expression checked before each iteration.
- The update statement (increment/decrement) must be handled explicitly inside the loop body to avoid an infinite loop.
For loop :
It provides a concise structure by putting the initialization, condition, and update (increment/decrement) statements in a single line
Syntax:
for (initialization; condition; update) {
// code to be executed
}
Initialization: Executed once at the very beginning of the loop.
Condition: A boolean expression checked before each iteration. If true, the loop body executes.
Update: Executed after each iteration of the loop body.
Top comments (0)