Java Reference
In-Depth Information
NOTE Noticehowthestatementonthesecondlineisindented.Thisistoshowthatitissubject
tothe if condition.Youshouldalwaysindentstatements inyourJavaprogramsascuestothe
program structure. You will learn more guidelines on the use of statement indenting as you
work with more complicated examples.
You may sometimes see a simple if written on a single line. The previous example could have been writ-
ten:
if(number%2 != 0) ++number; // If number is odd, make it even
This is perfectly legal. The compiler ignores excess spaces and newline characters. The semicolon acts as
the delimiter for a statement. Writing an if in this way saves a little space, and occasionally it can be an aid
to clarity, when you have a succession of such comparisons, for example, but generally it is better to write
the action statement on a separate line from the condition being tested.
Statement Blocks
In general, wherever you can have one executable statement in Java, you can also have a block of statements
enclosed between braces, {} . This applies to the statements within a statement block, so you can always
nest a statement block between braces inside another statement block, and you can do this to any depth. The
ability to use a block wherever you can have a statement means that you can use a statement block within
the basic if statement that you just saw. Therefore, the if statement can equally well be of the following
form:
if(expression) {
statement 1;
statement 2;
...
statement n;
}
Now if the value of expression is true , all the statements enclosed in the following block are executed;
if expression is false , the statements in the block are not executed. Of course, without the braces to en-
close the block, the code no longer has a statement block:
if(expression)
statement 1;
statement 2;
...
statement n;
Here, only the first statement, statement 1 , is omitted when the if expression is false ; the remaining
statements are always 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
Search WWH ::




Custom Search