on Leave a Comment

Java Switch Case Statement

The switch statement is java built-in multi-way decision statement. The switch statement test an expression with a list of case values and if the expression matches with case value, the block of statements followed by that case will execute.

Syntax:

switch(expression) 
{
   case value1:
      block1
      break; 
   
   case value2:
      block2
      break; 
   ......
   ......
   default : 
      // Statements
}

Rules for implementing switch statement:

The expression should be integer expression or character expression.

The value1, value2 are also integral constant.

All values should be unique in a switch statement.

We can use any number of case statements and each case statement is following by value and colon.

Each case block may contain zero or more statements.

It is not necessary to put braces around the blocks.

The default statement is optional and if you write default statement, it must appear after all the case statements.

Flow Chart
Java Switch Statement
Java Switch Statement

Example of Switch Statement

import java.util.Scanner;
class SwitchStatement
{
 public static void main(String[] args) {
  System.out.print("Enter a number between 1 to 7 : ");
  Scanner sc = new Scanner(System.in);
  int x = sc.nextInt();
  String day;
  switch(x)
  {
   case 1:  
         day = "Monday";
         System.out.println(day);
                              break;
                        case 2:  
                              day = "Tuesday";
                              System.out.println(day);
                              break;
                        case 3:  
                              day = "Wednesday";
                              System.out.println(day);
                              break;
                        case 4:
                               day = "Thursday";
                               System.out.println(day);
                               break;
                        case 5:
                               day = "Friday";
                               System.out.println(day);
                               break;
                        case 6:
                               day = "Saturday";
                               System.out.println(day);
                               break;
                        case 7:
                               day = "Sunday";
                               System.out.println(day);
                               break;
                       default:
                               day = "Invalid day";
                               System.out.println(day);
                               break;
  }
 }
}

Output:

Enter a number between 1 to 7 : 6
Saturday

In this program value of x will compared with case values, if any match is found, that case block will execute, otherwise default statements will execute. 

0 comments:

Post a Comment