A statement is a single command that performs some activity when executed by the Java interpreter:
GigSim
simulator
=
new
GigSim
(
"Let's play guitar!"
);
Java statements include the following varieties: expression, empty, block, conditional, iteration, transfer of control, exception handling, variable, labeled, assert, and synchronized.
Reserved Java words used in statements are if
, else
, switch
, case
, while
, do
, for
, break
, continue
, return
, synchronized
, throw
, try
, catch
, finally
, and assert
.
An expression statement is a statement that changes the program state. It is a Java expression that ends in a semicolon. Expression statements include assignments, prefix and postfix increments, prefix and postfix decrements, object creation, and method calls. The following are examples of expression statements:
isWithinOperatingHours
=
true
;
++
fret
;
patron
++;
--
glassOfWater
;
pick
--;
Guitarist
guitarist
=
new
Guitarist
();
guitarist
.
placeCapo
(
guitar
,
capo
,
fret
);
A group of statements is called a block or statement block. A block of statements is enclosed in braces. Variables and classes declared in the block are called local variables and local classes, respectively. The scope of local variables and classes is the block in which they are declared.
In blocks, one statement is interpreted at a time in the order in which it was written or in the order of flow control. The following is an example of a block:
static
{
GigSimProperties
.
setFirstFestivalActive
(
true
);
System
.
out
.
println
(
"First festival has begun"
);
gigsimLogger
.
info
(
"Simulator started 1st festival"
);
}
if
, if
else
, and if else if
are decision-making control flow statements. They are used to execute statements conditionally. The expression for any of these statements must have type Boolean
or boolean
. Type Boolean
is subject to unboxing and autoconversion of Boolean
to boolean
.
The if
statement consists of an expression and a statement or a block of statements that are executed if the expression evaluates to true
:
Guitar
guitar
=
new
Guitar
();
guitar
.
addProblemItem
(
"Whammy bar"
);
if
(
guitar
.
isBroken
())
{
Luthier
luthier
=
new
Luthier
();
luthier
.
repairGuitar
(
guitar
);
}
When using else
with if
, the first block of statements is executed if the expression evaluates to true
; otherwise, the block of code in the else
is executed:
CoffeeShop
coffeeshop
=
new
CoffeeShop
();
if
(
coffeeshop
.
getPatronCount
()
>
5
)
{
System
.
out
.
println
(
"Play the event."
);
}
else
{
System
.
out
.
println
(
"Go home without pay."
);
}
if else if
is typically used when you need to choose among multiple blocks of code. When the criteria are not met to execute any of the blocks, the block of code in the final else
is executed:
ArrayList
<
Song
>
playList
=
new
ArrayList
<>();
Song
song1
=
new
Song
(
"Mister Sandman"
);
Song
song2
=
new
Song
(
"Amazing Grace"
);
playList
.
add
(
song1
);
playList
.
add
(
song2
);
...
int
numOfSongs
=
playList
.
size
();
if
(
numOfSongs
<=
24
)
{
System
.
out
.
println
(
"Do not book"
);
}
else
if
((
numOfSongs
>
24
)
&
(
numOfSongs
<
50
)){
System
.
out
.
println
(
"Book for one night"
);
}
else
if
((
numOfSongs
>=
50
))
{
System
.
out
.
println
(
"Book for two nights"
);
}
else
{
System
.
out
.
println
(
"Book for the week"
);
}
The switch
statement is a control flow statement that starts with an expression and transfers control to one of the case statements based on the value of the expression. A switch works with char
, byte
, short
, int
, as well as Character
, Byte
, Short
, and Integer
wrapper types; enumeration types; and the String
type. Support for String
objects was added in Java SE 7. The break
statement is used to exit out of a switch
statement. If a case statement does not contain a break
, the line of code after the completion of the case will be executed.
This continues until either a break
statement is reached or the end of the switch is reached. One default
label is permitted and is often listed last for readability:
String
style
;
String
guitarist
=
"Eric Clapton"
;
...
switch
(
guitarist
)
{
case
"Chet Atkins"
:
style
=
"Nashville sound"
;
break
;
case
"Thomas Emmanuel"
:
style
=
"Complex fingerstyle"
;
break
;
default
:
style
=
"Unknown"
;
break
;
}
The for
loop, enhanced for
loop, while
, and do-while
statements are iteration statements. They are used for iterating through pieces of code.
The for
statement contains three parts: initialization, expression, and update. As shown next, the variable (i.e., i
) in the statement must be initialized before being used. The expression (i.e., i<bArray.length
) is evaluated before iterating through the loop (i.e., i++
). The iteration takes place only if the expression is true
and the variable is updated after each iteration:
Banjo
[]
bArray
=
new
Banjo
[
2
];
bArray
[
0
]
=
new
Banjo
();
bArray
[
0
].
setManufacturer
(
"Windsor"
);
bArray
[
1
]
=
new
Banjo
();
bArray
[
1
].
setManufacturer
(
"Gibson"
);
for
(
int
i
=
0
;
i
<
bArray
.
length
;
i
++){
System
.
out
.
println
(
bArray
[
i
].
getManufacturer
());
}
The enhanced for
loop, a.k.a. the “for in” loop and “for each” loop, is used for iteration through an iterable object or array. The loop is executed once for each element of the array or collection and does not use a counter, because the number of iterations is already determined:
ElectricGuitar
eGuitar1
=
new
ElectricGuitar
();
eGuitar1
.
setName
(
"Blackie"
);
ElectricGuitar
eGuitar2
=
new
ElectricGuitar
();
eGuitar2
.
setName
(
"Lucille"
);
ArrayList
<
ElectricGuitar
>
eList
=
new
ArrayList
<>();
eList
.
add
(
eGuitar1
);
eList
.
add
(
eGuitar2
);
for
(
ElectricGuitar
e
:
eList
)
{
System
.
out
.
println
(
"Name:"
+
e
.
getName
());
}
In a while
statement, the expression is evaluated and the loop is executed only if the expression evaluates to true
. The expression can be of type boolean
or Boolean
:
int
bandMembers
=
5
;
while
(
bandMembers
>
3
)
{
CoffeeShop
c
=
new
CoffeeShop
();
c
.
performGig
(
bandMembers
);
// Randomly set zero to seven members
bandMembers
=
new
Random
().
nextInt
(
8
);
}
In a do while
statement, the loop is always executed at least once and will continue to be executed as long as the expression is true
. The expression can be of type boolean
or Boolean
:
int
bandMembers
=
1
;
do
{
CoffeeShop
c
=
new
CoffeeShop
();
c
.
performGig
(
bandMembers
);
Random
generator
=
new
Random
();
bandMembers
=
generator
.
nextInt
(
7
)
+
1
;
// 1-7
}
while
(
bandMembers
>
3
);
Transfer of control statements are used to change the flow of control in a program. These include the break
, continue
, and return
statements.
An unlabeled break
statement is used to exit the body of a switch
statement or to immediately exit the loop in which it is contained. Loop bodies include those for the for
loop, enhanced for
loop, while
, and do-while
iteration statements:
Song
song
=
new
Song
(
"Pink Panther"
);
Guitar
guitar
=
new
Guitar
();
int
measure
=
1
;
int
lastMeasure
=
10
;
while
(
measure
<=
lastMeasure
)
{
if
(
guitar
.
checkForBrokenStrings
())
{
break
;
}
song
.
playMeasure
(
measure
);
measure
++;
}
A labeled break
forces a break of the loop statement immediately following the label. Labels are typically used with for
and while
loops when there are nested loops and there is a need to identify which loop to break. To label a loop or a statement, place the label statement immediately before the loop or statement being labeled, as follows:
...
playMeasures:
while
(
isWithinOperatingHours
())
{
while
(
measure
<=
lastMeasure
)
{
if
(
guitar
.
checkForBrokenStrings
())
{
break
playMeasures
;
}
song
.
playMeasure
(
measure
);
measure
++;
}
}
// exits to here
When executed, the unlabeled continue
statement stops the execution of the current for
loop, enhanced for
loop, while
, or do-while
statements and starts the next iteration of the loop. The rules for testing loop conditions apply. A labeled continue
statement forces the next iteration of the loop statement immediately following the label:
for
(
int
i
=
0
;
i
<
25
;
i
++)
{
if
(
playList
.
get
(
i
).
isPlayed
())
{
continue
;
}
else
{
song
.
playAllMeasures
();
}
}
The return
statement is used to exit a method and return a value if the method specifies a return type:
private
int
numberOfFrets
=
18
;
// default
...
public
int
getNumberOfFrets
()
{
return
numberOfFrets
;
}
The return
statement will be optional when it is the last statement in a method and the method doesn’t return anything.
The Java keyword synchronized
can be used to limit access to sections of code (i.e., entire methods) to a single thread. It provides the capability to control access to resources shared by multiple threads. See Chapter 14 for more information.
Assertions are Boolean expressions used to check whether code behaves as expected while running in debug mode (i.e., using the -enableassertions
or -ea
switch with the Java interpreter). Assertions are written as follows:
assert
boolean_expression
;
Assertions help identify bugs more easily, including identifying unexpected values. They are designed to validate assumptions that should always be true
. While running in debug mode, if the assertion evaluates to false
, a java.lang.AssertionError
is thrown and the program exits; otherwise, nothing happens:
// 'strings' value should be 4, 5, 6, 7, 8 or 12
assert
(
strings
==
12
||
(
strings
>=
4
&&
strings
<=
8
));
Assertions need to be explicitly enabled. To find command-line arguments used to enable assertions, see Chapter 10.
Assertions may also be written to include an optional error code. Although called an error code, it is really just text or a value to be used for informational purposes only.
When an assertion that contains an error code evaluates to false
, the error code value is turned into a string and displayed to the user immediately prior to the program exiting:
assert
boolean_expression
:
errorcode
;
An example of an assertion using an error code is as follows:
// Show invalid 'stringed instruments' strings value
assert
(
strings
==
12
||
(
strings
>=
4
&&
strings
<=
8
))
:
"Invalid string count: "
+
strings
;
Exception handling statements are used to specify code to be executed during unusual circumstances. The keywords throw
and try/catch/finally
are used for exception handling. For more information on exception handling, see Chapter 7.