Java Reference
In-Depth Information
Here is the syntax for a two-way if-else statement:
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
The flowchart of the statement is shown in Figure 3.3.
true
false
boolean-
expression
Statement(s) for the true case
Statement(s) for the false case
F IGURE 3.3 An if-else statement executes statements for the true case if the Boolean-
expression evaluates to true ; otherwise, statements for the false case are executed.
If the boolean-expression evaluates to true , the statement(s) for the true case are exe-
cuted; otherwise, the statement(s) for the false case are executed. For example, consider the
following code:
two-way if-else statement
if (radius >= 0 ) {
area = radius * radius * PI;
System.out.println( "The area for the circle of radius " +
radius + " is " + area);
}
else {
System.out.println( "Negative input" );
}
If radius >= 0 is true , area is computed and displayed; if it is false , the message
"Negative input" is displayed.
As usual, the braces can be omitted if there is only one statement within them. The braces
enclosing the System.out.println("Negative input") statement can therefore be
omitted in the preceding example.
Here is another example of using the if-else statement. The example checks whether a
number is even or odd, as follows:
if (number % 2 == 0 )
System.out.println(number + " is even." );
else
System.out.println(number + " is odd." );
 
 
Search WWH ::




Custom Search