Java Reference
In-Depth Information
sequence of statements belongs to the
if
, but only the first statement does because there are no braces. The
indenting is incorrect and misleading here and the code should be written as:
if(expression)
statement 1;
statement 2;
...
statement n;
NOTE
In this topic, I have adopted the convention of having the opening brace on the same
line as the
if
condition. The closing brace is then aligned with the first character,
i
,
in the
keyword
if
.
I indent all the statements within the block from the braces so that they are easily
identified as belonging to the block. This is consistent with the pattern I have been using with
a block defining a class and a block belonging to a method. There are other conventions that
youcanuseifyouprefer.Inanothercommonconvention, thebracesboundingablockappear
on their own line and are aligned. The most important consideration is that you are consistent
in whatever convention you adopt.
As a practical example of an
if
statement that includes a statement block, you could write the following:
if(number%2 != 0) { // Test if number is odd
// If so make it even and output a message
++number;
System.out.println("Number was forced to be even and is now " + number);
}
Now both statements between the braces are executed if the
if
expression is
true
, and neither of them is
executed if the
if
expression is
false
.
NOTE
It is good practice to always put opening and closing braces around the code depend-
ent on an
if
condition, even when there is only a single action statement. This helps to make
the code easier to follow and minimizes the possibility of the program logic being confused.
Statement blocks are more than just a convenient way of grouping statements together — they affect the
life and accessibility of variables. You will learn more about statement blocks when I discuss variable scope
later in this chapter. In the meantime, let's look a little deeper into what you can do with the
if
statement.
The else Clause
You can extend the basic
if
statement by adding an
else
clause. This provides an alternative choice of
statement, or statement block, that is executed when the
expression
in the
if
statement is
false
. You can
see the syntax of this statement, and how the program's control flow works, in
Figure 3-2
.