Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

CHAPTER 4: PROGRAMMING CONSTRUCTS OF JAVA

CHAPTER 4: Programming Constructs of Java

• Basic programming constructs


• Sequence
• Selection
• Iteration
• Switch statement
• Break and Continue statements

At the end of this chapter a student becomes familiar with the overall features of Java that will enable one
to write simple application programs. The requirements of structured programming are met at the end of
this chapter.

4-1
CHAPTER 4: PROGRAMMING CONSTRUCTS OF JAVA

4.0 Introduction

In the last chapter we studied about the different data types available in Java. We have also seen that the

variables can hold values of the data type specified and we can change the values of the variables during

the course of execution of the program.

The variables and key words when combined in a proper manner we get instructions. The instructions can

be grouped into block of statements.

The most important feature of procedural languages is that they provide a way for structured programming.

In structured programming, there are three basic constructs namely sequence, selection and iteration. The

focus of this chapter is to provide a clear idea about these three constructs.

4.1 Sequence

Sequence is one or more statements executed in the order in which they appear. Normally any program

will be executed statement by statement in the order they appear. This is called sequence.

For example if we have statements s1, s2, s3 appearing one by one then s1 will be executed first,

s2 next and s3 last.

S1

S2

S3

4-2
CHAPTER 4: PROGRAMMING CONSTRUCTS OF JAVA

4.2 Selection

Sometimes we may need to deviate from the normal sequence of execution of the program. In such a case

we have to use the transfer of control statements. The selection statement is used to select only one block of

statement out of two or more blocks available. This is achieved through the IF statement in Java. There are

various forms of IF constructs available. Let us see one by one in this section:

4.2.1 The basic IF construct

The syntax of the basic IF construct is given below:

If (condition)
{
statement1
statement2
….
}

In this case the block of statements will be executed if the condition is true otherwise the entire block will

be skipped altogether. If the block contains only one statement then the braces “{ }” can be omitted.

True
?

False

B Block

4-3
CHAPTER 4: PROGRAMMING CONSTRUCTS OF JAVA

4.2.2 The IF … ELSE construct

The syntax of the if … else construct is given below:

if (condition)
{
block 1
}
else
{
block2
}

In this type of if statement any one of the two blocks will be executed at any instant. If the condition is true

block 1 will be executed otherwise block 2 will be executed. Both block 1 and block 2 will not be executed

at any instant.

True False

Block 1 Block 2

4-4
CHAPTER 4: PROGRAMMING CONSTRUCTS OF JAVA

4.2.3 The if… else if … else Construct

The syntax of the if… else if … else construct is shown below.

If (condition 1)
{
block 1

}
else if (condition 2)
{
block 2
}
else
{
block 3
}

In this type of constructs block 1 will be executed if condition 1 is true , block 2 will be executed if

condition 2 is true otherwise block 3 will be executed. In this case also only one block will be executed at

any instant of time.

True False
C1
111

Block 1 True False


C2

Block 2 Block 3

4-5
CHAPTER 4: PROGRAMMING CONSTRUCTS OF JAVA

4.2.4 The conditional Operator

The conditional operator is otherwise known as the ternary operator and is considered to be an alternative

to the if… else construct. It returns a value and its syntax is given below:

<test> ? <pass> : <fail>

where <test > is the condition to be tested. If the condition returns true then the statement given in <pass>

will be executed. Otherwise, the statement given in <fail> will be executed.

Sample Program:

class IfTest {
public static void main(String args[ ]) {
int month = 4;
String season;
if (month = = 12 || month = = 1 || month = = 2) {
season = ”Winter”;
}
else if (month = = 3 || month = = 4 || month = = 5) {
season = ”Spring”;
}
else if (month = = 6 || month = = 7 || month = = 8) {
season = ”Summer”;
}
else if (month = = 9 || month = = 10 || month = = 11) {
season = ”Autum”;
}
else {
season = “Invalid Month”;
}
System.out.println(“ April is in “ + season + “.”);
}
}

Sample Program:

class Ternary {
public static void main(String args[ ]) {
int i = 10;
int j = 78;
int k;
k = i < j ? i : j:
System.out.println(“The value assigned is “ + k);
}

4-6
CHAPTER 4: PROGRAMMING CONSTRUCTS OF JAVA

4.3 The Iterative Constructs


There are occasions when we require to repeat the given block of statements over and over again for a

given number of times. This is achieved through the iterative statements. There are three types of iterative

constructs – the While … loop, the for loop and the do … while loop – available in Java. All these

iterative constructs repeat the block until a condition is satisfied.

4.3.1 The while … loop

The while loop executes a set of codes repeatedly until the condition returns false. The syntax for the while

loop is given below:

While (<condition>) {

< body of the loop >

where the < conditon > is the condition to be tested. If the condition returns true then the statement inside

the < body of the loop > are executed. Else the loop is terminated.

Block

4-7
CHAPTER 4: PROGRAMMING CONSTRUCTS OF JAVA

Sample Program:

class WhileDemo {
public static void main(String args[ ]) {
int max = 25;
int prev = 0;
int next = 1;
int sum;
while (next <= max)
{
System.out.println(“The Fibonacci series is “ + next);
sum = prev + next;
prev = next;
next = sum;
}
}
}

4.3.2 The do… while loop

The do … while loop is similar to the while … loop except that the condition to be evaluated is given at the

end. Hence the loop is executed at least once even when the condition is false. The syntax of the do …

while loop is given below:

do {

< body of the loop >

} while (< condition >);

Block

4-8
CHAPTER 4: PROGRAMMING CONSTRUCTS OF JAVA

4.3.3 The for loop

The for loop repeats a block of statements a certain number of times until a condition is matched. It is

commonly used for simple iteration. The syntax of the for loop is given below.

for (initialization; test; expression) {

block of statements;

In the first part a variable is initialized to a value. The second part consists of a test condition that returns

only a Boolean. The last part is an expression, evaluated every time the loop is executed. The following

example depicts the usage of for loop.

class ForDemo {
public static void main(String args [ ]) {
int i;
for (i = 0; i < 10; i = i + 2)
{
if ((i % 2) = = 0)
System.out.println(“ The number “ + i + “ is an even number”);
}
}
}

4.4 The switch statement

The switch statement dispatches the control to the different parts of the code based on the value of a single

variable or expression. The value of expression is compared with each of the literal values in the case

statements. If they match, the following code sequence is executed. Otherwise an optional default statement

is executed. The general syntax of the switch statement is as follows:

switch (< test > ) {


case < valueOne >:
< resultOne >;
break;
case < valueTwo >:
< resultTwo >;
break;
default :
< defaultResult >;

4-9
CHAPTER 4: PROGRAMMING CONSTRUCTS OF JAVA

Sample Program:

class SwitchDemo {
public static void main(String args[ ]) {
int v = 4;
switch (v) {
case 1:
case 2:
case 3:
System.out.println(“Spring is around the corner”);
break;
case 4:
case 5:
case 6:
System.out.println(“Summer is scorching its way through ”);
break;
case 7:
case 8:
case 9:
System.out.println(“Autumn leaves are abundant”);
break;
case 10:
case 11:
case 12:
System.out.println(“Winter is freezing ”);
break;
}
}
}

4.5 Break and Continue


The break keyword halts the execution of the current loop and forces control out of the loop. The term

break refers to the act of breaking out of a block of code. It tells the runtime to pick up the execution past

the end of the named block. In order to refer to a block by name, Java has a label construct that assigns a

name to every block.

The continue keyword is similar to the break, except that instead of halting the execution of the loop, it

starts the next iteration.

4 - 10

You might also like