Java Reference
In-Depth Information
else
car.door.open();
If
car.door.isOpen()
and
car.key.isPresent()
each return true,
car.start()
executes. If
car.door.isOpen()
returns true and
car.key.isPresent()
returns false,
car.door.open();
executes. At-
tempting to open an open door makes no sense.
The developer must have wanted the else to match the outer if, but forgot that else
matches the nearest if. This problem can be fixed by surrounding the inner if with
braces, as follows:
if (car.door.isOpen())
{
if (car.key.isPresent())
car.start();
}
else
car.door.open();
When
car.door.isOpen()
returns true, the compound statement executes.
When this method returns false,
car.door.open();
executes, which makes
sense.
Forgettingthatelsematchesthenearestifandusingpoorindentationtoobscurethis
fact is known as the
dangling-else problem
.
Switch Statement
Theswitchstatementletsyouchoosefromamongseveralexecutionpathsinamoreef-
ficient manner than with equivalent chained if-else statements. This statement has the
following syntax:
switch (
selector expression
)
{
case
value1
:
statement1
[break;]
case
value2
:
statement2
[break;]
…
case
valueN
:
statementN
[break;]
[default:
statement
]
}
Switch consists of reserved word
switch
, followed by a
selector expres-
sion
inparentheses,followedbyabodyofcases.The
selector expression
is