Create Software Components 

Using Java Level 2

 

 

Course Info

Scheme

Resources

Tutorials

Java Demos

Utilities

Links


 

   Lecture 6

Program Flow Control 

 

How do you exercise control over which statements are executed in your code and which statements are skipped, depending upon certain conditions?  There are various methods for controlling program flow.

Controlling Program Flow

Relational & Equality Operators

Logical Operations on Booleans

Program Flow - Selection

Program Flow - Iteration


Controlling Program Flow

So far, all the code examples used so far have involved each line of code being executed sequentially, one line after another.   

This sort of sequential line execution can be limiting.  What happens if we want a certain line to be executed only if a particular condition is met?   Or what happens if we want a line to execute repeatedly a certain number of times?  

For finer control over the sequence in which lines are executed in our code we need to use selection and iteration statements.

However before looking at these control statements you need to understand equality, relational and Boolean operators. 


Relational & Equality Operators

Relational and equality operators allow us to compare the relationship between two quantities.  The result of evaluation will be a true or a false.  For example, 3 < 5 is like asking "3 is less than five; true or false?", which results in an answer of true since 3 is certainly less than 5.

The table below shows more of these operators.  The first two are equality operators, the rest are relational operators.

Operator

Name

 Example/Description

  ==     

equal to 

x == y  // if x is equal to y the expression evaluates to true, otherwise returns false

!= 

 not equal to 

x != y   // if x is not equal to y the expression evaluates to true otherwise, returns false

< 

less than   

x < y  // if x is smaller than y the expression evaluates to true, otherwise returns false

  <=    

less than or equal to

x <= y  // if x is smaller or equal to y the expression evaluates to true, otherwise returns false

  >  

greater than

x > y  // if x is greater than y the expression evaluates to true, otherwise returns false

>=

greater than or equal to  

  x >= y  // if x is greater than y the expression evaluates to true, otherwise returns false

Here are a few examples;-

10 < -5;  returns a false

11.5 >= 2;  returns a true

int i = 10, j = 3;

i == j  returns a false

i != j  returns a true

i <= (j + 7)  returns a true

         

~Now try the activity~

Activity 6A

State if the following expressions return a true or false.

int i = 2, j = 1;

  1. 20 < -5

  2. 20 <= (-5 + 25)

  3.  i > j++

  4.  i > ++j

Why not check your answers by using code.

 


Logical Operations on Booleans

Java contains the Logical operators AND (&&), OR ( || ) and NOT ( ! ).  These operators are used with expressions that evaluate to a Boolean true or false.  Let's look at some examples:-

Example of && (AND)

You can imagine the AND operator && to mean..

(this expression) AND (this expression) must both evaluate to true

As an example:-

(4 < 2) // evaluates to false

(1 < 2) // evaluates to true

So, the following expression means -  if both sides of the && evaluate to true then return a true, else return a false.

(4 < 2) && (1 < 2) 

So let's rewrite the expression as:-

false && true  

So the whole expression evaluates to false

Example of || (OR)

You can imagine the OR operator ||  to mean..

(this expression) OR (this expression) must evaluate to true

As an example:-

(4 < 2) // evaluates to false

(1 < 2) // evaluates to true

So, the following expression means -  if one or both sides of the || evaluate to true then return a true.  If both sides evaluate to false then return a false.

(4 < 2) || (1 < 2) 

So let's rewrite the expression as:-

false || true  

So the whole expression evaluates to true

Example of ! (NOT)

You can imagine the NOT operator !  to reverse the Boolean result it is operating on:-

NOT(true)  evaluates to false

NOT(false)  evaluates to true

As an example:-

(4 < 2) // evaluates to false

(1 < 2) // evaluates to true

So, the following expressions mean -  return a false if expression is true and vice-versa.

!(4 < 2) evaluates to !false which is reversed to a true

!(1 < 2) evaluates to !true which is reversed to false

 

The table below shows all of the logical and Boolean operators.

 

Operator

Name

 Example/Description

&&  

Logical AND  

Produces a true if both operands are true

||

Logical OR  

Produces a true if one or both of the operands is true

!

Logical NOT

Reverses a false to a true and vice-versa

&

AND

Produces a true if both operands are true

|

OR

Produces a true if one or both of the operands is true

^

XOR

Produces a true only if one of the operands is true

 

There are two ways to represent the AND operator; & or &&.  There is a slight difference between them.  Consider the following:-

(salary < 10,000) & (age < 60)

or

(salary < 10,000) && (age < 60)

In the first case, where the single ampersand is used the Boolean expression is evaluated in the following way:-

  1. evaluate (salary < 10,000) first

  2. now evaluate (age < 60)

  3. check if both sides of the & evaluate to true

In the second case, where the double ampersand is used the Boolean expression is evaluated in the following way:-

  1. evaluate (salary < 10,000) first

  2. only bother to evaluate (age < 60) if step 1 gave a result of true;  (it doesn't matter what the second expression evaluates to if the first gives a false.)

The double ampersand operator carries out a shorthand process, since it only evaluates the first expression if that expression returns a false.  Knowing the difference between these operators can be useful on occasion.

There are also two ways to represent the OR operator; | or ||.  There is also a slight difference between these two operators.  Consider the following:-

(salary < 10,000) | (age < 60)

or

(salary < 10,000) || (age < 60)

In the first case, where the single vertical line | is used each expressions is evaluated regardless of whether an individual expression returns a true or false.  Only then is the whole thing checked to see if one of the expressions returned a true.

In the second case where the double vertical line || is used, each expression is evaluated int turn unless one of them returns a true .  Then it stops evaluating any other expression - why bother to carry on evaluating expressions if one of them returns a true since the whole thing will then evaluate to true regardless of the other expressions.

 

~Now try the activity~

Activity 6B

Given the following declaration, evaluate the Boolean expressions and state if the result is a true or a false.

int a = 2, b = 6;

  1. (a < b) && (a <=2)

  2. (a != b) || (b == 6)

  3. !(a > b) && ( ( b > = 6) || ( b == a) ) 

  4. Examine the code below.  What do you think the output will be?  Now type in, compile and run the code.  What happens?

  5. Make one correction to the code so that the program will run.

public class TestAndOperator  {

     public static void main (String args[] ) {

        int a = 0;

        if ( a != 0 & 10/a > 1 ) {

            System.out.println ( "evaluated to true");

       }

       else {

            System.out.println ( "evaluated to false");

       }

    }

}

You can check your answers.

 


Program Flow - Selection Statements

Selection statements allow us to choose between alternative actions within a program.  Java has two distinct selection statements.  The if statement and the switch statement.  We shall examine the simplest form of selection - the if statement. 

If and if-else statement

The syntax of the if statement is:-

if (condition) {

  statement;

}

where condition is any expression that evaluates to a true or false.  If condition evaluates to a true then statement is executed otherwise statement will be bypassed.  Here is an example:-

int age = 20;

if (age >= 18) {
    System.out.println("You are an adult");
}

Since the expression age >= 18 evaluates to true, "You are an adult" is displayed.

Another selection statement id the if-else statement.  The syntax is:-

if (condition) {

  statement;

}

else {

  statement;

}

where again, condition is any expression that evaluates to a true or false.  If condition evaluates to a true then statement is executed otherwise statement will be bypassed.  However, the statement in the else block will be executed instead.   Here is an example:-

if (age >= 18) {
    System.out.println("You are an adult");
}
else {
    System.out.println("You are a minor");
}

If age is set to value of 10, what will be printed out?

Here is another example:-

int i  = 10, j = 4;

if (i < j) {

    System.out.println("i is smaller than j");

}

Since  i< j evaluates to false, the statement inside the if block is not executed.  However, given...

if (!(i < j)) {

    System.out.println("i is smaller than j");

}

The statement inside the if block is executed.  This is because  i< j evaluates to false but the not operator ! reverses this to a true.  

Here is another example:-

if ( (condition1) && (condition2) ) { do something }  e.g.

if ((3 < 4) && (6 > 2)) {

    do something..

    do some more;

}


This statement means if condition 1 AND condition 2 are true then execute the statements inside the if block.  Since (3 < 4) evaluates to true but (6 > 2) evaluates to false then the result of (3 < 4) && (6 > 2) is false.  The statements do not get executed.

Here is another example:-

if ( (condition1) || (condition2) )  { do something } e.g. 

if ((3 < 4) || (6 > 2)) {

    do something..

    do some more;

}


This statement is very similar to the one above except that the || means OR.  So the statement translates to if condition1 OR condition2 are met then execute the statements inside the if block. Since (3 < 4) evaluates to true but (6 > 2) evaluates to false then the result of (3 < 4) || (6 > 2) is true.  The statements do get executed.   

Yet another example:-

int num = 6;

if (num == (10 - 4)) {

    do something..

    do some more;

}

This condition in this case uses the equality operator ==.  Since (10 - 4) is 6 and num is certainly equal to 6 then the expression num == (10 - 4) evaluates to true.

#Warning#  Don't make the mistake of using  the assignment operator = to test for equality.  E.g. 

if (num = (10 - 4)) {

would create a compiler error.

One last example:-

String  str  =  "cat";

if (str.equals ("dog") ) {

    do something..

    do some more;

}

The .equals(String) method is used for testing if 2 strings are equal.  In this case I am testing if the atring that str refers to (i.e. "cat") is the same as the string "dog".  Of course "cat" and "dog" are not the same so this evaluates to false and the statement inside the if block do not get executed.

 

~Now try the activity~

 

Activity 6C

  1. Write a program that reads in a numbers between 1 and 10 and displays the phrase "number is a prime" or "number is not a prime" as appropriate. Prime numbers between 1 and 10 are 1, 2, 3, 5 and 7. 

You can use the line

num = System.in.read() - 48;

to get a number input 

You must also include this line.

public static void main (String[] args) throws java.io.IOException {

You can check out my code after you have written your own.

 

 


Program Flow - Iteration Statements

Java has three distinct iteration statements.  The for, while and do-while iterations.  Iteration means something is repeated in a cyclic manner.  In programming this refers to a cycle where a block of code is repeatedly executed.

For Loop

This loop is used if you know exactly how many times you want a block of code to be repeatedly executed. The syntax is:-

for(loop counter; break condition; increment statement)  {

        statement(s);

        }

As an example, to print out the 2 times table we need to loop 10 times. Look at the Two TimesTable code below.  Compile and run this code.  You should see ten lines of output displaying the two times table.


public class TwoTimesTable {

    public static void main(String [] args) {

        for (int i = 1; i<11; i++)  {

        System.out.println(i + " times 2 is " + (i*2));

        }
    }
}

Let's explain the loop.  A loop counter variable i is declared and initialised.  The break condition is then tested, (i < 11).  If the break condition evaluates to true then the code in the loop block is executed.  The increment statement causes the loop counter to be incremented by 1 (i++).  A new cycle starts where the break condition is tested again and if it evaluates to true the code in the loop block is executed again.  

The cycle continues until the break condition becomes false at which point the code in the loop block is skipped and program execution continues on the next line after the loop block.

In this example the loop is exited when the variable i is finally incremented to 11 and so the condition i<11 becomes false.  

Now, how about  look at a while loop!

While Loop

This loop is used when you aren’t sure how many times you need to repeatedly execute a block of code.  Let's create code for a two times table using a while loop.

public class TwoTimesTable2 {

    public static void main(String [] args) {

          int i = 1;

         while (i<11)  {

            System.out.println(i + " times 2 is " + (i*2));

            i++;

        }
    }
}


The while loop is called a pre-condition loop because the break condition is tested first.  In our example the break condition (i < 11) is first tested at the top of the loop and if it evaluates to true then the code in the loop block is executed.  We can see that because the loop counter i is incremented at the bottom of the loop every time the loop cycles, eventually i will reach a value of 11 and the loop will be exited.  

While loops can be useful if you want to create an indefinite loops. Look at the code below.  I have used the word true in the statement while(true).  Because of this, the loop condition is always going to be true.  So, this loop will run forever unless I add something inside the loop that will let me break out of it.  The keyword break lets you exit a loop and in the case below, the break statement will execute if some condition becomes true in the if statement.

while(true) {

    if (some condition becomes true) { break;}

     //do something

}

Why is this type of loop useful.  Perhaps you need your program to repeatedly carry out some task and break if the user say presses a certain key on the keyboard.

Now, how about a look at a do-while loop!

Do-While Loop

This loop is similar to the while loop except it is a post-condition loop.  This means that the loop condition is checked at the end of the loop and not at the beginning.  Let's have a look at some code.

public class TwoTimesTable3 {

    public static void main(String [] args) {

          int i = 1;

         do {

            System.out.println(i + " times 2 is " + (i*2));

            i++;

        }while (i<11); 
    }
}


In our example, the code in the loop executes at least once, since the loop condition is not checked until the end of the loop block is reached.  You might ask why we need these two types of loops at all?  In the TwoTimesTable example, there is no real difference in our code whether we choose to use a post or pre-condition loop.  However, sometimes you may want a loop block to execute at least once, in which case you would use the do-while loop.

 

~Now try the activity~

Activity 6D

  1. Create code for displaying the two times table in an applet window using a For loop.

  2. Create code for displaying the two times table in an applet window using a while loop.

  3. Create code for displaying the two times table in an applet window using a do-while loop.

Remember, you can use the g.drawString method in the paint method to display output in an applet window

Check out my code after you have created your own.

 


That is folks!!

Now try the Program Flow Control exercise

 

  Site Home 

Java Home   

  Forum  

Course Info

Welcome

Overview

Assessment

Qualification

Scheme of Work

Assignments

Resources

Information

Blackboard

Learning Center

Web Materials

Reading

Java Demos

Utilities

Links

Lecture Materials

Tutorials & Notes

Exercises

Activities

Quizzes

 

Site Home

Top

Unit Home

ADR 2002