Conditional Statements


Two Alternatives: If/Else Statements

Sometimes you have a situation where one of two actions should be taken, depending on whether a condition is true or not. Your code should either do one action or the other.

For example, a timestamp should show "AM" or "PM", depending on the time. (Assuming it is not showing the time in 24-hour time.)

    int hour = aClock.getHour();     // getHour returns 0 - 24
    System.out.print(aClock.getHH() + ":" + aClock.getMM());
    if ( hour < 13 )
    {
        System.out.println(" AM");
    }
    else
    {
        System.out.println(" PM");
    }
    // Follow-up code goes here.
Syntax:
if ( <boolean-expression> )
{
    <the statement(s) for the first alternative>
}
else            // No boolean expression goes here!
{
    <the statement(s) for the second alternative>
}

Alyce Brady, Kalamazoo College