A2oz

What is the Syntax of Each of the Decision Structures in Java?

Published in Java Programming 2 mins read

Java offers three primary decision structures for controlling the flow of execution based on conditions:

1. if Statement

The if statement executes a block of code only if a specified condition is true.

Syntax:

if (condition) {
    // Code to be executed if the condition is true
}

Example:

int age = 25;

if (age >= 18) {
    System.out.println("You are eligible to vote.");
}

2. if-else Statement

The if-else statement provides an alternative block of code to execute if the condition in the if statement is false.

Syntax:

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

Example:

int score = 75;

if (score >= 90) {
    System.out.println("Excellent!");
} else {
    System.out.println("Good job!");
}

3. if-else if-else Statement

The if-else if-else statement allows for multiple conditions to be checked sequentially. If a condition is true, its corresponding block of code is executed. If none of the conditions are true, the else block is executed.

Syntax:

if (condition1) {
    // Code to be executed if condition1 is true
} else if (condition2) {
    // Code to be executed if condition2 is true
} else if (condition3) {
    // Code to be executed if condition3 is true
} else {
    // Code to be executed if none of the conditions are true
}

Example:

int grade = 85;

if (grade >= 90) {
    System.out.println("A");
} else if (grade >= 80) {
    System.out.println("B");
} else if (grade >= 70) {
    System.out.println("C");
} else {
    System.out.println("D");
}

These decision structures are fundamental to creating dynamic and responsive Java programs. They enable you to control the flow of execution based on specific conditions, making your code more adaptable and efficient.

Related Articles