The if-else Statement
In this lesson, we will use the if-else statement to choose between two courses of action.
We'll cover the following...
What is an if-else
statement?
So far, we have used the if
statement to do something if a certain condition is true, but to not do it if the condition is false. Frequently, however, you want to do one thing if a certain condition is true and another thing if it is not, as the figure given below illustrates.
In these situations, an if
statement can have an else
clause that indicates what to do when the condition is false. This kind of if
statement is
sometimes called an if-else
statement. It has the following form:
📝 Syntax: The if-else statement
if ( condition ) statement1 else statement2 }
Effect: statement1 executes only if condition is true; statement2 executes only if condition is false.
Example 1
A portion of a bank’s program that maintains our checking account could use BigDecimal
objects to represent monetary values, as we saw in an earlier chapter. Suppose that balance
and checkAmount
...