Java Control Flow Constructs
Java Control Flow Constructs
1. Simple if Construct
Syntax:
if (condition) {
// statement(s)
}
Flowchart:
Start → [Condition true?] → Yes → Execute statement → End
↘ No → End
Output:
a is greater than 5
2. if...else Construct
Syntax:
if (condition) {
// if block
} else {
// else block
}
Flowchart:
Start → [Condition true?] → Yes → If block → End
↘ No → Else block → End
Output:
a <= 5
Syntax:
if (condition1) {
if (condition2) {
// code
} else {
// code
}
} else {
// code
}
Flowchart:
Start → [Condition1?] → Yes → [Condition2?] → Yes → Inner If block → End
↘ No → Inner Else block → End
↘ No → Outer Else block → End
Output:
Positive even
4. else if Ladder Construct
Syntax:
if (cond1) {
// code
} else if (cond2) {
// code
} else {
// default
}
Flowchart:
Start → [Cond1?] → Yes → Block1 → End
↘ No → [Cond2?] → Yes → Block2 → End
↘ No → Else block → End
Output:
Zero
5. switch Construct
Syntax:
switch (expression) {
case val1:
// code
break;
default:
// default code
}
Flowchart:
Start → Evaluate expression
→ Match case1? → Yes → Case1 code → End
→ Match case2? → Yes → Case2 code → End
→ No match → Default code → End
Output:
Monday
Example (while):
public class Main {
public static void main(String[] args) {
int i = 5;
while (i < 5)
System.out.println("Hello");
}
}
Output:
(no output)
Example (do...while):
public class Main {
public static void main(String[] args) {
int i = 5;
do
System.out.println("Hello");
while (i < 5);
}
}
Output:
Hello