How to use String in a Switch Statement with JDK 7


Before JDK 7  using String class in a Switch statement was not allowed by Java.
Now by using JDK 7 programmers are allowed to use Strings in Switch statements.

Sample error

Exception in thread “main” java.lang.RuntimeException: Uncompilable source code – strings in switch are not supported in -source 1.6
  (use -source 7 or higher to enable strings in switch)
    at stringsinswitch.StringsInSwitch.testingSwitch(StringsInSwitch.java:20)
    at stringsinswitch.StringsInSwitch.main(StringsInSwitch.java:14)
Java Result: 1

Before JDK 7 Switch statement allows programmers to use the following values;

byte
short
char
int
Enums

With JDK 7

All of the above types + String

Sample program;

package stringsinswitch;

/**
*
* @author tunatore
*/
public class StringsInSwitch {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//JDK 7 allows programmers using Strings in Switch statement
StringsInSwitch.testingSwitch(“string1”);
StringsInSwitch.testingSwitch(“string2”);
StringsInSwitch.testingSwitch(“”);
}
public static void testingSwitch(String inStr) {

switch (inStr) {
case “string1”:
System.out.println(“string1”);
break;
case “string2”:
System.out.println(“string2”);
break;
default:
System.out.println(“inside –>  Default”);
break;
}

}
}

Output of the program;

run:
string1
string2
inside –>  Default
BUILD SUCCESSFUL (total time: 0 seconds)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s