Java Reference
In-Depth Information
Another difference in using a ternary operator and an
if-else
statement is that you can use an expression, which
uses a ternary operator as an argument to a method. However, you cannot use an
if-else
statement as an argument
to a method. Suppose you have a
calc()
method that accepts an
int
as an argument. You have two integers,
num1
and
num2
. If you want to pass the minimum of the two integers to the
calc()
method, you would write the code as shown:
// Use of an if-else statement
if (num1 < num2)
calc(num1);
else
calc(num2);
// Use of a ternary operator
calc(num1 < num2 ? num1 : num2)
Suppose you want to print the message
"k is 15"
if the value of an
int
variable
k
is equal to
15
. Otherwise, you
want to print the message
"k is not 15"
. You can print the message using a ternary operator writing one line of code
as follows:
System.out.println(k == 15 ? "k is 15" : "k is not 15");
The switch Statement
The general form of a
switch
statement is
switch (switch-expression) {
case label1:
statements
case label2:
statements
case label3:
statements
default:
statements
}
The
switch-expression
must evaluate to a type:
byte
,
short
,
char
,
int
,
enum
, or
String
. The
enum
type
(shorthand for enumerated type) was introduced in Java 5. Please refer to the chapter on enums for details on how
to use an
enum
type in a
switch
statement. Java 7 added support for the
String
type in a
switch
statement. Please
refer to Chapter 11 for details on how to use strings in a
switch
statement. The
label1
,
label2
, etc. are compile-time
constant expressions whose values must be in the range of the type of the
switch-expression
. A
switch
statement
is evaluated as follows:
switch-expression
is evaluated.
•
The
switch-expression
matches a
case
label, the execution starts from the
matched
case
label and executes all statements until the end of the
switch
statement.
•
If the value of the
switch-expression
does not match a
case
label, execution starts at the
statement following the optional
default
label and continues until the end of the
switch
statement.
•
If the value of the