Java switch

Java switch statement is used to select one of many code blocks to be executed.

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

How to Java switch works:

  • Matching each expression with case
  • Once it match, execute all case from where it matched.
  • Use break to exit from switch
  • Use default when expression does not match with any case

Sample program with if
Write a program or WAP to print the name of day from a number.

class SampleSwitch
{
   public static void main(String args[])
   {
        int day = 4;
      	switch (day) {
	  case 1:
		System.out.println("The day is Monday");
		break;
	  case 2:
		System.out.println("The day is Tuesday");
		break;
	  case 3:
		System.out.println("The day is Wednesday");
		break;
	  case 4:
		System.out.println("The day is Thursday");
		break;
	  case 5:
		System.out.println("The day is Friday");
		break;
	  case 6:
		System.out.println("The day is Saturday");
		break;
	  case 7:
		System.out.println("The day is Sunday");
		break;
          deafault:
                System.out.println("Please enter between 1 to 7.");
	} 
   }
}


Output:

The day is Thursday

java java tutorials learn java study java