DEV Community

velvizhi Muthu
velvizhi Muthu

Posted on

Module 2-Switch case

Switch case:

  1. What is Switch case? Switch ,default and case is java key words. The switch statement in Java is used for multi-way branching — it lets you execute different blocks of code based on the value of a variable or expression.

02.How It Works?
The expression is evaluated once.
The value is compared with each case.
If a match is found, the corresponding block runs.
break exits the switch block (without it, fall-through happens).
default is optional and runs if no case matches.

03.What is a case?
A case is a label inside a switch block that represents a possible value of the switch expression.

04.How case works?
The switch expression is compared to each case value.
If a match is found, that case block runs.
break is used to stop further execution after a match.

Important Notes:
Each case value must be unique.
case values must be constant expressions (not variables).
Without break, the switch falls through to the next case.

Term Meaning
case A possible value to match in a switch
break Stops execution of more case blocks
default Runs if no case matches

Example Program:

//Java version 1.0
    //int tamilMark = 150;// Y
    //byte tamilMark = 100;//Y
    //short tamilMark = 150;//Y
    //long tamilMark = 150; //N
    //float tamilMark = 10.0f;//N
    //double tamilMark = 10.0;//N
    //char tamilMark = 'a';//Y
    //boolean tamilMark = true;//N

    //java 7th version
    String name = "kumar";//Y

    switch(name) //Expression
    {
    case "nantha" :
        System.out.println("fail");
        break;
    case "kumar" :
        System.out.println("Average");
        break;
    case "mukesh":
        System.out.println("Very Good");
        break;
    default :
        System.out.println("student not present");
    }
Enter fullscreen mode Exit fullscreen mode

    String name = "kumar";//Y
    switch(name) //Expression
    {
    case "nantha" -> System.out.println("fail");
    case "kumar" -> System.out.println("Average");
    case "mukesh" -> System.out.println("Very Good");
    default -> System.out.println("student not present");
    }
Enter fullscreen mode Exit fullscreen mode

    String name = "kumar";//Y
    int result = switch(name) //Expression
    {
    case "nantha" -> 1;
    case "kumar" -> 2;
    case "mukesh" -> 3;
    default -> 4;
    };
    System.out.println(result);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)