Perhaps the single most powerful tool in programming is the if-then-else
conditional test statement. It allows the flow of the program to
proceed in different ways according to a test that results in boolean
true or false value.
In Java the "then" is implied. The conditional
test follows the C/C++ form with:
if(
boolean expression )
statement 1;
else
statement 2;
where boolean expression encompasses any expression that
returns a boolean value and statement 1 and statement
2 indicate single line statements.
Often the if-else
will use code blocks of multiple statements enclosed in parentheses:
if(
boolean expression )
{
statement 1;
statement 1a;
}
else
{
statement 2;
statement 2a;
}
The else
clause can be dropped if no alternate operation needed :
if(
boolean expression ) statement;
Possible boolean expressions include the following:
- A boolean
variable:
public void test( boolean b)
{
...
if ( b ) y = 5;
...
}
- A comparison
public void test( int x )
{
...
if ( x > 5 ) x = 5;
...
}
- A boolean
operation
public void test( boolean b1, boolean b2)
{
...
if ( b1 || b2 ) x = 5;
...
}
- An assignment to a boolean
public void test( boolean b)
{
...
boolean b1;
if ( b1 = b ) x = 5;
...
}
Several if-else sequential tests can be done in one compound
statement:
if(
boolean expression 1)
{
statement 1;
statement 1a;
} else if( boolean expression 2)
{
statement 2;
statement 2a;
}else if( boolean expression 3)
statement 3;
else
{
statement 4;
}
Note that statement 4 is executed if the other boolean expressions
all return false.
Latest update: Dec.11.2003
|