< Java 天地·Core Java·Lecture Notes·Unit 3 - Core Java Programming Concepts - Content 23 -- 追寻梦想>编程乐园
您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)


Content Index

Content Page # 23

Selection in Java

A selection can result in a statement being executed once or not at all. What determines whether the statement will be executed or not is the result of a test If the result of the test is true then the statement will be executed, if the result is false it will not be executed.

There are three forms of selection statement implemented in Java:

  • if
  • if...else
  • switch...case

In this module we shall concentrate on the first two of these selection statements. They are all technically equivalent; the choice as to which form of selection statement to implement in a program is made by each programmer on the grounds of style or convenience.

In this unit we shall examine just the first (simpler) if selection statement. In the next unit we will examine the extended if...else selection statement and an iteration statement

Selection: `if'

Using pseudocode code we can illustrate how an if statement works. Consider the following pseudocode for a system to operate fire alarms in an office building:

if ( temperature too high )

sound the alarm

This illustrates the general form of an if statement, i.e.:

if <test>

action to perform if test is true

To implement our fire alarm pseudocode as a valid Java statement we could write the following:

if (temperature > 78)

soundAlarm();

(of course we are assuming the class has a variable called temperature and a method soundAlarm())

The way an if statement can cause deviation from the default sequential flow of execution can be illustrated as follows. Consider this pseudocode design:

statementA;

if( age > 60 )

statementB;

statementC;

If the variable age has a value over 60, say 65, then the test ( age > 60 ) will be true, and the therefore statementB will be executed. So the statements to be executed will be:

statementA

statementB

statementC

However, if the variable age has a value of 60 or less, say 21, then the test ( age > 60 ) will be false, and statementB will not be executed. So the statements executed will be:

statementA

statementC

Thus the result of a selection statement means that some statements may not be executed, or may be executed once.

.Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg