CodeToLive

Control Structures in Java

Control structures in Java allow you to control the flow of your program. They include conditional statements (if-else, switch) and loops (for, while, do-while).

If-Else Statements:

The if-else statement is used to execute a block of code based on a condition. If the condition is true, the code inside the if block is executed. Otherwise, the code inside the else block is executed.


// If-Else Example
int age = 20;
if (age >= 18) {
    System.out.println("You are an adult.");
} else {
    System.out.println("You are a minor.");
}
      

Switch Statement:

The switch statement is used to select one of many code blocks to be executed. It evaluates an expression and matches the value to a case label. If a match is found, the corresponding block of code is executed.


// Switch Example
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("Invalid day");
}
      

For Loop:

The for loop is used to iterate a block of code a specific number of times. It consists of an initialization, a condition, and an increment/decrement expression.


// For Loop Example
for (int i = 0; i < 5; i++) {
    System.out.println(i);
}
      

While Loop:

The while loop is used to repeatedly execute a block of code as long as a condition is true. The condition is evaluated before the loop body is executed.


// While Loop Example
int count = 0;
while (count < 5) {
    System.out.println(count);
    count++;
}
      

Do-While Loop:

The do-while loop is similar to the while loop, but the condition is evaluated after the loop body is executed. This ensures that the loop body is executed at least once.


// Do-While Loop Example
int count = 0;
do {
    System.out.println(count);
    count++;
} while (count < 5);
      

Nested Control Structures:

Control structures can be nested within each other to create more complex logic. For example, you can have an if statement inside a for loop.


// Nested Control Structures Example
for (int i = 0; i < 5; i++) {
    if (i % 2 == 0) {
        System.out.println(i + " is even.");
    } else {
        System.out.println(i + " is odd.");
    }
}
      
Next: Functions