Java Control Structures


Java provides several control structures that allow you to control the flow of a program. These control structures allow you to execute code conditionally, repeat code a certain number of times, and loop through arrays and other collections.

If-else statements

The if-else statement allows you to execute a block of code conditionally. The code inside the if statement is executed if the condition is true, and the code inside the else statement is executed if the condition is false. Here is an example:

if (condition) {
    // code to be executed if the condition is true
} else {
    // code to be executed if the condition is false
}

Switch statements

The switch statement allows you to execute a block of code based on the value of a variable. The switch statement compares the value of the variable to a list of possible values and executes the code associated with the matching value. Here is an example:

switch (variable) {
    case value1:
        // code to be executed if variable equals value1
        break;
    case value2:
        // code to be executed if variable equals value2
        break;
    default:
        // code to be executed if variable doesn't match any of the values
        break;
}

While loops

The while loop allows you to repeat a block of code while a condition is true. The code inside the loop is executed repeatedly until the condition becomes false. Here is an example:

while (condition) {
    // code to be executed repeatedly while the condition is true
}

Do-while loops

The do-while loop is similar to the while loop, but the code inside the loop is executed at least once, even if the condition is false. Here is an example:

do {
    // code to be executed at least once, and repeatedly while the condition is true
} while (condition);

For loops

The for loop allows you to iterate through a collection of items, such as an array or a list. Here is an example:

for (int i = 0; i < array.length; i++) {
    // code to be executed for each item in the array
}

These are the basic control structures in Java, and they allow you to write programs that can make decisions, repeat code, and iterate through collections of data.

A quick recap of Java