Java Reference
In-Depth Information
1.5.3 the if statement
The if statement is the fundamental decision maker. Its basic form is
The if statement is
the fundamental
decision maker.
if( expression )
statement
next statement
If expression evaluates to true , then statement is executed; otherwise, it is
not. When the if statement is completed (without an unhandled error), control
passes to the next statement.
Optionally, we can use an if-else statement, as follows:
if( expression )
statement1
else
statement2
next statement
In this case, if expression evaluates to true , then statement1 is executed; oth-
erwise, statement2 is executed. In either case, control then passes to the next
statement, as in
System.out.print( "1/x is " );
if( x != 0 )
System.out.print( 1 / x );
else
System.out.print( "Undefined" );
System.out.println( );
Remember that each of the if and else clauses contains at most one
statement, no matter how you indent. Here are two mistakes:
if( x == 0 ); // ; is null statement (and counts)
System.out.println( "x is zero " );
else
System.out.print( "x is " );
System.out.println( x ); // Two statements
The first mistake is the inclusion of the ; at the end of the first if . This
semicolon by itself counts as the null statement ; consequently, this frag-
ment won't compile (the else is no longer associated with an if ). Once
that mistake is fixed, we have a logic error: that is, the last line is not part
of the else , even though the indentation suggests it is. To fix this problem,
we have to use a block , in which we enclose a sequence of statements by
a pair of braces:
A semicolon by
itself is the null
statement.
A block is a
sequence of state-
ments within
braces.
 
Search WWH ::




Custom Search