the end. The semicolon terminates the statement.[1] In fact, a semicolon by itself is a statement that does
nothingthe empty statement. Not all expressions can become statements, since it would be almost always
meaningless to have, for example, an expression such as x<=y stand alone as a statement. Only the following
types of expressions can be made into statements by adding a terminating semicolon:
[1] There is a distinction between terminator and separator. The comma between identifiers in
declarations is a separator because it comes between elements in the list. The semicolon is a
terminator because it ends each statement. If the semicolon were a statement separator, the
last semicolon in a code block would be unnecessary and (depending on the choice of the
language designer) possibly invalid.
- Assignment expressionsthose that contain = or one of the op= operators
- Prefix or postfix forms of ++ and --
- Method calls (whether or not they return a value)
- Object creation expressionsthose that use new to create an object
Declaration statements (formally called local variable declaration statements) declare a variable and initialize
it to a value, as discussed in Section 7.3.1 on page 170. They can appear anywhere inside a block, not just at
the beginning. Local variables exist only as long as the block containing their declaration is executing. Local
variables must be initialized before use, either by initialization when declared or by assignment. If any local
variable is used before it is initialized, the code will not compile.
Local class declaration statements declare a local inner class that can be used within the block in which it was
declared. Local classes were discussed in detail on page 142.
In addition to the expression statements listed, several other kinds of statements, such as if and for
statements, affect flow of control through the program. This chapter covers each type of statement in detail.
Curly braces, { and }, group zero or more statements into a block. A block can be used where any single
statement is allowed because a block is a statement, albeit a compound one.
10.2. ifelse
The most basic form of conditional control flow is the if statement, which chooses whether to execute
statements that follow it. Its syntax is:
if (expression)
statement1
else
statement2
First, the expressionwhich must be of type boolean or Booleanis evaluated. If its value is TRue, then
statement1 is executed; otherwise, if there is an else clause, statement2 is executed. The else
clause is optional.
You can build a series of tests by joining another if to the else clause of a previous if. Here is a method
that maps a stringexpected to be one of a particular set of wordsinto an action to be performed with a value:
public void setProperty(String keyword, double value)
throws UnknownProperty
{
if (keyword.equals("charm"))