Selection statements | Java

Selection statements | Java

Flow control • Java Fundamentals

  • 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:

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 -

      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 -

      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) -

      int x = 10;
      if (x == 20) { 
          System.out.println("Program executed successfully");
      } else {
          System.out.println("Program failed");
      }
    

    Example 4 (Valid) -

      int x = true;
      if (x == false) { 
          System.out.println("Program executed successfully");
      } else {
          System.out.println("Program failed");
      }
    
  • else part and curly braces are optional in Java.

  • Without curly braces and only one statement is allowed which should not be declarative statement.

    Example -

      // 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:

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:

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
}

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.

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

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.

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. 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:

      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:

    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.

  • We cannot use boolean because if we go for boolean only two cases are possible so better go for if else.

  • 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.

      //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.

      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.

      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");
              }
          }
      }
    
      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 switch arguments and case label can be expression but must label should be constant expression.

  •   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");
              }
          }
      }
    
  • Case label should be in the range of switch argument type otherwise we will get compiled time error.

      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.

      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 if any case is matched from that case onwards all statement will be executed until break or end of the switch 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).

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-

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.

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-

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.

Did you find this article valuable?

Support Xander Billa by becoming a sponsor. Any amount is appreciated!