Case Control Instruction

This passage provides an overview of the switch-case-default control instruction in Java, which is used to make decisions between multiple alternatives, offering a structured approach compared to a series of if statements. Here’s a summary of key points:

Structure of switch-case:

  • A switch statement evaluates an expression, and its value is compared with constants in the case clauses.
  • If a match is found, the program executes the corresponding statements until a break statement is encountered.
  • If no match is found, the default case is executed.

Example Code:

public class SwitchDemoProject {
public static void main (String[] args) {
int i = 2;
switch (i) {
case 1:
System.out.println(“I am in case 1”);
break;
case 2:
System.out.println(“I am in case 2”);
break;
case 3:
System.out.println(“I am in case 3”);
break;
default:
System.out.println(“I am in default”);
break;
}
}
}

Key Insights:

  1. Cases can be written in any order.
  2. Multiple statements per case don’t require braces.
  3. Each case must have unique constants (no duplicates).
  4. Break statements are essential to prevent fall-through, though it can be omitted if a fall-through is desired.
  5. Only byte, short, int, char, or string constants can be used in the switch expression (from JDK 7 onwards, strings can be checked).
  6. Expressions in the switch are allowed if they resolve to constant values.
  7. Nested switch statements are possible but rarely used.
  8. Switch is faster than an equivalent if-else ladder due to the use of a jump table for optimization.

Example of Multiple Cases with a Common Statement:

public class SwitchFormsProject {
    public static void main (String[] args) throws Exception {
        char ch;
        System.out.println("Enter an alphabet a or b");
        ch = (char) System.in.read();
        switch (ch) {
            case 'a':
            case 'A':
                System.out.println("a as in apple");
                break;
            case 'b':
            case 'B':
                System.out.println("b as in ball");
                break;
            default:
                System.out.println("wish you knew alphabets");
                break;
        }
    }
}

  • Here, both a and A share the same logic, demonstrating how fall-through can be used effectively when cases share the same outcome.

switch vs. if-else Ladder:

  • Advantages of switch: It’s faster than an if-else ladder due to the use of a jump table, which avoids checking conditions repeatedly.
  • Limitations of switch: It doesn’t support float, double, long, boolean, or variable expressions in cases.