BhauAutomation

Java Control Statements

Learn about Java Control Statements to control the flow of your program using decision-making and loops with practical examples.

What are Control Statements?

Control statements in Java allow you to control the flow of program execution. Using them, you can execute statements conditionally or repeatedly based on certain conditions.

If-Else Statement

The if-else statement is used to execute a block of code based on a condition. If the condition is true, the code inside 'if' executes; otherwise, 'else' block executes.

int num = 10;
if (num % 2 == 0) {
    System.out.println("Even number");
} else {
    System.out.println("Odd number");
}
  

Switch Statement

The switch statement allows a variable to be tested for equality against a list of values.

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("Other day");
}
  

For Loop

The for loop executes a block of code for a fixed number of times.

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 the condition is true.

int i = 1;
while (i <= 5) {
    System.out.println("Count: " + i);
    i++;
}
  

Do-While Loop

The do-while loop executes the block of code once before checking the condition and then continues if the condition is true.

int i = 1;
do {
    System.out.println("Count: " + i);
    i++;
} while (i <= 5);
  

Break and Continue Statements

The break statement exits a loop immediately, while continue skips the current iteration and moves to the next.

for (int i = 1; i <= 5; i++) {
    if (i == 3) continue;
    if (i == 5) break;
    System.out.println(i);
}
// Output: 1 2 4