Java Reference
In-Depth Information
Here, only the first statement, statement 1 , will be omitted when the if expression is false ; the
remaining statements will always be executed regardless of the value of expression . You can see
from this that indenting is just a visual cue to the logic. It has no effect on how the program code
executes. This looks as though the sequence of statements belongs to the if , but only the first one does
because there are no braces. The indenting is incorrect here.
In this topic, we will adopt the convention of having the opening brace on the same
line as the statement. The closing brace will then be aligned with the statement. We
will indent all the statements within the block from the braces so that they are easily
identified as belonging to the block. There are other conventions that you can use if
you prefer, the most important consideration being that you are consistent.
As a practical example of an if statement that includes a statement block, we could write:
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 .
It is a good practice to always have opening and closing braces even when there is only a single
action statement, this helps clarify the code and will stop confusion of its logic.
Statement blocks are more than just a convenient way of grouping statements together - they affect the life
and accessibility of variables. We will learn more about statement blocks when we discuss variable scope later
in this chapter. In the meantime let's look a little deeper into what we can do with the if statement.
The else Clause
We can extend the basic if statement
by adding an else clause. This
provides a second 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 clause, and how the
program's control flow works, in this
diagram:
yes
no
expression is
true?
i f (expression) {
statement:
)else {
statement2:
execute
statement1
execute
statement2
)
next_statement
execute
next_statement
Search WWH ::




Custom Search