Java Switch

18-Sep-2024

Understand how to use the switch statement in Java.

  

In the swtich control statement. The case block code will be executed whose case value matches the expression. If no case value matches the expression, the default case block is executed


Syntax :



switch ( expression ) {
case value1:
// if value1 is equal to the expression then this block will executed
// statements
break;
case value2: System.out.println("golpo");
// if value2 is equal to the expression then this block will executed
// statements
break;
case value3: System.out.println("coto golpo");
// if value3 is equal to the expression then this block will executed
// statements
break;
default:
// If no case is matched by the expression then the default case block will be executed
// statements
}



Flow Chart:


              



 Example:




import java.util.Scanner;
public class switch_test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
      int button = sc.nextInt();
     
switch ( button ) {
        case 1:
System.out.println("kobita");
        break;
        case 2:
System.out.println("golpo");  
        break;
        case 3:
System.out.println("coto golpo");
        break;
        default:
System.out.println("invalid button");
}
           
     }

}
     
     


In this example, if the value of the button is 1 then the first case code block will be executed else the next case will be checked if the value of the button is 2 then this second code block will be executed if the value of the button is not matched in this case also the third case will be checked if the value of the button 3 then this case block will be executed. If the value of all cases does not match the expression then the default code block will be executed.

now let's talk about the break statement in each case. The break statement is optional in each case. If you don't use the break statement then what will happen? see in the next example





import java.util.Scanner;
public class switch_test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
      int button = sc.nextInt();
     
switch ( button ) {
        case 1:
System.out.println("kobita");
        case 2:
System.out.println("golpo");  
        case 3:
System.out.println("coto golpo");
        default:
System.out.println("invalid button");
}
           
     }

}
     
     


Suppose the button value is 1. Then the first case will executed because the case value is matched by the expression. but the problem is next each case including the default case will execute automatically without checking the case condition. When we use the break statement the case which matched by the expression will execute and break the switch control. and lastly, we got the desired output.



Comments