- JAVA SE 06 or earlier :- Not Allowed
- JAVA SE 07 or later :- Allowed
Use of string in switch case is allowed in Java from version 1.7, i.e. if you are using Java version 7 or later, you may use string in switch case if needed.
Consider this example :
class StringCaseDemo
{
public static void main(String args[])
{
String country=args[0];// value specified by user (comm-line args)
switch (country)
{
case "india":
System.out.println( "Country Code is +91 ");
break;
case "usa":
System.out.println( "Country Code is +1 ");
break;
case "italy":
System.out.println( "Country Code is +39 ");
break;
case "spain":
System.out.println( "Country Code is +34 ");
break;
default:
System.out.println( "Invalid Country Code ");
} // end of switch
}
}
The above code works well with Java 1.7 (or later). But Java versions < 1.7 gives compile-time error.