if Statement
In its most basic form, an if statement executes a single statement or a block of statements if a boolean expression evaluates to true. Here’s the syntax:
if (boolean-expression)
statement
The boolean expression must be enclosed in parentheses. If you use only a single statement, it must end with a semicolon. However, the statement can also be a statement block enclosed by braces. In that case, each statement within the block needs a semicolon, but the block itself doesn’t.
Here’s an example:
double commissionRate = 0.0;
if (salesTotal > 10000.0)
commissionRate = 0.05;
In this example, a variable named commissionRate is initialized to 0.0 and then set to 0.05 if salesTotal is greater than 10000.0.
Here’s an example that uses a block rather than a single statement:
double commissionRate = 0.0;
if (salesTotal > 10000.0)
{
commissionRate = 0.05;
commission = salesTotal * commissionRate;
}
In this example, the two statements within the braces are executed if salesTotal is greater than $10,000. Otherwise, neither statement is executed.
An if statement can include an else clause that executes a statement or block if the boolean expression is not true. Its basic format is
if (boolean-expression)
statement
else
statement
Here’s an example:
double commissionRate;
if (salesTotal <= 10000.0)
commissionRate = 0.02;
else
commissionRate = 0.05;
In this example, the commission rate is set to 2% if the sales total is less than or equal to $10,000. If the sales total is greater ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access