In the JDK 7 release, you can use a String
object in the expression of a switch
statement.
Comparing string object is case sensitive.
1: public class TEST {
2:
3: public static void testSwt(String testswitch) {
4: String tw;
5: switch (testswitch) {
6: case "teststr":
7: tw = "TestingSwitch with String";
8: break;
9: case "testswitch2":
10: tw = "Testing Switch with String one";
11: break;
12: case "testswitch3":
13: tw = "Testing Switch with String two";
14: break;
15: default:
16: tw = "ERROR";
17: break;
18: }
19: System.out.println(tw);
20:
21: }
22:
23: public static void main(String[] args) {
24: String strswitch = "teststr";
25: TEST.testSwt(strswitch);
26:
27: }
28: }
The Java compiler generates generally more efficient bytecode from switch
statements that use String
objects than from chained if-then-else
statements.
No comments:
Post a Comment