if-else
SYNTAX
if (
condition) {
true_statements ;
}
OR
if (
condition)
true_statement ;
OR
if (
condition) {
true_statements ;
} else {
false_statements ;
}
PROGRAM FLOW
- First, the boolean expression condition is evaluated.
- If condition evaluates to
true
, the
true_statement(s) are executed.
- If condition evaluates to
false
and
an else
clause exists, the false_statement(s)
are executed.
- Flow exits the if-else structure.
EXAMPLE
The following example tests to see if a user supplied function
f
comes within a tolerance
of zero
and prints an appropriate message.
if( Math.abs(f(x)) <= tolerance) {
System.out.println("Zero found at x="+x);
}
else {
System.out.println("Failed to find a zero");
}
COMMON ERRORS
Make sure that if you want to test equality in the condition
to use the boolean operator ==
and not the assignment
operator =
. Consider the following bad piece of code.
double x=0;
if(x=1) {
System.out.println("x is 0");
} else {
System.out.println("x is not 0. x is "+x);
}
The output will be
x is not 0. x is 1
since x is assigned to 1 in the condition.
David Maxwell,
who is still writing this, would like to
hear your comments and suggestions.