Java Reference
In-Depth Information
evaluates to false, then the statement associated with the if clause is
skipped.
Statement blocks
The simple form of the if construct consists of a single statement that exe-
cutesiftheconditionalexpressionistrue.TheBeepIfprogram,listedprevi-
ously, uses a simple if construct. But your code will often need to perform
more than one operation acording to the result of a decision. Java provides
a simple way of grouping several statements so that they are treated as a
unit. The grouping is performed by means of curly brace ({}) or roster sym-
bols. The statements enclosed within the two rosters form a compound
statement, also called a statement block .
You can use statement blocking to modify the BeepIf program so that
more than one statement executes when the test condition evaluates to
true. For example:
if(userInput == 1 || userInput == 2)
{
System.out.println("BEEP-BEEP");
System.out.println("The value entered is " + userInput);
}
The brace symbols ({ and }) are used to associate more than one state-
ment with the related if. In this example, both println() statements exe-
cute if the conditional clause evaluates to true and both are skipped if it
evaluates to false.
The nested if
Several if statements can be nested in a single construct. The result is that
theexecutionofastatementorstatementgroupisconditioned,nottoasin-
gle condition, but to two or more conditions. For example, we can modify
the if construct in the BeepIf program so that the code provides additional
processing for the case where the user input is the value 2, as follows:
if(userInput == 1 || userInput == 2)
{
System.out.println("BEEP-BEEP");
if(userInput == 2)
System.out.println("input was 2");
}
In the above code fragment, the if statement that tests for a value of 2
in the user input is nested inside the if statement that tests for a user in-
put of either 1 or 2. The inner if statement is never reached if the outer
one evaluates to false. If the user enters the value 3, the first test evalu-
Search WWH ::




Custom Search