Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^168) | Selection and Encapsulation
Statement1A
Statement 2
Statement1B
false true
if( Expression )
else
Figure 4.3 if-elseFlow of Control


The if-else Form


In Java, the ifstatement comes in two forms: the if-elseform and the ifform. Let’s look first
at if-else. Here is its syntax template:

The expression in parentheses must produce a booleanresult. At run time, the computer
evaluates the expression. If the value is true, the computer executes Statement1A. If the
value of the expression is false, it executes Statement1B. Statement1A is often called the then
clause; Statement1B is the else clause. Figure 4.3 illustrates the flow of control of the if-elsestate-
ment. In the figure, Statement2 is the next statement in the code after the entire ifstatement.
Notice that a Java ifstatement uses the reserved words ifand elsebut the thenclause
does not include the word then. The following code fragment shows how to write an ifstate-
ment. Observe the indentation of the thenclause and the elseclause, which makes the state-
ment easier to read. Also notice the placement of the statement following the ifstatement.

If-Statement (the if-else form)

if ( Expression )
Statement1A

Statement1B

else
Free download pdf