Saturday, February 4, 2012

Java 7 Language Enhancements - Use String in the switch statement

Switch statement is used to evaluate expressions based only on a single integer, enumerated value, or String object. Therefore it cannot be used to evaluate a range expression.

Before Java 7, strings were not supported in the switch statement. Below is the code which demonstrates the use of a switch statement using a string expression

com.benjmaz.string

public class SwitchDemo {
 public static void main(String[] args){

        String ans="A";
        switch (ans){
            case "C":
             System.out.println("C is the answer");
             break;
            case "B":
             System.out.println("B is the answer");
             break;
            case "D":
             System.out.println("D is the answer");
             break;
            case "A":
             System.out.println("A is the answer");
            default:
             System.out.println("This is the default answer");
        }
    }
}

What would be output? Yes you guessed right! The output will be

A is the Answer
This is the default answer

The default statement was execute since case "A" block is not terminated by break, hence execution continues to the default block

Lets look at the second scenario. We have opted to embed the default block in the midst of other statements. Analyze the code and suggest as to whether the code will compile or not, and if it compiles what would be the result

com.benjmaz.string

public class SwitchDemo {

 public static void main(String[] args){
        String ans="X";
        switch (ans){
            case "C":
             System.out.println("C is a the answer");
             break;
            default:
             System.out.println("This is the default answer");
         case "B":
             System.out.println("B is a the answer");
             break;
            case "D":
             System.out.println("D is a the answer");
             break;
            case "A":
             System.out.println("Buza! A is the answer");
        }
    }
}

The above code will compile and the output will be

This is the default answer
B is the answer

Note the "B is the answer" is printed as well due to the fault that break statement was omitted in the default block hence case B block was executed as well.

If you are working out towards Java 7 certification, you need to be mindful and alert on all the possible ways (legal and illegal) how the switch statement can be constructed

No comments:

Post a Comment