Monday, 5 October 2015

IMPROVEMENTS OF SWITCH STATEMENT IN JAVA 7

This post discuss one of improvements of Switch statement in Java 7. Just before discussing about the improvements, Lets recapitulate the well known Switch statement. How it works.

Typical Syntax:

switch  (expression) {

    case label1:

                     statements;

    case label2:

                     statements;

    case label3:
                     statements;
         . . . 
    default:
                     statements;
}


Initially, the expression is evaluated. If the value of the expression is matched to any of the case labels, from the matched case label - its start executing the statements till the end of the switch statement. For example, if value matches to label2, then it executes all the statements from the case label2 till the end of the switch statement and even the optional default label statements are executed.

If the value of the expression is not matched to any of the case labels then it executes the statements under the optional default label.

Note: But generally, we use switch statement to execute one of many possibilities. so we use break statement to stop all other statements after that matched case. 

Example:
// without break;

 int age = 10;
 switch (age) {
 case 10: // Found the match
  System.out.println("Age 10"); // Execution starts here
 case 20:
  System.out.println("Age 20");
 default:
  System.out.println("AgeLess");
 }

Output:
             Age 10
             Age 20
             AgeLess


The expression must evaluate to a type : byte, short, char, int, enum.

In addition to these types, Java 7 added support for Strings in a SWITCH statement.

Expression : String Type

The expression uses a String type. If the expression is evaluating to a null, then a NullPointerException is thrown. The case labels must be String literals.

You cannot use String variables (non-final variables) in the case labels. Can use constants (final variables) as case labels.

Example:

String company = "alphabet";

 switch (company) {

 case "google":
  System.out.println("google");
  break;
 case "facebook":
  System.out.println("facebook");
  break;
 case "alphabet":
  System.out.println("alphabet");
  break;
 default:
  System.out.println("Company Not Found");
  break;

 }

Output:
            alphabet

(does not execute the default label statements because we have used break statement under matched case "alphabet")

Note: The above code fails to compile before java 1.7.
This feature works properly from java 1.7 and above.

Some variants of switch statements:

>> If expression does not match and expression is evaluating to a type int:
/*
  * expression evaluating to int type 
  * match does not match any case label
  */

 int num = 50;
 switch (num) {
 case 10:
  System.out.println("Ten");
 case 20:
  System.out.println("Twenty");
 default:
  System.out.println("No-match"); /* Execution starts here */
 }

Output:
       
No-match


>>You can place the optional default label any where in order. Its not mandatory to place as a last label. But as a convention, its better to place as a last option.

char currency = '$';
 switch (currency) {
 case '€':
  System.out.println("Euro");
 default:
  System.out.println("No Proper Currency"); 
 case '$': //As match is found
  System.out.println("Dollar"); // Execution starts here
 }

 Output:
        Dollar


/*
  * default label can be anywhere and is optional By convention, 
  * most of developers use as last label
  */

 char currency = '@';
 switch (currency) {
 case '€':
  System.out.println("Euro");
 default: //As No match is found
  System.out.println("No Proper Currency"); // Execution starts here
 case '$':
  System.out.println("Dollar");
 }

Output:
        No Proper Currency
        Dollar



>>When expression evaluating to a byte type. Important to remember the byte type value range is -128 to 127 only.

Possible compile-time errors:


//remember byte data type range is -128 to 127
   
  byte b = 10; 
  
  switch (b) {
  case 5:
   System.out.println("Its five");
  case 50:
   System.out.println("Its fifty");
 /* case 150:  fails : A compile-time error. 150 is greater than 127
   b--; */
     default: 
      System.out.println("Its Zero"); 
     }
Output:
         Its Zero

>>should not use duplicate case labels.
int num = 10;

    switch (num) {
    
    case 10: 
     num++; 
    
    case 10:   // fails: CE: same case label 
     num--; 
    
    default: 
     num =100; 
     } 
Output: 
         compile time error:  Duplicate Case

>>should not use variables in case labels. constants are allowed
/*
  * num2 is not a constant 
  * should not use a variable as case label
  */
 int num1 = 10;
 int num2 = 10;

 switch (num1) {
 case 20:
  System.out.println("num1 is 20");

 case num2: // A Compile-time error.
  System.out.println("num1 is 10");
 }

Output:
       compile time error: case expression must be a constant expressions

>> the expression can use an enum type. Here, the case labels must use unqualified enum values. 

Example:
/*
 * An enum defined with three values
 * This enum has to be given to switch
 * as expression
 */
public enum Facility {
 
 ORDINARY,
 
 SEMI_LUXUCY,
 
 LUXURY

}

public class EnumSwitch {

 public static void main(String[] args) {

  Facility fac = Facility.LUXURY; // passing this input param.

  String facility_code = getFacility(fac);
  System.out.println("Code of Facility.LUXURY is " + 
  facility_code);

 }

 private static String getFacility(Facility facility) {
  String fa_code = "";

  // passing Enum as expression
  switch (facility) {
  /*
   * Cannot use Must use Enum value only 
   * Must not quality with Enum i.e,
   * should not use Facility.ORDINARY in case labels
   */
  case ORDINARY:
   fa_code = "ORD";
   break;
  case SEMI_LUXUCY:
   fa_code = "SEM";
   break;
  case LUXURY:
   fa_code = "LUX";
   break;
  }
  return fa_code;
 }

}

 Output:
         Code of Facility.LUXURY is LUX 

Thanks for reading                         Hope u like it :)                               Please share :)

No comments:

Post a Comment