|
|
Flow Control and Exception Handling - if...else Statement
Syntax
if( boolean expression ) {
statement1;
...
statementn;
}
if( boolean expression ) {
statement1;
....
statementn;
} else {
statementa;
...
statementz;
}
- the expression must be a boolean type
- curly braces are only required if there is more than one execution statement
- in the first form, the statements are only executed if the boolean expression evaluates to true
- in the second form, the first set of statements are executed if the boolean expression evaluates to true; otherwise, the statements following else are executed
- may be nested
if( x == y ) {
// do this
} else if( x > y ) { // nested 'if'
// do this
} else {
// do this
}
Example Code
Traps
- a non-boolean value used in the
if( )
- using the assignment operator '=' vs '=='
|