DEV Community

Abhishek Kumar
Abhishek Kumar

Posted on

Control Structures in Java

Control structures dictate the flow of execution in a program. Java provides various control structures like loops and conditionals to control how code is executed based on conditions or repeatedly for a certain number of times.


1. Loops: for, while, do-while

Loops allow you to execute a block of code multiple times, either for a fixed number of iterations or while a condition is true.

for Loop

The for loop is typically used when the number of iterations is known beforehand.

Syntax:
for (initialization; condition; increment/decrement) {
    // code to be executed
}
Enter fullscreen mode Exit fullscreen mode
Example:
for (int i = 0; i < 5; i++) {
    System.out.println("i = " + i);
}
Enter fullscreen mode Exit fullscreen mode

Output:

i = 0
i = 1
i = 2
i = 3
i = 4
Enter fullscreen mode Exit fullscreen mode
  • Initialization: Executes once at the start.
  • Condition: If true, the loop continues; if false, it terminates.
  • Increment/Decrement: Updates the loop counter after each iteration.

Enhanced for Loop (for-each)

The enhanced for loop is used for iterating over arrays or collections.

Syntax:
for (type variable : collection) {
    // code to be executed
}
Enter fullscreen mode Exit fullscreen mode
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
    System.out.println(num);
}
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

while Loop

The while loop is used when the number of iterations isn't known in advance, but depends on a condition.

Syntax:
while (condition) {
    // code to be executed
}
Enter fullscreen mode Exit fullscreen mode
Example:
int i = 0;
while (i < 5) {
    System.out.println("i = " + i);
    i++;
}
Enter fullscreen mode Exit fullscreen mode

Output:

i = 0
i = 1
i = 2
i = 3
i = 4
Enter fullscreen mode Exit fullscreen mode
  • The loop runs as long as the condition is true.

do-while Loop

A do-while loop is similar to the while loop, but the condition is checked after the loop body is executed, ensuring that the body is executed at least once.

Syntax:
do {
    // code to be executed
} while (condition);
Enter fullscreen mode Exit fullscreen mode
Example:
int i = 0;
do {
    System.out.println("i = " + i);
    i++;
} while (i < 5);
Enter fullscreen mode Exit fullscreen mode

Output:

i = 0
i = 1
i = 2
i = 3
i = 4
Enter fullscreen mode Exit fullscreen mode

2. Conditionals: if-else and switch

Conditionals allow decision-making in a program by executing different blocks of code based on conditions.

if-else Statement

An if statement checks a condition and executes the block of code if the condition is true. You can extend it with an optional else or else if block.

Syntax:
if (condition) {
    // code to be executed if condition is true
} else if (anotherCondition) {
    // code to be executed if anotherCondition is true
} else {
    // code to be executed if all conditions are false
}
Enter fullscreen mode Exit fullscreen mode
Example:
int age = 20;

if (age >= 18) {
    System.out.println("You are an adult.");
} else if (age >= 13) {
    System.out.println("You are a teenager.");
} else {
    System.out.println("You are a child.");
}
Enter fullscreen mode Exit fullscreen mode

Output:

You are an adult.
Enter fullscreen mode Exit fullscreen mode

switch Statement

The switch statement allows you to choose between multiple options based on the value of an expression.

Syntax:
switch (expression) {
    case value1:
        // code to be executed for value1
        break;
    case value2:
        // code to be executed for value2
        break;
    // more cases
    default:
        // code to be executed if no cases match
}
Enter fullscreen mode Exit fullscreen mode
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");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Wednesday
Enter fullscreen mode Exit fullscreen mode
  • The break statement ensures the switch statement exits after the matched case is executed.
  • The default case is optional and gets executed if no case matches the expression.

3. Iteration using for and while

Both the for and while loops allow iteration over sequences like arrays, lists, or ranges of values.

Iterating Over an Array Using for Loop:

int[] numbers = {1, 2, 3, 4, 5};

for (int i = 0; i < numbers.length; i++) {
    System.out.println("Number: " + numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

Iterating Over a List Using while Loop:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("John");
        names.add("Doe");
        names.add("Alice");

        int i = 0;
        while (i < names.size()) {
            System.out.println("Name: " + names.get(i));
            i++;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion:

  • Loops like for, while, and do-while are essential for repeating code.
  • Conditionals like if-else and switch help control decision-making by executing different blocks based on conditions.
  • Using these control structures effectively is crucial in writing efficient and clean Java programs.

Top comments (0)