Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www2.austin.cc.tx.us/baldwin/

Flow of Control

Java Programming, Lecture Notes # 26, Revised 10/03/99.

Preface
Introduction
Flow of Control
The while Statement
The if-else Statement
The switch-case Statement
The for Loop
The do-while Loop
The break and continue Statements
Unlabeled break and continue
Labeled break and continue Statements
Labeled break Statements
Labeled continue Statements
The return Statement
Exception Handling
Review

Preface

Students in Prof. Baldwin's Introductory Java Programming classes at ACC are responsible for knowing and understanding all of the material in this lesson (except that they are not responsible for detailed information that is specific to C++).

The detailed material on C++ is provided as supplementary material for the benefit of those persons who are already familiar with C++ and who are making the transition into Java.

Introduction

The first step

The first step in learning to use a new programming language is usually to learn the foundation concepts such as variables, types, expressions, flow-of-control, etc. This lesson concentrates on flow-of-control. In many cases, these concepts, as they apply to the Java language, are compared to the same concepts for the C++ language, identifying similarities and differences.

Flow of Control

What is flow of control?

Both C++ and Java support several different kinds of statements designed to alter or control the logical flow of the program, although in some cases, the behavior of those statements differs between Java and C++.

The ability to alter the logical flow of the program is often referred to as Flow of Control.

Statements that support flow of control

The following table lists the statements supported by Java (and by C++ with some exceptions) for controlling the logical flow of the program.

Statement            Type
if-else              selection
switch-case          selection
for                  loop
while                loop
do-while             loop
try-catch-finally    exception handling
throw                exception handling
break                miscellaneous
continue             miscellaneous
label:               miscellaneous
return               miscellaneous
goto                 reserved by Java but not supported

The while Statement

We've already seen the while statement

Several of the previous programs contained a while statement (involving I/O) designed to control the logical flow of the program.

Comparison of Java and C++ I/O

Note that the operation of the input/output system for Java is significantly different from that for C++ so the conditional expression that involved the I/O system was also different between the two.

Syntax of a while statement

In both languages, the general syntax of a while statement is as follows

while (conditional expression)
  statement or compound statement;

Behavior of a while statement

In both languages, the program will continue to execute the statement or compound statement for as long as the conditional expression evaluates to true.

Sample Java while statement

The following while statement was extracted from a previous Java program.

while( (ch1 = System.in.read() ) != '#') ch2 = ch1;

Sample C++ while statement

The while statement that follows was extracted from a previous C++ program.

while( (ch1 = getchar()) != '#') ch2 = ch1; 

How Java and C++ while statements differ

These two statements differ only in respect to how they use their respective input/output system to fetch a character from the keyboard before comparing it with the # character.

The C++ version is straightforward

The C++ statement is fairly straightforward in that the conditional expression simply calls one of the standard I/O functions which returns a character from the standard input device.

The Java version is less straightforward

The conditional expression in the Java statement is less straightforward.

The in variable of the System class

The System class defines a class variable named in. Since it is a class variable, it can be accessed using the name of the System class without the requirement to instantiate an object of the System class.

What does the in variable contain?

The in variable refers to an instance of a class that provides a read() method, which returns a character from the standard input device.

Therefore, the expression System.in.read() constitutes a call to the read method of the object referred to by the in variable of the System class.

A while loop is an entry condition loop

Note that the while statement is used to form an entry condition loop in both Java and C++. The significance of an entry condition loop is that the conditional expression is tested before the statements in the loop are executed. If it tests false initially, the statements in the loop will not be executed.

The if-else Statement

General syntax of an if statement

The general syntax of the if statement in Java is the same as its form in C++.

if(conditional expression)
  statement or compound statement;
else //optional
  statement or compound statement; //optional

Given the syntax, the behavior of this statement should be familiar to those students who have completed the prerequisite Programming Fundamentals course (or equivalent) so it won't be discussed further here.

The switch-case Statement

General syntax of a switch-case statement

The general syntax of the switch-case statement is the same in Java and C++. There is a similar selection statement in Pascal but its behavior is considerably different.

switch(expression){
  case constant:
    //sequence of optional statements
    break; //optional
  case constant:
    //sequence of optional statements
    break; //optional
.
.
.
  default //optional
    //sequence of optional statements
}

What type is the expression?

According to the book, Java Language Reference, by Mark Grand, the expression must be byte, char, short, or int.

What is the behavior?

This expression is tested against a series of constants of the same type (assignable to the type of the switch expression). If a match is found, the sequence of optional statements is executed.

Execution of statements continues until the optional break is encountered. When break is encountered, execution of the switch statement is terminated and control is passed to the next statement following the switch statement.

How does this work in C++?

Also in C++, the expression must evaluate to an integer. This integer is tested against a series of integer or character constants. If a match is found, the sequence of optional statements is executed. Execution of statements continues until the optional break is encountered. When break is encountered, execution of the switch statement is terminated and control is passed to the next statement following the switch statement.

Note that character matches are possible in C++ because the char type is C++ is really an 8-bit integer type. That is not the case in Java.

Tell me more about the case constant

In both languages, each case constant must be unique.

What is the purpose of the default keyword?

If no match is found and the optional default keyword along with a sequence of optional statements has been provided, those statements will be executed.

Labeled break

Java also supports labeled break statements. This capability can be used to cause Java to exhibit different behavior when switch statements are nested. This will be explained more fully in a later section on labeled break statements.

The for Loop

Actions of a for loop

The operation of a loop normally involves three actions in addition to executing the code in the body of the loop:

Grouping the actions

Both Java and C++ provide the for loop construct which groups these three actions in one place. Although there is no general difference in the basic behavior of the for loop in Java and C++, differences in other features (such as labeled break and continue statements) can cause it to appear that the behavior is different.

The syntax of a for loop

The heart of a for loop in both Java and C++ consists of three clauses separated by semicolons as shown below.

for (first clause; second clause; third clause)
  single or compound statement

What do the clauses contain?

The first and third clauses can consist of one or more expressions, separated by the comma operator.

What about the comma operator?

In both Java and C++, the comma operator guarantees that its left operand will be executed before its right operand.

While the comma operator has other uses in C++, this is the only use of the comma operator in Java.

Behavior and purpose of the first clause

The expressions in the first clause in both Java and C++ are executed only once, at the beginning of the loop. Any legal expression(s) may be contained in the first clause, but typically the first clause is used for initialization.

Declaring and initializing variables in the first clause

Note that variables can also be declared and initialized in the first clause, and this has an interesting ramification regarding scope that will be discussed later.

Behavior of the second clause

The second clause in both Java and C++ consists of a single expression that must eventually evaluate to false to cause the loop to terminate.

Since any expression that evaluates to zero is treated as false in C++, the range of possible expressions that can be used in the second clause in C++ is limitless.

Java is somewhat more restrictive than C++ in this regard. The expression in the second clause in Java must evaluate to a boolean type.

Typically relational expressions or relational and conditional expressions are used in the second clause.

When is the test performed?

The value of the second clause is tested when the statement first begins execution, and at the beginning of each iteration thereafter. Therefore, the for loop is an entry condition loop.

When is the third clause executed?

Although the third clause appears physically at the top of the loop, it isn't executed until the statements in the body of the loop have completed execution.

This is an important point since this clause is typically used to update the control variable, and perhaps other variables as well.

What can be contained in the third clause?

Multiple expressions can appear in the third clause, separated by the comma operator. Again, those expressions will be executed from left to right. If variables are updated in the third clause and used in the body of the loop, it is important to understand that they do not get updated until the execution of the body is completed.

Behavior of first clause in C++

As mentioned earlier, it is also allowable to declare variables in the first clause of a for loop.

The most up-to-date versions of C++ compilers allow declaration of loop control variables inside the for loop having the same name as variables declared outside the loop. The scope of those variables declared inside the loop is limited to the loop. This is illustrated by the following C++ program which declares a local method variable named cnt and then declares a loop control variable named cnt. The values of the two variables having the same name are displayed at several points in the program. The output produced by this program is shown in the comments at the beginning of the program.

/*File for1.cpp Copyright 1997, R.G.Baldwin
This program illustrates the declaration of a local 
method variable and the declaration of a loop 
control variable having the same name.  
The output from the program follows:

Value of method var named cnt is 5
Value of loop var named cnt is 0
Value of loop var named cnt is 1
Value of method var named cnt is 5

This program was compiled using Borland's C++ for 
Windows, Version 5.0
*******************************************************/

#include<iostream.h>

class for1 {
public:
  static void classMain(); //this method is defined below
};//End class definition.

void for1::classMain(){ //define classMain method
  int cnt = 5; //declare local method variable
  cout << 
    "Value of method var named cnt is " << cnt << endl;
  for(int cnt = 0; cnt < 2; cnt++)
    cout << 
      "Value of loop var named cnt is " << cnt << endl;
  cout << 
    "Value of method var named cnt is " << cnt << endl;
}//end classMain
//======================================================

void main()
{
  //call the class method named classMain
  for1::classMain(); 
}//end main

While Java has a similar feature, it is more restrictive regarding variable names than is C++.

The Java compiler, version JDK 1.1.3 treats variables declared inside the first clause of a for loop differently from the way they are treated in C++.

The above C++ program declared a variable named cnt at two different places in the program, once outside the for loop and once inside the first clause of the for loop. However, that doesn't work in Java.

Declaring a variable in for loop in Java

In Java, you can declare a variable with a given name outside (prior to) the for loop, or you can declare it inside the for loop, but not both.

If you declare it outside the for loop, you can access it either outside or inside the loop.

However, if you declare it inside the loop, you can access it only inside the loop. In other words, the scope of variables declared inside a for loop is limited to the loop.

This is illustrated in following sequence of four simple programs.

This program won't compile

The following Java program refuses to compile with a complaint that a variable named cnt has already been declared in the method when the attempt is made to declare it in the for loop.

/*File for1.java Copyright 1997, R.G.Baldwin
This program will not compile because the variable 
named cnt is declared twice.
********************************************************/
class for1 { //define the controlling class
  public static void main(String[] args){ //main method
    int cnt = 5; //declare local method variable
    System.out.println(
          "Value of method var named cnt is " + cnt);

    for(int cnt = 0; cnt < 2; cnt++)
      System.out.println(
              "Value of loop var named cnt is " + cnt);

    System.out.println(
            "Value of method var named cnt is " + cnt);
  }//end main
}//End controlling class.  Note no semicolon required

This program also won't compile, but for a different reason

The declaration of the variable named cnt, outside the for loop, was removed from the next program and the declaration inside the loop was allowed to remain. This eliminated the problem of attempting to declare the variable twice.

However, this program refused to compile because an attempt was made to access the variable named cnt outside the for loop. This was not allowed because the variable was declared inside the for loop and the scope of the variable was limited to the loop.

/*File for2.java Copyright 1997, R.G.Baldwin
This program will not compile because the variable 
declared inside the for loop is not accessible 
outside the loop.
********************************************************/
class for2 { //define the controlling class
  public static void main(String[] args){ //main method
 
    for(int cnt = 0; cnt < 2; cnt++)
      System.out.println(
                  "Value of loop var named cnt is " + cnt);

    System.out.println(
                "Value of method var named cnt is " + cnt);
  }//end main
}//End controlling class.  Note no semicolon required

This program will compile

The following Java program will compile and run because the variable named cnt that is declared inside the for loop is accessed only inside the for loop. No reference to a variable with the same name appears outside the loop.

/*File for3.java Copyright 1997, R.G.Baldwin
This program will compile because the variable declared 
inside the for loop is accessed only inside the loop.
**********************************************************/
class for3 { //define the controlling class
  public static void main(String[] args){ //main method
 
    for(int cnt = 0; cnt < 2; cnt++)
      System.out.println(
                  "Value of loop var named cnt is " + cnt);
  }//end main
}//End controlling class. 

This program will also compile

Similarly, the following Java program will compile and run because the variable named cnt was declared outside the for loop and was not declared inside the for loop. This made it possible to access that variable both inside and outside the loop.

/*File for4.java Copyright 1997, R.G.Baldwin
This program will compile and run because the variable 
named cnt is declared outside the for loop and is not
declared inside the for loop.
**********************************************************/
class for4 { //define the controlling class
  public static void main(String[] args){ //main method
    int cnt = 5; //declare local method variable
    System.out.println(
              "Value of method var named cnt is " + cnt);

    for(cnt = 0; cnt < 2; cnt++)
      System.out.println(
                  "Value of loop var named cnt is " + cnt);

    System.out.println(
                "Value of method var named cnt is " + cnt);
  }//end main
}//End controlling class.  Note no semicolon required

Empty clauses in a for loop

The first and third clauses in a for loop can be empty but the semicolon must be there as a placeholder.

One author suggests that even the middle clause can be empty, but it isn't obvious to this author how the loop would ever terminate if there is no conditional expression to be evaluated. Perhaps the loop could be terminated by using a break inside the loop, but in that case, you might just as well use a while loop.

The do-while Loop

An exit-condition loop

Both Java and C++ provide an exit-condition loop having the general syntax shown below.

do {
    statements
              } while (conditional expression);

Behavior

The statements in the body of the loop continue to be executed for as long as the conditional expression evaluates to true. An exit-condition loop guarantees that the body of the loop will be executed at least one time, even if the conditional expression evaluates to false the first time it is tested.

Other than the differences resulting from the availability of labeled break and continue statements in Java, and the difference in the way that Java and C++ determine true and false, there is essentially no difference in the behavior of the do-while loop in Java and C++.

The break and continue Statements

Comparison between Java and C++

The break and continue statements in Java differ significantly from the corresponding statements in C++. In particular, in addition to the "normal" behavior of these statements in Java which matches the behavior in C++, Java also supports the use of labeled break and labeled continue statements.

General behavior

Although some authors suggest that this provides an alternative to the infamous goto statement (which is still supported by C++ but is not supported by Java), it appears that the behavior of the labeled break and labeled continue statements is much more restrictive than a general goto.

In particular, it appears that a labeled break or continue will compile successfully only if the labeled statement is a statement which would normally be referenced by an unlabeled break or continue.

Unlabeled break and continue

First consider the behavior of break and continue in their unlabeled configuration in both Java and C++.

Use of a break statement

The break statement can be used either in a switch statement or in a loop. When encountered in a switch statement, break causes control to be passed to the next statement outside the innermost enclosing switch statement.

When break is encountered in a loop, it causes control to be passed to the next statement outside the innermost enclosing loop.

As we will see later, labeled break statements can be used to pass control to the next statement following switch or loop statements beyond the innermost switch or loop statement when those statements are nested.

Use of a continue statement

The continue statement cannot be used in a switch statement, but is confined to loops.

When an unlabeled continue statement is encountered in either Java or C++, it causes the current iteration to be terminated and the next iteration to begin.

A labeled continue statement can cause control to be passed to the next iteration of an outer enclosing loop in a nested loop situation.

An example of the use of an unlabeled switch statement is given in the next section.

Labeled break and continue Statements

This section discusses the use of labeled break and continue statements.

Labeled break Statements

One way to describe the behavior of a labeled break in Java is to say: "Break all the way out of the labeled statement."

Syntax of a labeled statement

To begin with, the syntax of a labeled statement is the same in Java or C++: a label followed by a colon ahead of the statement. The label can be any legal Java or C++ identifier. This syntax is illustrated in the following example.

myLabel:  myStatement;

Behavior of labeled break

The behavior of a labeled break can best be illustrated using nested switch statements. For a comparison of labeled and unlabeled switch statements, consider the following program named switch1.java which does not use a labeled break. Even though this program has a labeled statement, that statement is not referenced by a break. Therefore, the label is of no consequence.

After reviewing switch1.java, consider the same program modified to use a labeled break which is named switch2.java. The outputs from both programs are shown in the comments at the beginning of the program. By examining the second program, and comparing the output from the second program with the first program, you should be able to see how the use of the labeled break statement causes control to break all the way out of the labeled switch statement.

/*File switch1.java
This is a Java application which serves as a baseline
comparison for switch2.java which uses a labeled break.
Note that the program uses nested switch statements.

The program displays the following output:

Match and break from here
Case 6 in outer switch
Default in outer switch
Beyond switch statements

********************************************************/
class switch1 { //define the controlling class
  public static void main(String[] args){ //main method

  //Note that the following labeled switch statement is
  // not referenced by a labeled break in this program.
  // It will be referenced in the next program.  
  outerSwitch: switch(5){//labeled outer switch statement
    case 5: //execute the following switch statement
    //Note that the code for this case is not followed 
    // by break. Therefore, execution will fall through
    // the case 6 and the default.
      switch(1){ //inner switch statement
        case 1: System.out.println(
                            "Match and break from here");
                break; //break with no label
        case 2: System.out.println(
                           "No match for this constant");
                break;
      }//end inner switch statement

    case 6: System.out.println("Case 6 in outer switch");
    default: System.out.println(
                              "Default in outer switch");
  }//end outer switch statement

  System.out.println("Beyond switch statements");
  }//end main
}//End switch1 class.  

The modified program which uses a labeled break statement follows. By comparing the output from this program with the output from the previous program, you can see that execution of the labeled break statement caused control to break all the way out of the labeled switch statement completely bypassing case 6 and default.

/*File switch2.java
This is a Java application which uses a labeled break.
Note that the program uses nested switch statements.

See switch1.java for a comparison program which does not
use a labeled break.

The program displays the following output:

Match and break from here
Beyond switch statements
**********************************************************/
class switch2 { //define the controlling class
  public static void main(String[] args){ //main method

  outerSwitch: switch(5){//labeled outer switch statement
    case 5: //execute the following switch statement
    //Note that the code for this case is not followed by
    // break. Therefore, except for the labeled break at 
    // case 1, execution would fall through the case 6 and
    // the default as demonstrated in the program named
    // switch1. However, the use of the labeled break
    // causes control to break all the way out of the
    // labeled switch bypassing case 6 and the default.
      switch(1){ //inner switch statement
        case 1: System.out.println(
                              "Match and break from here");
                break outerSwitch; //break with label
        case 2: System.out.println(
                             "No match for this constant");
                break;
      }//end inner switch statement

    case 6: System.out.println(
                                 "Case 6 in outer switch");
    default: System.out.println("Default in outer switch");
  }//end outer switch statement

  System.out.println("Beyond switch statements");
  }//end main
}//End switch1 class. 

As you can see from examining the output, the labeled break statement (repeated below) causes the program to break all the way out of the switch statement which bears a matching label.

break outerSwitch; //break with label

A similar situation exists when a labeled break is used in nested loops with one of the enclosing outer loops being labeled. Control will break out of the enclosing loop to which the labeled break refers. It will be left as an exercise for the student to demonstrate this behavior to his or her satisfaction.

Labeled continue Statements

Now consider use of the labeled continue statement. A continue statement can only be used in a loop; it cannot be used in a switch. The behavior of a labeled continue statement can be described as follows: "Terminate the current iteration and continue with the next iteration of the loop to which the label refers."

Again, it will be left as an exercise for the student to demonstrate this behavior to his or her satisfaction.

The return Statement

Use of the return statement

Both Java and C++ support the use of the return statement to terminate a method or function and (optionally) return a value to the calling method or function.

Pascal programmers will recall that it is possible to return a value from a Pascal function but the keyword return is not part of the Pascal language. Rather, in order to return a value from a Pascal function, a statement is executed which appears to be assigning the value to an identifier which matches the name of the function.

The return type

The type of value returned in C++ and Java must match the type of the declared return value for the method or function.

The void return type

If the return value is declared as void, you can use the following syntax to terminate the function. (You can also simply allow the method or function to run out of statements to execute.)

return;

Returning a value

If the method or function returns a value, follow the word return with an expression (or constant) which evaluates to the value being returned as in the following:

return x+y;

Returning by pointer or reference in C++

C++ allows you to return by value, pointer, or reference. Care must be exercised when returning by pointer or reference in C++ to ensure that the object being referred to will continue to exist after the function terminates. For example, returning a pointer or a reference to a local automatic variable in a function can lead to problems since the variable will cease to exist as soon as the function terminates.

The Borland C++ compilers used by this author will not permit you to return a reference to an automatic local variable but they will allow you to return a pointer to such a variable. This is illustrated in the following simple C++ program which returns a pointer to a local variable, creates an array in the main function to modify memory, and then uses the returned pointer to display the contents of the pointed-to memory. The program displays garbage because after the function terminates, the pointer points to a memory address which is no longer valid. This is one of the pitfalls that Java is designed to eliminate.

/* File return1.cpp Copyright 1997, R.G.Baldwin
Illustrates an attempt to return a local variable by 
pointer from a function.  The memory occupied by 
the local variable is overwritten after the function 
terminates, and the pointer then points to garbage.

The output from the program is garbage.
*/

#include <iostream.h>

int* test()
{
  //declare a local variable in the function
  int localVar = 6; 
  //put its address in a pointer variable
  int* ptr = &localVar; 
  return ptr; //return the pointer to the local variable
}//end test

void main()
{
  //save pointer returned by function
  int * mainPtr = test(); 
  // consume some memory
  int memEater[5] = {10,11,12,13,14};
  //Display the contents of the memory pointed to 
  // nce the variable is stored by the pointer.
  cout << "Return value is " << *mainPtr;
  //The above statement displays garbage.
} //end main

Return by value only, please

Apparently in Java, you are allowed to return only by value. In the case of primitive types, this returns a copy of the returned item.

In the case of objects, returning by value returns a copy of the address where the object is stored.

What can you do with a copy of the address?

Note that having a copy of the address is just as good as having the original address. All objects in Java are stored in dynamic memory and that memory is not overwritten until all references to that memory cease to exist.

Illustrating return by value in Java

This is illustrated in the following Java application which

The program successfully displays the contents of the object. This program does not necessarily prove the point because the object could have escaped being overwritten by sheer luck. However, the fact that it continued to exist with valid data does suggest very strongly that the object was being protected by the system and was not eligible for garbage collection.

Note that this program also illustrates the need to instantiate an object of the controlling class in order to allow its (non-class) methods to be called by code in main(). This is because main is static and code in static methods can only access other static methods. The test method used in this program is not static.

/*File return2.java Copyright 1997, R.G.Baldwin
This is a Java application program which illustrates 
returning a reference to an object from a method.

The program also illustrates instantiating an object of 
the controlling class to allow its methods to be called.

The output from this program is as shown below:

Return value is 6

**********************************************************/
class return2 { //define the controlling class

  public static void main(String[] args){ //main method
    //Instantiate an object of the controlling class to 
    // allow its methods to be called.
    return2 obj = new return2();

    //Declare a reference to an object of the type which 
    // will be returned from the test() method.
    myClass mainObj;

    //Use the object of the controlling class to call the
    // test() method and assign the returned reference to 
    // mainObj.
    mainObj = obj.test();

    //Attempt to overwrite the returned object by creating
    // a very large array and filling it with data.
    int[] memEater = new int[2000000];
    for(int i = 0; i < 2000000; i++) memEater[i] = i + 5;

    //Display the value in the object returned by test()
    // to show that the reference is still valid.
    System.out.println("Return value is " 
                                        + mainObj.myData );
  }//end main

  //this is a method of the controlling class
  myClass test(){ 
    //instantiate a local object
    myClass localObj = new myClass(6); 
    //return reference to the local object
    return localObj; 
  }//end test method
}//End controlling class.

class myClass{//class used to instantiate object in test()
  int myData;
  myClass(int inData){myData = inData;}//constructor
} //end myClass

When are Java objects destroyed?

The above Java application does not suffer from the same problem as the previous C++ program because objects instantiated in a function are not destroyed when the function terminates unless all references to the object have ceased to exist.

In this case, the reference is assigned to and saved in a reference variable which is a local variable in the calling method, main() so that it doesn't cease to exist.

A similar C++ program

The following C++ program provides behavior similar to the Java program. In this program, rather than declaring an automatic variable in the function, code in the function creates an automatic pointer variable in the function and also creates a variable in dynamic memory. The address of that variable in dynamic memory is assigned to the automatic pointer variable in the function.

Although the automatic pointer variable in the function is destroyed when the function terminates, the variable in dynamic memory is not destroyed in this case until the program terminates (no calls were made to the delete operator). A copy of the automatic pointer variable is returned from the function and assigned to a pointer variable in the calling function, which continues to point to valid data in memory even after the function terminates.

This is one way to cause a function in C++ to instantiate an object and pass it back to the calling function while maintaining its validity after the function terminates.

/* File return2.cpp Copyright 1997, R.G.Baldwin
Illustrates storing a variable in dynamic memory in a
function, and then returning a pointer to that variable.

Since the variable is stored in dynamic memory, the 
memory occupied by the local variable is not 
overwritten after the function terminates.  The pointer 
which was returned from the function still points to 
the variable and can be used to display it.

The output from the program is:

Return value is 6

*******************************************************/
#include <iostream.h>
#include <new.h>
#include <stdlib.h>

int* test(){
  //system will return null on allocation error
  set_new_handler(0);
  //declare a variable in the function
  int* ptr = new int(6);
  if(!ptr) exit(1); //abort on failure to allocate
  return ptr; //return the pointer to the local variable
}//end test

void main(){
  //save pointer returned by function
  int * mainPtr = test();
  // consume some memory
  int memEater[5] = {10,11,12,13,14};
  //Display the contents of the memory pointed to by
  // the pointer.
  cout << "Return value is " << *mainPtr;
} //end main

Exception Handling

Exception handling is a process which modifies the flow of control of a program, so it merits being mentioned in this lesson. However, it is a fairly complex topic in both Java and C++. This topic will be discussed in detail in subsequent lessons.

Suffice it at this point to say that whenever an exception is detected, control is transferred to an exception event handler if such an event handler has been provided. Otherwise, the program will terminate. Thus, the exception handling system should be mentioned in discussions regarding flow of control.

Review

Q - List and describe eight of the statements used in Java programs to alter or control the logical flow of the program.

A - The following table lists the statements supported by Java for controlling the logical flow of the program.

Statement            Type
if-else              selection                   
switch-case          selection                    
for                  loop                         
while                loop                         
do-while             loop                       
try-catch-finally    exception handling        
throw                exception handling         
break                miscellaneous            
continue             miscellaneous               
label:               miscellaneous             
return               miscellaneous           
goto                 reserved by Java but not supported

Q - Provide pseudo-code that illustrates the general syntax of a while statement in Java.

A - The general syntax of a while statement follows :

while (conditional expression)
  statement or compound statement;

Q - During the execution of a while statement in Java, the program will continue to execute the statement or compound statement for as long as the conditional expression evaluates to true, or until a break or continue statement is encountered: True or False. If false, explain why.

A - True.

Q - A while loop in Java is an entry condition loop: True or False? If false, explain why.

A - True. The while statement is used to form an entry condition loop in Java.

Q - What is the significance of an entry condition loop?

A - The significance of an entry condition loop is that the conditional expression is tested before the statements in the loop are executed. If it tests false initially, the statements in the loop will not be executed.

Q - Provide pseudo-code illustrating the general syntax of the if else statement in Java.

A - The general syntax of the if-else statement in Java is:

if(conditional expression)
  statement or compound statement;
else //optional
  statement or compound statement; //optional

Q - Provide pseudo-code illustrating the general syntax of the switch-case statement in Java.

A - The general syntax of the switch-case statement follows:

switch(expression){
  case constant:
    sequence of optional statements
    break; //optional
  case constant:
    sequence of optional statements
    break; //optional
.
.
.
  default //optional
    sequence of optional statements
}

Q - Describe the behavior of a switch-case statement. Provide a pseudo-code fragment that illustrates your description of the behavior. Do not include a description of labeled break statements.

A - The pseudo-code fragment follows:

switch(expression){
  case constant:
    sequence of optional statements
    break; //optional
  case constant:
    sequence of optional statements
    break; //optional
.
.
.
  default //optional
    sequence of optional statements
}

An expression is tested against a series of unique integer constants. If a match is found, the sequence of optional statements associated with the matching constant is executed. Execution of statements continues until an optional break is encountered. When break is encountered, execution of the switch statement is terminated and control is passed to the next statement following the switch statement.

If no match is found and the optional default keyword along with a sequence of optional statements has been provided, those statements will be executed.

Q - What are the three actions normally involved in the operation of a loop (in addition to executing the code in the body of the loop)?

A - The operation of a loop normally involves the following three actions in addition to executing the code in the body of the loop:

Q - The heart of a for loop consists of three clauses separated by colons: True or False? If false, explain why.

A - False: The heart of a for loop consists of three clauses separated by semicolons, not colons.

Q - Provide pseudo-code illustrating the general syntax of a for loop in Java.

A - The general syntax of a for loop in Java is shown below.

for (first clause; second clause; third clause)
  single or compound statement

Q - In a for loop, the first and third clauses within the parentheses can consist of one or more expressions, separated by the comma operator: True of False. If False, explain why.

A - True. The first and third clauses can consist of one or more expressions, separated by the comma operator.

Q - What is the guarantee made by the comma operator?

A - The comma operator guarantees that its left operand will be executed before its right operand.

Q - The expressions within the first clause in the parentheses in a for loop can be executed only once during each iteration of the loop: True or False? If false, explain why.

A - False. The expressions in the first clause may be executed only once, at the beginning of the loop, regardless of the number of iterations.

Q - While any legal expression(s) may be contained in the first clause within the parentheses of a for loop, the first clause has a specific purpose. What is that purpose?

A - Any legal expression(s) may be contained in the first clause of a for loop, but typically the first clause is used for initialization. The purpose of the first clause is initialization.

Q - Variables can be declared and initialized within the first clause in the parentheses of a for loop? True or False. If false, explain why.

A - True. Variables can be declared and initialized in the first clause of a for loop.

Q - The second clause in the parentheses of a for loop consists of a single expression which must eventually evaluate to true to cause the loop to terminate: True or False? If false, explain why.

A - False. The second clause consists of a single expression which must eventually evaluate to false (not true) to cause the loop to terminate.

Q - A for loop is an exit condition loop: True or False? If false, explain why.

A - False. The value of the second clause is tested when the statement first begins execution, and at the beginning of each iteration thereafter. Therefore, the for loop is an entry condition loop.

Q - Because a for loop is an entry condition loop, the third clause inside the parentheses is executed at the beginning of each iteration: True or False? If false, explain why.

A - False. Although the third clause appears physically at the top of the loop, it isn't executed until the statements in the body of the loop have completed execution. This is an important point since this clause is typically used to update the control variable, and perhaps other variables as well. If variables are updated in the third clause and used in the body of the loop, it is important to understand that they do not get updated until the execution of the body is completed.

Q - A return statement is used to terminate a method and (optionally) return a value to the calling method: True or False? If False, explain why.

A - True. Java supports the use of the return statement to terminate a method and (optionally) return a value to the calling method or function.

Q - Exception handling modifies the flow of control of a Java program: True or False. If false, explain why.

A - True. Exception handling is a process which modifies the flow of control of a program.

-end-