If Statements

Using If Statements
The if statement is one of the most important statements in any programming language, and Java is no exception. The following sections describe the ins and outs of using the various forms of Java’s powerful if statement.

Simple if statements
In its most basic form, an if statement lets you execute a single statement or a block of statements only if a boolean expression evaluates to true. The basic form of the if statement is this:

if (boolean-expression)
statement

Note that the boolean expression must be enclosed in parentheses. Also, if you use only a single statement, it must end with a semicolon. But 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 of a typical if statement:
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 10,000.

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 10000.0. Otherwise, neither statement is executed.

No comments: