Control flow statements in Java
Anonymous User
819

Control flow statements in Java allow you to control the flow of your program's execution based on certain conditions. These statements include if-else, switch, and loops like for, while, and do-while. Let's explore each with simple examples:

  • If-else Statement :
    The if-else statement allows you to execute a block of code based on whether a condition is true or false.
int x = 10;
if (x > 0) {
    System.out.println("x is positive");
} else {
    System.out.println("x is not positive");
}
  • Switch Statement :
    The switch statement evaluates an expression and executes code blocks based on matching cases.
int day = 3;
String dayName;
switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    default:
        dayName = "Invalid day";
}
System.out.println("Day is: " + dayName);
  • For Loop :
    The for loop iterates over a range of values, executing a block of code each time.
for (int i = 1; i <= 5; i++) {
    System.out.println("Count: " + i);
}
  • While Loop :
    The while loop executes a block of code as long as a condition is true.
int i = 1;
while (i <= 5) {
    System.out.println("Count: " + i);
    i++;
}
  • Do-while Loop :
    The do-while loop is similar to the while loop but guarantees the code block will execute at least once before evaluating the condition.
int i = 1;
do {
    System.out.println("Count: " + i);
    i++;
} while (i <= 5);
Comments (0)