Java Reference
In-Depth Information
2.2 Conditional structures: Simple and multiple
choices
2.2.1 Branching conditions: if ... else ...
Programs are not always as simple as plain sequences of instructions that are
executed step by step, one at a time on the processor. In other words, programs
are not usually mere monolithic blocks of instructions, but rather compact
structured sets of instruction blocks whose executions are decided on the fly.
This gives a program a rich set of different instruction workflows depending on
initial conditions.
Programmers often need to check the status of a computed intermediate
result to branch the program to such or such another block of instructions
to pursue the computation. The elementary branching condition structure in
many imperative languages, including Java, is the following if else instruction
statement:
if (booleanExpression)
{BlockA}
else
{BlockB}
The boolean expression booleanExpression in the if structure is first
evaluated to either true or false . If the outcome is true then BlockA is
executed, otherwise it is BlockB that is selected (boolean expression evaluated
to false ). Blocks of instructions are delimited using braces
. Although the
curly brackets are optional if there is only a single instruction, we recommend
you set them in order to improve code readibility. Thus, using a simple if
else statement, we observe that the same program can have different execution
paths depending on its initial conditions. For example, consider the following
code that takes two given dates to compare their order. We use the branching
condition to display the appropriate console message as follows:
{
...
}
int h1 =... , m1 =... , s1 =...; // initial conditions
int h2 =... , m2 =... , s2 =...; // initial conditions
int hs1 = 3600 h1 + 60 m1 + s 1 ;
int hs2 = 3600 h2 + 60 m2 + s 2 ;
int d=hs2 hs1 ;
if (d > 0) System . out . println ( "larger" );
else
System . out . println ( "smaller or identical" );
Note that there is no then keyword in the syntax of Java. Furthermore, the
else part in the conditional statement is optional:
 
Search WWH ::




Custom Search