Java Reference
In-Depth Information
Strings in a switch Statement
I discussed the
switch
statement in Chapter 5. Java 7 added support for strings in a
switch
statement. The
switch
-expression uses a
String
type. If the
switch
-expression is
null
, a
NullPointerException
is thrown. The
case
labels must be
String
literals. You cannot use
String
variables in the
case
labels. The following is an example of using
a
String
in a
switch
statement, which will print
"Turn on"
on the standard output:
String status = "on";
switch(status) {
case "on":
System.out.println("Turn on"); // Will execute this
break;
case "off":
System.out.println("Turn off");
break;
default:
System.out.println("Unknown command");
break;
}
The
switch
statement for strings compares the
switch
-expression with
case
labels as if the
equals()
method
of the
String
class has been invoked. In the above example,
status.equals("on")
will be invoked to test if the first
case
block should be executed. Note that the
equals()
method of the
String
class performs a case-sensitive string
comparison. It means that the
switch
statement that uses strings is case-sensitive.
The following
switch
statement will print
"Unknown command"
on the standard output, because the
switch-expression
"ON"
in uppercase will not match the first
case
label
"on"
in lowercase.
String status = "ON";
switch(status) {
case "on":
System.out.println("Turn on");
break;
case "off":
System.out.println("Turn off");
break;
default:
System.out.println("Unknown command"); // Will execute this
break;
}
As good programming practice, you need to do the following two things before executing a
switch
statement
with strings:
switch
-expression for the
switch
statement is
null
. If it is
null
, do not execute
the
switch
statement.
•
Check if the
switch
statement, you need to
convert the
switch
-expression to lowercase or uppercase and use lowercase or uppercase in
the
case
labels accordingly.
•
If you want to perform a case-insensitive comparison in a
You can rewrite the above
switch
statement example as shown in Listing 11-3, which takes care of the above
two suggestions.