# Selection statements | Java

* It is also called decision making statement.
    
* Among several options only one option will be selected and executed based on some condition.
    

There are two conditional statements comes under selected statements -

## `if else` Statement

It is used to evaluate the condition. It is an expansion of `if` statement. In `if` statement, if the condition is true then the corresponding statement will be executed otherwise the block will be discarded.

**Syntax:**

```plaintext
if (condition){
    // statement if action is true
} else {
    // statement if action is false
}
```

* The argument to the if statement should be bullion type only.
    
* If we try to pass any other type then we will get compiled on error.
    
    **Example 1 -**
    
    ```java
    int x = 10;
    if (x) { // int cannot be converted to boolean
        System.out.println("Program executed successfully");
    } else {
        System.out.println("Program failed");
    }
    ```
    
    **Example 2 -**
    
    ```java
    int x = 10;
    if (x = 20) { // int cannot be converted to boolean
        System.out.println("Program executed successfully");
    } else {
        System.out.println("Program failed");
    }
    ```
    
    **Example 3 (Valid) -**
    
    ```java
    int x = 10;
    if (x == 20) { 
        System.out.println("Program executed successfully");
    } else {
        System.out.println("Program failed");
    }
    ```
    
    **Example 4 (Valid) -**
    
    ```java
    int x = true;
    if (x == false) { 
        System.out.println("Program executed successfully");
    } else {
        System.out.println("Program failed");
    }
    ```
    
* `else` <mark>part and curly braces are optional in Java.</mark>
    
* Without curly braces and only one statement is allowed which should not be declarative statement.
    
    **Example -**
    
    ```java
    // case 1 - Valid
    
    if (true) 
        System.out.println("Program executed successfully");
    
    // case 2 - valid
    
    if (true) 
    
    // case 3 - Invalid
    
    if (true)
        int x = 10;
        System.out.println(x);
    
    // case 4 - Valid
    
    if (true) {
        int x = 10;
        System.out.println(x);
    }
    ```
    
    **Note**: In **case 4** declarative statement which cannot be assigned - `int x` is a local variable And local warrior must be declared in sight curly braces or a block.
    
* There is no dangling `else` problem in Java every `else` is mapped to the nearest `if` statement.
    

### Nested `if-else` statements

A nested if-else statement is an if-else statement that is embedded within another if or else block. This allows for more complex decision-making logic based on multiple conditions.

Here's an example of nested if-else statements in Java:

```java
public class NestedIfElseExample {
    public static void main(String[] args) {
        int x = 10;
        int y = 20;

        if (x > y) {
            System.out.println("x is greater than y");
        } else {
            System.out.println("x is not greater than y");

            if (x < y) {
                System.out.println("x is less than y");
            } else {
                System.out.println("x is equal to y");
            }
        }
    }
}
```

In this example, there is an outer if-else statement checking if `x` is greater than `y`. If that condition is false, the nested if-else statement inside the else block is executed, checking whether `x` is less than `y` or equal to `y`.

### `if-else-if` ladder statements

It is a series of if-else statements where each "else-if" condition is checked only if the preceding conditions are false. This allows you to evaluate multiple conditions in a sequential manner. Here's the basic syntax:

```java
if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition2 is true
} else if (condition3) {
    // Code to execute if condition3 is true
} else {
    // Code to execute if none of the conditions are true
}
```

<mark>Each "if" or "else-if" condition is evaluated from top to bottom, and as soon as a true condition is encountered, the corresponding block of code is executed, and the rest of the conditions are skipped.</mark>

Here's an example of an if-else-if ladder:

```java
public class IfElseIfExample {
    public static void main(String[] args) {
        int number = 5;

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

In this example, the program checks whether the variable `number` is positive, negative, or zero. The conditions are checked in a sequential manner, and the corresponding block of code is executed based on the first true condition encountered.

<mark>It's important to note that in an if-else-if ladder, only the code block associated with the first true condition is executed, even if multiple conditions are true.</mark> This is different from a series of independent if statements, where multiple conditions can be true, and their corresponding code blocks would all be executed.

## `switch` Statement

* It contain multiple block of code called cases
    
* If several options are available then it is not recommended to use nested if else
    
* Using of nested `if else` reduces readability to handle this requirement we should go for `switch` statement.
    
* The `switch` statement is a control flow statement that allows you to select one of many code blocks to be executed based on the value of an expression.
    
    Here is the basic syntax of the `switch` statement:
    
    ```java
    switch (expression) {
        case value1:
            // Code to be executed if expression == value1
            break;
        case value2:
            // Code to be executed if expression == value2
            break;
        // Additional cases...
        default:
            // Code to be executed if none of the cases match
    }
    ```
    
    Key points to remember about the `switch` statement:
    
    * The `expression` must evaluate to a byte, short, char, int, String, or enum constant.
        
    * Each `case` represents a possible value of the expression.
        
    * The `break` statement is used to exit the `switch` statement. Without it, control will "fall through" to subsequent cases.
        
    * The `default` case is optional and provides code to be executed when none of the cases match.
        
    
    Here's an example of a `switch` statement:
    
    ```java
    public class SwitchExample {
        public static void main(String[] args) {
            int dayOfWeek = 3;
    
            switch (dayOfWeek) {
                case 1:
                    System.out.println("Monday");
                    break;
                case 2:
                    System.out.println("Tuesday");
                    break;
                case 3:
                    System.out.println("Wednesday");
                    break;
                case 4:
                    System.out.println("Thursday");
                    break;
                case 5:
                    System.out.println("Friday");
                    break;
                default:
                    System.out.println("Weekend");
            }
        }
    }
    ```
    
    In this example, the program prints the day of the week based on the value of the `dayOfWeek` variable. The `switch` statement provides a concise way to handle multiple cases and improves code readability compared to a series of `if-else` statements.
    
* The allowed argument type for switch statements are `byte`, `short`, `int`, `String` and `char`
    
* From 1.5v corresponding wrapper classes and enum also allowed.
    
* <mark>We cannot use boolean because if we go for boolean only two cases are possible so better go for if else</mark>.
    
* In case of `long` there is no need of that much long range of cases.
    
* We also cannot use floating data type because between 2 numbers there can be infinite number of cases which is impossible.
    
* Curly braces are mandatory
    
* Except Switch Curly braces are optional.
    
* In case of switch both `case` and `default` are optional.
    
* An empty `switch` statement is a valid java statement.
    
    ```java
    //Valid statement 
    
    switch (x) {
        
     }
    
    //Valid statement 
    
    switch (x) {
        case 1:
            //case statement
     }
    
    //Valid statement 
    
    switch (x) {
        case 1:
            //case statement
        default :
            //default statement
     }
    
    //Valid statement 
    
    switch (x) {
        default :
            //default statement
     }
    ```
    
* Inside a switch every statement should be under some `case` or `default`.
    
* Independent statements are not allowed.
    
    ```java
    switch (x) {
        System.out.println("Switch statement"); //Invalid
     }
    ```
    
* Every case label should be constant that is constant expression. But if we declare variable as `final` then we don't get any compile time error.
    
    ```java
    public class SwitchExample {
        public static void main(String[] args) {
            int y = 3;
            int x = 10;
    
            switch (x) {
                case 1:
                    System.out.println("Monday");
                    break;
                case x: //Constant Expression Required
                    System.out.println("Tuesday");
                    break;
                default:
                    System.out.println("Weekend");
            }
        }
    }
    ```
    
    ```java
    public class SwitchExample {
        public static void main(String[] args) {
            int final y = 3;
            int x = 10;
    
            switch (x) {
                case 1:
                    System.out.println("Monday");
                    break;
                case x: //Valid
                    System.out.println("Tuesday");
                    break;
                default:
                    System.out.println("Weekend");
            }
        }
    }
    ```
    
* Both <mark>switch arguments and case label can be expression</mark> but must label should be constant expression.
    
* ```java
    public class SwitchExample {
        public static void main(String[] args) {
            int y = 3;
            int x = 10;
    
            switch (x) {
                case 1:
                    System.out.println("Monday");
                    break;
                case 12+20: //Valid
                    System.out.println("Tuesday");
                    break;
                default:
                    System.out.println("Weekend");
            }
        }
    }
    ```
    
* <mark>Case label should be in the range of switch argument type otherwise we will get compiled time error</mark>.
    
    ```java
    public class SwitchExample {
        public static void main(String[] args) {
            byte x = 10;
    
            switch (x) {
                case 1:
                case: 100;
                case: 1000; // found 'int' required 'byte'
            }
        }
    }
    ```
    
* Duplicate case are not allowed otherwise we will get compiled time error.
    
    ```java
    public class SwitchExample {
        public static void main(String[] args) {
            byte x = 10;
    
            switch (x) {
                case 32:
                case: 32; // Duplicate case label
            }
        }
    }
    ```
    

### Fall through inside `switch`

Within the switch <mark>if any case is matched from that case onwards all statement will be executed until break or end of the switch</mark> this is called fall through inside a switch.

The main advantage of fall through inside switch is we can define common action for multiple cases (code reusability).

```java
public class SwitchExample {
    public static void main(String[] args) {
        int x = 1;

        switch (x) {
            case 1:
                System.out.println("Monday");
            case 2: 
                System.out.println("Tuesday");
                break;
            default:
                System.out.println("Weekend");
        }
    }
}
```

In the above examples the output will be-

```java
Monday
Tuesday 
```

### `default`

* within the switch weekend take default case atmost once.
    
* `default` case will be executed if and only if there is no case matched.
    

Within `switch` statement we can write default case anywhere but it is recommended to write as last case.

```java
public class SwitchExample {
    public static void main(String[] args) {
        int y = 3;
        int x = 10;

        switch (x) {
            case 1:
                System.out.println("Monday");
                break;
            default:
                System.out.println("Weekend");
            case 2:
                System.out.println("Tuesday");
                break;
        }
    }
}
```

In the above examples the output will be-

```java
Weekend
```

## Conclusion

Decision-making in Java involves various statements, including if-else, nested if-else, if-else-if ladder, and switch. Understanding their syntax, rules, and use cases is crucial for effective control flow and decision logic in programming.
