Post 4: Control Flow Statements in Java
In Java programming, control flow statements are used to determine the execution order of statements within a program. These statements allow you to control the flow of your program based on certain conditions or loops. In this post, we will cover the basics of control flow statements and provide examples to help you understand their usage.
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Example:
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a minor.");
}
switch (variable) {
case value1:
// code to be executed if variable == value1
break;
case value2:
// code to be executed if variable == value2
break;
...
default:
// code to be executed if none of the cases match
break;
}
Example:
int dayOfWeek = 5;
switch (dayOfWeek) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
// and so on...
default:
System.out.println("Invalid day");
break;
}
for (initialization; condition; update) {
// code to be executed
}
Example:
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
while (condition) {
// code to be executed
}
Example:
int count = 1;
while (count <= 5) {
System.out.println(count);
count++;
}
do {
// code to be executed
} while (condition);
Example:
int count = 1;
do {
System.out.println(count);
count++;
} while (count <= 5);
These control flow statements are integral to controlling the flow and logic of your Java programs. Practice using them in various scenarios to become comfortable with their syntax and behavior.