Another way of controlling the flow of your program is with switch statement. Switch gives you an option to test the range of your value and depending on the value you can execute a particular case. For example.

switch(switchValue){
case 1:
  System.out.println("Value 1");
  break;
case 2:
  System.out.println("Value 2");
  break;
case 3:
  System.out.println("Value 3");
  break;
default:
  System.out.println("Deafult Case");
  break;
}

In the above example, the value we are testing is switchValue. Depending on the switchValue, a particular case will be executed. Considering the value to be 2, Case 2 will be executed. Notice the break statement at the end of every case. break statements are used to exit the loop. If you don't end your case with break statement all the next cases will get executed.

default: case is executed in case none of you defined case match the value passed into your switch statement.

Note that the value in consideration for the switch statement can be of type that can be byte, short, int, char, boolean and String. Your case option value should have the same type as the value you passed into your switch statement.

Exercise Question
1. Write a program to Print the month number from the Month Name. Your switch statement should accept a String and the cases should be denoted with month name i.e. january, february, march etc. When a particular case is executed it should print the month Number, 1 for january, 2 for february and so on. Default case should print message of "Invalid Input"

Comments