Java Reference
In-Depth Information
single statement. In the if-statement shown above, the then-part consists of this
block:
{
x= x + 2;
y= y + 2;
}
Notice the indentation: statements inside a block are indented. The opening
brace is put on the same line as the condition. The closing brace appears on its
own line, indented the same amount as the if . (A method body is a block, so it
follows these conventions.)
We (and Sun Microsystems) strongly advocate using a block for the then-
part even if there is only a single statement within the braces, as in this example:
if (x < y) {
x= x + 2;
}
Why? Because often, after writing some Java code, we have to change it. Here
is an example of a fairly common occurrence, even among professional pro-
grammers. We have written this statement, without braces:
if (x < y)
x= x + 2;
and we want to change it so that the then-part adds 2 to y as well as to x . We are
quite likely to simply append the new assignment, yielding:
if (x < y)
x= x + 2;
y= y + 2;
But this is not correct because the braces are missing, and it is actually equiva-
lent to:
if (x < y)
x= x + 2;
y= y + 2;
Thus, if we don't make the then-part a block right from the beginning, we are
liable to make a mistake if we have to change the then-part later on.
Hereafter, we always include the braces.
The if-else statement
At times, we want to execute one thing if a condition is true and another if
it is false . For this we use an if-else statement. Here is an example:
 
Search WWH ::




Custom Search