Java Reference
In-Depth Information
FIGURE 3.1
The syntax of an if statement
The if keyword
Parentheses (required)
if( boolean_expression ) {
//if block
Executes when boolean_expression is true.
} else {
The else statement and subsequent
else block is optional.
//else block
}
Executes when boolean_expression is false.
The following rules apply to an if-else statement:
The expression in parentheses must evaluate to a boolean . Otherwise, a compiler error
is generated.
If the boolean expression evaluates to true , the block of code following the if executes.
If the boolean expression evaluates to false , the else block executes.
The else block is optional.
The curly braces are not required in either the if or else block if the block of code is a
single statement. However, for readability it is a good idea to always use the curly braces.
An else block can contain an additional if statement.
The following simple example of an if statement demonstrates the syntax:
8. int x = (int) (Math.random() * 10 + 1);
9. if(x <= 5) {
10. System.out.println(“Under five”);
11. }
The value of x is assigned a random number between 1 and 10 . If the value of x is less
than or equal to 5 , then Under five displays on line 10. If x is greater than 5 , the block of
code that contains line 10 is skipped.
An else can be added to any if statement. The following if-then-else statement
outputs either
Under five or Over five :
8. int x = (int) (Math.random() * 10 + 1);
9. if(x <= 5) {
10. System.out.println(“Under five”);
11. } else {
12. System.out.println(“Over five”);
13. }
Search WWH ::




Custom Search