DEV Community

Deepikandas
Deepikandas

Posted on

#20 Known is a drop! Switch statement & Switch Expression JAVA-Tricky Questions

1.Traditional Switch Statement (Java ≤ 16)

  • Purpose: Execute code blocks
  • Syntax: Uses : after case
  • Break: Required to prevent fall-through
  • Return value: ❌ Cannot return
  • Multi-label: ❌ Not allowed (before Java 14)
  • Null: ❌ Not allowed for objects (NullPointerException)
    2.Enhanced Switch Expression (Java 14+)

  • Purpose: Produces a value (can be returned/assigned)

  • Syntax: Uses -> (arrow)

  • Break: ❌ Not needed

  • Multi-label: ✅ Allowed (case 1,2,3 -> ...)

  • Null: ✅ Allowed (case null -> ...) in Java 17+

  • Multi-statement block: ✅ Use { ... yield ... }
    3.Switch Expression with Pattern Matching (Java 17+)

-case Type variable → automatically checks type & assigns variable
-Can combine pattern matching + multi-label + null + yield.

  • Safer and cleaner than instanceof + cast
  • Works with switch expressions only (not old style) 4.Multi-statement block in Expression
  1. Use yield to return a value from a block
  2. All branches must produce same type (String here)
1.public class Sample {
    public static void main(String[] args) {
        int x = 2;
        switch(x) {
            case 1:
           System.out.println("One");
           break;
            case 2:
             System.out.println("Two");
              break;
            case 3:
            System.out.println("Three");
            break;
            default:
            System.out.println("Default");
                   }
}
}
output: Two
Enter fullscreen mode Exit fullscreen mode
//After java 8th version switch case :
2.public class Sample {
    public static void main(String[] args) {
    int x = 2;
    switch(x) {
    case 1 -> System.out.println("Hi");
    case 2 -> System.out.println("Welcome");
    default -> System.out.println("Hello");
        }//no need of semicolon as switch expression is not used
}
}
output: Welcome
Enter fullscreen mode Exit fullscreen mode
public class Sample {

    public static void main(String[] args) {
        int x = 2;
        int result = switch(x) {
            case 1 -> 10;
            case 2 -> 20;
            default -> 0;
        };//semicolon must
        System.out.println(result);
}
}
output: 20
Enter fullscreen mode Exit fullscreen mode
public class Sample {

    public static void main(String[] args) {
        int x = 1;
        int result = switch(x) {
            case 1 -> {
                System.out.println("One");
            }
            default -> 0;
        };

}
}

**Compile time error:**
A switch labeled block in a switch expression must yield a value or throw an an exception
**Reason:**case 1-> should return a value like case 1->1
without using curly braces.
When curly braces used,"yield" key word is used.
eg: case 1 -> {             System.out.println("One");
yield 1;
    }
NOte:yield must be end of the case1 block.
Enter fullscreen mode Exit fullscreen mode
//After java 14th version switch case :Multiple labels
public class Sample {
    public static void main(String[] args) {
        int x = 3;
        int result = switch(x) {
            case 1, 2 -> 10;
            case 3 -> 20;
            default -> 0;
        };
System.out.println("value of result: "+result);
}
}
Output: value of result: 20
Enter fullscreen mode Exit fullscreen mode
After java 17th version switch case(Java 17+ (Pattern matching switch case) :
public class Sample {
    public static void main(String[] args) {
        Object obj = "Hello";
        switch(obj) {
    case String s -> System.out.println(s.length());
    case Integer i -> System.out.println(i * 2);
    default -> System.out.println("Other");
        }
}
}
output: 5
Enter fullscreen mode Exit fullscreen mode
//After java 17th version switch case(Java 17+ (Pattern matching switch case) :
public class Sample {
    public static void main(String[] args) {
        Object obj = "Hello";
        switch(obj) {
            case String s -> System.out.println("length of string : "+s.length());
            case Integer i -> System.out.println(i * 2);
            default -> System.out.println("Other");
        }           
        }
}
output:length of string : 5
Enter fullscreen mode Exit fullscreen mode
public static void main(String[] args) {
        int x = 2;
        switch(x) {
            case 1:
                System.out.println("One");
            case 2:
                System.out.println("Two");
            case 3:
                System.out.println("Three");
            default:
                System.out.println("Default");
        }
output:(Fall through)
Two
Three
Default
Enter fullscreen mode Exit fullscreen mode
char ch = 'A';
switch(ch) {
    case 65:
        System.out.println("ASCII 65");
        break;
    case 'A':
        System.out.println("Character A");
}

Compile error: 
 duplicate case label
                case 'A':
Enter fullscreen mode Exit fullscreen mode
public class Sample {
    public static void main(String[] args) {
        int x = 10;
        switch(x / 2) {
            case 5:
                System.out.println("Five");
                break;
            case 10:
                System.out.println("Ten");
        }
        }
}
output: Five
Enter fullscreen mode Exit fullscreen mode
//final makes it constant → allowed in case
public class Sample {
    public static void main(String[] args) {
final int a = 1;
        int b = 2;
        switch(b) {
            case a:
                System.out.println("A");
                break;
            case a + 1:
                System.out.println("A+1: "+a);
        }

        }
}
output: A+1: 1
Enter fullscreen mode Exit fullscreen mode
Case labels are case sensitive
public class Sample {
    public static void main(String[] args) {
        String s = "Java";
        switch(s) {
            case "Java":
                System.out.println("Java");
                break;
            case "JAVA":
                System.out.println("JAVA");
                break;
        }

        }
}
output:
Java
Enter fullscreen mode Exit fullscreen mode
//Switch case label should be null to handle null pointer exception when null is used.
public class Sample {
    public static void main(String[] args) {
        String s = null;
        switch(s) {
            case "Hi":
                System.out.println("Hi");
                break;
            default:
                System.out.println("Default");
        }


        }
}
output:
Nullpointer exception
Enter fullscreen mode Exit fullscreen mode
int x = 1;
switch(x) {
    case 1:
        System.out.println("One");
        break;
    case 1:
        System.out.println("Duplicate");
}
compile time error: Duplicate case

Enter fullscreen mode Exit fullscreen mode
final int a = 2;
switch(2) {
    case a:
        System.out.println("A");
        break;
    case 2:
        System.out.println("Two");
}

compile time error: Duplicate case
Enter fullscreen mode Exit fullscreen mode
public class Sample {
    public static void main(String[] args) {
        int x = 1;
        switch(x) {
            case 1:
                switch(x + 1) {
                    case 2:
                        System.out.println("Inner Two");
                }
            case 2:
                System.out.println("Outer Two");
        }
        }
}
output:
Inner Two
Outer Two
Enter fullscreen mode Exit fullscreen mode
public class Sample {
    public static void main(String[] args) {
        int x = 1;
        switch(x) {
            case 1:
                switch(x + 1) {
                    case 2:
                        System.out.println("Inner Two");

                }
                        case 4:
                System.out.println("Outer Two");
        }
        }
}
output: no break for case1 block
Inner Two
Outer Two
Enter fullscreen mode Exit fullscreen mode

Top comments (0)