Blog

Java Switch case – Basic Java Course

Java Switch case - Basic Java Course

Selection Control :

Allows one set of statements to be executed if a condition is true and another set of actions to be executed if a condition is false.

Switch Case :

switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

  • A Switch statement can be easier than if-else statements
  • In the switch statement, we have multiple cases.
  • Only the matching case will be executed.
  • In the switch statement, we can only use int, chat, byte, and short data types.

Switch case Provides an easy way to dispatch the execution to different parts of code, In the switch case the duplicate cases are not allowed to use and value must be of the same data type as the variable in the switch.

The break statement is used to end the case, which is optional , if omitted , executions will continue in the next case.

Default switch case is used inside switch block, if the cases are not matched with any other cases then it comes to default case.

Program of switch case : Example

package practice_06;
public class SwitchCase 
{
   public static void main(String[] args) 
   {
      char choice = 'c';
      switch(choice)
      {
          case 'a':
              System.out.println("Inside case a");
              break;
          case 'b':
              System.out.println("Inside case b");
              break;
          case 'c':
              System.out.println("Inside case c");
              break;
          default:
              System.out.println("Inside default block.");
      }
       System.out.println("Outside of switch case.");
   }
    
}