Java Reference
In-Depth Information
greetings = Hello, length = 5
greetings = Hello, length = 5
greetings = Hi, length = 2
Radius = 2.30, Area = 16.62
The switch Statement
The
switch
statement in Nashorn works pretty much the same as the
switch
statement in
Java works. Its syntax is:
switch(expression) {
case expression-1:
statement-1;
case expression-2:
statement-2;
default:
statement-3;
}
The
expression
is matched against the expressions in
case
clauses using the
===
operator. The statements in the first matched
case
clause are executed. If the
case
clause
contains a
break
statement, the control is transferred to the end of the
switch
statement;
otherwise, the statements following the matched
case
clause are executed. If no match is
found, the statements in the
default
clause are executed. If there are multiple matches,
only the statements in the first matched
case
clause are executed. In Java, the
expression
must be of type
int
,
String
, or
enum,
whereas in Nashorn the
expression
can be of any
type including the Object, Null, and Undefined types. The following snippet of code
demonstrates how to use a
switch
statement:
// Define a match function that matches the passed in argument
// using a switch statement
function match(value) {
switch (value) {
case undefined:
print("Matched undefined:", value);
break;
case null:
print("Matched null:", value);
break;
case '2':
print("Matched string '2':", value);
break;
Search WWH ::
Custom Search