String argument in switch statement
In the JDK 7 release, we can use a String object in the expression of a switch statement..
Example given below
class TestClass{
public integer getIntegerFromString(String stringFormat) {
integer number;
switch (stringFormat) {
case "One":
number=1;
break;
case "Two":number=2;break;
case "Three":number=3;break;
case "Four":number=4;break;
case "Five": number=5;
break;
case "Six":number=6;break;
case "Seven":
number=7;break;
case "Eight":
number=8;break;
case "Nine":
number=9;break;
case "Zero":
number=0;break;
default:System.out.println("Not an integer value");
}
return number;
}
public static void main(String arg[])
{
TestClass obj=new TestClass();
System.out.println("Integer value of Three is "+obj.getIntegerFromString("Three")) ;
}
}
The switch
statement compares the String
object in its expression with the expressions associated with each case
label as if it were using the String.equals
method; consequently, the comparison of String
objects in switch
statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch
statements that use String
objects than from chained if-then-else
statements