Java Reference
In-Depth Information
Here is the output from the program:
As you can see, the original string
orgstr
is unchanged, and
substr
contains the sub-
string.
Using a String to Control a switch Statement
As explained in
Chapter 3
, prior to JDK 7, a
switch
had to be controlled by an integer type,
such as
int
or
char
. This precluded the use of a
switch
in situations in which one of several
actions is selected based on the contents of a string. Instead, an
if
-
else
-
if
ladder was the
typical solution. Although an
if
-
else
-
if
ladder is semantically correct, a
switch
statement
would be the more natural idiom for such a selection. Fortunately, this situation has been
remedied. Today, you can use a
String
to control a switch. This results in more readable,
streamlined code in many situations.
Here is an example that demonstrates controlling a
switch
with a
String
: