Saturday, January 18, 2025
HomeQ&AWhat Is Selection Statement In Java?

What Is Selection Statement In Java?

A selection statement in Java allows the program to choose different paths of execution based on a condition. It provides a way to make decisions in the code, determining which block of code should run depending on whether a condition evaluates to true or false.

There are three primary types of selection statements in Java:

1. if statement:

The if statement evaluates a condition, and if the condition is true, the block of code inside the if statement is executed.

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

2. if-else statement:

The if-else statement is used when you need to choose between two different blocks of code—one to be executed if the condition is true, and the other if the condition is false.

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

3. if-else if-else statement:

This structure allows you to test multiple conditions sequentially. If the first condition is false, it checks the second one, and so on. If no condition is true, the else block will execute.

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

4. switch statement:

The switch statement evaluates an expression against multiple possible values and executes the corresponding block of code for the matching case. If no case matches, the default block (if provided) will execute.

switch (expression) {
    case value1:
        // Code if expression matches value1
        break;
    case value2:
        // Code if expression matches value2
        break;
    default:
        // Code if no match is found
}

Example:

int number = 10;

if (number > 0) {
    System.out.println("Positive number");
} else if (number < 0) {
    System.out.println("Negative number");
} else {
    System.out.println("Zero");
}

Selection statements are essential in controlling the flow of a program based on different conditions.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x