Friday, 19 August 2016

Switch-Case statement in Java

Switch case statement is Java's decision statement which can have a number of possible execution paths. It provides an easy and more readable way to execute a set of code based on the value of the expression.

General form of switch-case statement

switch (expression) {
 case value1:
  // statement
  break;
 case value2:
  // statement
  break;
 .
 .
 .
 case valueN :
  // statement
  break;
 default:
  // default statement
}

Switch works with byte,short, char, and int primitive data types and their wrapper classes Character,  Byte, Short, and Integer. Starting Java 7 it also works with String in Java.

Execution path of switch-case statement

When a value is passed in the switch expression it is compared with the value of each case statement, if match is found the code following that case statement is executed. Code execution with in the case statement is terminated when the break statement is encountered. As soon as the break statement is encountered no other case statement is executed and control comes out of the switch case statement.

If none of the values in the case statement matches the value of the expression then the default statement is executed. Note that default statement is not mandatory though. If none of the values in the case statement matches the value of the expression and default statement is also not there then control will come out of the switch-case statement executing nothing.

It is not mandatory to have break statement in every case statement, in case break statement is omitted in any case statement, next case statement will also be executed though it doesn't match the value of the expression. That can be used to group a set of case statements but omission due to negligence will result in execution of several case statements in place of a single matching one. See example for more clarity.

Also note that the type of each value must be compatible with the type of expression.

Switch-case statement example

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 7;
  switch(month){
   case 1: System.out.println("Month is January"); 
   break;
   case 2: System.out.println("Month is February"); 
   break;
   case 3: System.out.println("Month is March"); 
   break;
   case 4: System.out.println("Month is April"); 
   break;
   case 5: System.out.println("Month is May"); 
   break;
   case 6: System.out.println("Month is June"); 
   break;
   case 7: System.out.println("Month is July"); 
   break;
   case 8: System.out.println("Month is August"); 
   break;
   case 9: System.out.println("Month is September"); 
   break;
   case 10: System.out.println("Month is October"); 
   break;
   case 11: System.out.println("Month is November"); 
   break;
   case 12: System.out.println("Month is Decmber"); 
   break;
  }

 }

}

Output

Month is July

Here month expression has the value 7 so it will go to the case statement which has value 7 and execute the statements with in that case statement and then break out.

Note that default statement is not used this code.

Let us change this example to pass month as 13 and have a default statement to encounter such cases.

Java code

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 13;
  switch(month){
   case 1: System.out.println("Month is January"); 
   break;
   case 2: System.out.println("Month is February"); 
   break;
   case 3: System.out.println("Month is March"); 
   break;
   case 4: System.out.println("Month is April"); 
   break;
   case 5: System.out.println("Month is May"); 
   break;
   case 6: System.out.println("Month is June"); 
   break;
   case 7: System.out.println("Month is July"); 
   break;
   case 8: System.out.println("Month is August"); 
   break;
   case 9: System.out.println("Month is September"); 
   break;
   case 10: System.out.println("Month is October"); 
   break;
   case 11: System.out.println("Month is November"); 
   break;
   case 12: System.out.println("Month is Decmber"); 
   break;
   default: System.out.println("Invalid month value passed");
  }
 }
}

Output

Invalid month value passed

Example omitting break statement

As stated above break statement is not mandatory but it will result in execution of the next case statement.

Java code

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 7;
  
  switch(month){
   case 1: System.out.println("Month is January");
   
   case 2: System.out.println("Month is February"); 
   
   case 3: System.out.println("Month is March"); 
   
   case 4: System.out.println("Month is April"); 
   
   case 5: System.out.println("Month is May"); 
   
   case 6: System.out.println("Month is June"); 
   
   case 7: System.out.println("Month is July"); 
   
   case 8: System.out.println("Month is August"); 
   
   case 9: System.out.println("Month is September"); 
   
   case 10: System.out.println("Month is October"); 
   
   case 11: System.out.println("Month is November"); 
   
   case 12: System.out.println("Month is Decmber"); 
   
   default: System.out.println("Invalid month value passed");
  }

 }

}

Output

Month is July
Month is August
Month is September
Month is October
Month is November
Month is Decmber
Invalid month value passed

In the above switch case statement break is not used with any case statement. Since month passed is 7 so control will go to the case statement having value 7 and start executing the code with in that case statement but it won't know when to break so all the following case statements (even default) are executed.

Case statements can be grouped by omitting the break statement. As example if you want to display the quarter passed month falls into then you can group three case statements where break statement is used with only the last one in the group.

Java Code

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 5;
  
  switch(month){
   case 1: 
   
   case 2: 
   
   case 3: System.out.println("Quarter 1"); 
     break;
   
   case 4: 
   
   case 5:  
   
   case 6: System.out.println("Quarter 2"); 
     break;
   
   case 7:
   
   case 8:
   
   case 9: System.out.println("Quarter 3"); 
     break;
   
   case 10:  
   
   case 11: 
   
   case 12: System.out.println("Quarter 4"); 
      break;
   
   default: System.out.println("Invalid month value passed");
  }

 }

}

Output

Quarter 2

Using Strings in switch Statements

In Java SE 7 and later, you can use a  String object in the switch statement's expression.

 
public class StringSwitchDemo {

 public static void main(String[] args) {
  String dept = "Human Resources";
  String deptCd = null;
  switch(dept.toLowerCase()){
   case "account": 
    deptCd = "acct";
    break;
   case "human resources": 
    deptCd = "hr";
    break;
   case "administration":
    deptCd = "admin";
    break;
   default: System.out.println("Invalid deprtment");
  }
  
  System.out.println("Department - " + deptCd);
 }

}

Output

Department – hr

Nested switch statements

You can have nested switch-case statement with in the outer switch statement.

switch(month){
 case 1:
 switch(week){
  case 1: .....
         break;
  case 2 : ....

  ...
  ...
 }
 break;
}

Switch-case statement efficiency

If you have to make a choice between sequence of if-else stateemnt and switch-case statement opt for switch case as it will run faster.

Reason being when the Java compiler compiles a swith-case statement it will go through all the case statement values (which are constants) and make a jump table. The value on which the switch is being performed is used as an index into the jump table to directly go to that case statement. In the case of switch-case statemnt it can be done as compiler knows that case values are all of sane type and switch expression can only be used for equality test with case values.

Points to note

  1. Value of the case statement can only be a constant expression.
  2. Switch case statement can only be used for equality test. No other boolean expression like greater than, not equal to etc. can be used with switch statement.
  3. Duplicate case values are not allowed, each case statement should have a unique value.
  4. default statement is not mandatory.
  5. break statement is also not mandatory. Leaving break statement with in a case statement will result in the execution of the next case statement.
  6. From Java 7 string class can also be used with switch case.

That's all for this topic Switch-case statement in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. String in Java
  2. Ternary operator in Java
  3. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

No comments:

Post a Comment