您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

INT4120 Semester 2 1999/2000




MIDDLESEX UNIVERSITY


EXAMINATION PAPER


1999/2000 Semester 2




INT4120


Object-oriented

software development






Time allowed: 2 hours


Total number of questions: five


Instructions to candidates: answer three questions from five


Materials provided: none


Equipment permitted: calculators; printed language and translations dictionaries



Q1.

(Mark weighting: section A - 10%; section B - 30%; section C - 30%; section C - 30%)


A. Examine the Java program below. The program displays a simple window like this:





import java.awt.*;


class HelloWindow extends Frame // Line 1

{

HelloWindow() // Line 2

{

super ("Hello"); // Line 3

setSize(250,100); // Line 4

show(); // Line 5

}


public void paint (Graphics g) // Line 6

{

g.drawString("Hello world", 40, 60); // Line 7

}

}


public class exam1 // Line 8

{

public static void main(String args[]) // Line 9

{

HelloWindow helloWindow = new HelloWindow(); // Line 10

}

}



Explain, in outline, how the program accomplishes this.


B. Describe the exact sequence in which each of the program instructions will be executed when the command `java exam1' is given, and why. What happens after the last line is executed?


C. Describe, in as much detail as possible, the exact functions of each of the numbered lines in the program listing above.


D. When this program is executed, the window it creates appears to have a button in the caption bar that will cause the window to close. However, if the user clicks this button, nothing will happen. Why not? Describe briefly, but mentioning appropriate Java classes, how the programmer can arrange that the program exit when the user clicks the close button.



Q2.

(Mark weighting: section A - 50%; section B - 30%; section C - 20%)

A. Explain, using examples (and diagrams if necessary), the meanings of the following terms in object-oriented programming, particular as applied to Java. Note that the answer will be marked primarily on the quality of the examples, rather than the textual descriptions.

  1. subclass

  2. constructor

  3. interface

  4. abstract class

  5. method


B. Explain, using a few lines of Java, how a method called X with no parameters and return-type `void' is implemented in a class `Y'; how an instance of class X is created, and how method Y is called in that instance.


C. Explain what multiple inheritance is, why (briefly) it is not allowed in Java programs, and how the `interface' mechanism is intended to provide a substitute.




Q3.

(Mark weighting: section A - 50%; section B - 30%; section C - 20%)

A. Describe the roles of a compiler, an interpreter and a run-time engine in the software development process, particularly as they apply to programming in Java. Explain how a Web browser behaves as a run-time engine for the execution of Java applets.


B. Describe how the Sun JDK tools may be used to compile and execute a Java program, which is implemented as an applet (not a stand-alone application). Using an example, list the files that are provided by the programmer, and the files that are generated during the compile-execute process. Which files should be provided (on a Web server or elsewhere) to an end-user so that the user is able to run the applet? Assume the end-user does not have access to the JDK package.


C. A `just-in-time' (JIT) compiler for Java compiles Java `bytecode' (the output from the compiler) into native machine code, and then executes it. How does this improve the speed of execution compared to an `interpreting' run-time engine, while at the same time maintaining cross-platform compatibility without the need to distribute source code?



Q4

(Mark weighting: section A - 30%; section B - 40%; section C - 20%; section D - 10%)


A. In programming, what are the meanings of syntax error, logical error, and exception? Give examples in Java of each of these.


B.

(i) What different styles of comment does Java support? What is a documentation comment? Why are comments, indentation and layout important in programming?


(ii) Using whichever indentation convention you prefer, rewrite the following section of Java using indentation, so that the structure is clear (it is not important that the program does not do anything useful). Hence, or otherwise, detect and correct the syntax error in the code.


class X

{

int a;

public void Y()

{

for (int i = 0; i < 5; i++)

{

if (i == 2) Z(); else B(i);

}

}

}

a = 2;

}


C. In what ways is it suggested that the use of object-oriented development techniques may make it easy for the developers to handle logical errors than might otherwise be the case?


D. In the Java example in section B(ii), an attempt to compile the code would produce an error message of the form `class or interface declaration expected' on the line ``a = 2''. What does this error message mean, and why has it arisen?




Q5.

(Mark weighting: section A - 40%; section B - 40%; section C - 20%)


A.

(i) Explain why the following piece of Java, which attempts to calculate `5 divided by 2', gives the `wrong' answer (that is, it displays `2' and not `2.5').


int result = 5 / 2;

System.out.println(result);


(ii) Explain why the following piece of Java does not solve the problem described in part (i).


double result = 5 / 2;

System.out.println(result);


(iii) Suggest a simple modification that would cause the program to calculate and display the result correctly


(iv) Not all programming languages would give the `wrong' answer in situations like the above; why might the Java designers have made the assumptions that they did that lead to this problem?


B.

(i) Illustrate three loop constructs available to the Java programmer, by showing how each can be used to add the numbers from 1 to 10.


(ii) In theory, one loop construct can do the work of any of the others. Why does Java provide a number of different looping mechanisms?


C. In Java, what are the differences between a String, a StringBuffer, and an array of characters?



Q1.

(Mark weighting: section A - 10%; section B - 30%; section C - 30%; section C - 30%)


A. Examine the Java program below. The program displays a simple window like this:




import java.awt.*;


class HelloWindow extends Frame // Line 1

{

HelloWindow() // Line 2

{

super ("Hello"); // Line 3

setSize(250,100); // Line 4

show(); // Line 5

}


public void paint (Graphics g) // Line 6

{

g.drawString("Hello world", 40, 60); // Line 7

}

}


public class exam1 // Line 8

{

public static void main(String args[]) // Line 9

{

HelloWindow helloWindow = new HelloWindow(); // Line 10

}

}



Explain, in outline, how the program accomplishes this.


The program creates an object of type HelloWindow, which is a sub-class of Frame. Most of the important functionality is implemented in Frame or its base classes. When the object is created, it sets its caption by calling the constructor for Frame, which has this function. The window then sets its size and makes itself visible.


B. Describe the exact sequence in which each of the program instructions will be executed when the command `java exam1' is given, and why. What happens after the last line is executed?


The program starts from `main' in the class specified to the `java' program. So the first instruction to be executed is line 10. (lines 8 and 9 are defining statements, not instructions). This causes a new object to be instantiated, thus causing its constructor to execute, starting from line 3. Execution then proceeds with lines 4 and 5. After line 5, no further lines of this program are executed, but code in the base classes of HelloWindow will be executed, in response to user and system events.


C. Describe, in as much detail as possible, the exact functions of each of the numbered lines in the program listing above.


Line 1: indicates that the following is the definition of a class called HelloWindow which is a subclass of Frame

Line 2: indicates that the following is the definition of the constructor for HelloWindow

Line 3: calls the constructor for Frame, passing the string ``hello'' as a parameter. This has the effect of setting the Frame caption

Line 4: sets the size of the Frame to 250 pixels wide by 100 pixels high

Line 5: shows the Frame. This has the effect of making the Frame visible on the screen, and able to respond to events.

Line 6: indicates that the following is the definition of a method called paint() that takes on parameter g of class Graphics. This method is called by the Java system when the Frame needs to be repainted

Line 7: displays the text on the screen at the specified X and Y position

Line 8: indicates that the following is the definition of a class called exam1

Line 9: defines a method called main(). This will be executed when the class is specified to the Java run-time system

Line 10: create a new object of class HelloWindow, and store the reference in the variable helloWindow


D. When this program is executed, the window it creates appears to have a button in the caption bar that will cause the window to close. However, if the user clicks this button, nothing will happen. Why not? Describe briefly, but mentioning appropriate Java classes, how the programmer can arrange that the program exit when the user clicks the close button.


The programmer has provided no instructions on how the window closure is to be effected. There is no default behaviour in Frame or its base classes. The programmer needs to handle window events for this class, probably by defining a WindowListener . This involves creating a class that implements the WindowListener interface, and calling addWindowListener on the object of class HelloWindow that is created. This class implements a windowClosed method which will be called by the run-time when the close button is clicked. This method should close the program, perhaps by calling System.exit(0).


Q2.

(Mark weighting: section A - 50%; section B - 30%; section C - 20%)

A. Explain, using examples (and diagrams if necessary), the meanings of the following terms in object-oriented programming, particular as applied to Java. Note that the answer will be marked primarily on the quality of the examples, rather than the textual descriptions.

  1. subclass

  2. constructor

  3. interface

  4. abstract class

  5. message



  1. The subclass relationship indicates that one class is a `type of' another, or `like' another. In Java the keyword `extends' indicates this. For example, a program's main window is likely to be a subclass of Frame.

  2. A constructor is the method that is executed whenever a new object of that class is created. For example, the Frame constructor sets the caption of a window as specified, among other things

  3. An interface is a class with no implementation; the methods are defined but not program statements are associated with them. For example `WindowListener' in Java is an interface with methods that are called when window events occur. It is an interface because there is no implementation for these methods; the programmer provides implementation that is appropriate for the application

  4. An abstract class has, even in theory, no instances. Of course any class may happen to have no instances; an abstract class has no instances by definition. For example, we may define a class `Shape' to encapsulate the common behaviour of a number of different shapes, e.g., square, circle. No instances of `Shape' are constructed, it is simply an aid to organization.

  5. A method is a function member of a class, or a self-contained unit of functionality, or an encapsulation of code (however you want to express it). Examples include Graphics.drawString(), Component.show(), etc.


B. Explain, using a few lines of Java, how a method called X with no parameters and return-type `void' is implemented in a class `Y'; how an instance of class X is created, and how method Y is called in that instance.


The definition is as follows:


class X

{

void Y()

{

//... program statements

}

}


The instantiation is:


X x = new X();


The method call is


x.y();



C. Explain what multiple inheritance is, why (briefly) it is not allowed in Java programs, and how the `interface' mechanism is intended to provide a substitute.


Multiple inheritance is the definition of a class that inherits behaviour and properties from more than one base class. Many, but not all, authorities suggest that multiple inheritance is dangerous for a number of reasons. A particular case is the so-called `diamond of death', where a class inherits from the same indirect base class twice. For example, X is a type of Y which is a type of Z, X is a type of A which is a type of Z. It is not clear how often Z.method() should be executed if X.method() is called. Java's interface mechanism gets round these complications by only allowing multiple inheritance from interfaces. As interfaces have no implementation, there is no argument about how often a method is executed. However, it becomes necessary to provide the missing implementation somewhere, often by a process of delegation.


Q3.

(Mark weighting: section A - 50%; section B - 30%; section C - 20%)

A. Describe the roles of a compiler, an interpreter and a run-time engine in the software development process, particularly as they apply to programming in Java. Explain how a Web browser behaves as a run-time engine for the execution of Java applets.


A compiler translates program text into machine code (called bytecode in Java). The machine code is a sequence of numerical instructions intended to be processed directly by a computer's hardware. Java bytecodes are not intended to be processed by a specific computer's hardware, but they are at a similar level of abstract to true machine code. An interpreter processes program text on a line-by-line basis, perhaps with some kind of pre-processing. A run-time engine is any piece of software that supports the execution of a program once it has been started. In Java, the run-time engine acts as an interpreter (or JIT compiler) for byte-codes, thus making the run-time platform-specific, while the compiler is platform-independent. A Web browser takes the name of a Java class as input when an <APPLET> tag is encountered. The bytecode file corresponding to the specified class is interpreted by the Web browser, or by some other software to which is delegates this function. In addition, the Web browser is a source of events to the executing program. Blah, blah...


B. Describe how the Sun JDK tools may be used to compile and execute a Java program, which is implemented as an applet (not a stand-alone application). Using an example, list the files that are provided by the programmer, and the files that are generated during the compile-execute process. Which files should be provided (on a Web server or elsewhere) to an end-user so that the user is able to run the applet? Assume the end-user does not have access to the JDK package.


The user supplies one or more Java source files. For example, assume we are defining a class called `MyApplet' in the file MyApplet.java. The javac program compiles this file. On the command line we would type `javac MyApplet.java'. The compiler would produce MyApplet.class. We then need to create an HTML file to be read by the applet viewer. The HTML file (let's call is MyApplet.html) need contain only one line, which provides the applet tag: <applet MyApplet width=... height=...></applet>. We can run the applet by executing `appletviewer MyApplet.html'. To run the applet, the end-user needs a Web browser, and access to the HTML file and the .class files produced by the compiler. Both the latter can be provided on a Web server.


C. A `just-in-time' (JIT) compiler for Java compiles Java `bytecode' (the output from the compiler) into native machine code, and then executes it. How does this improve the speed of execution compared to an `interpreting' run-time engine, while at the same time maintaining cross-platform compatibility without the need to distribute source code?


If a language is common across platforms at the source code level, then we can always get cross-platform compatibility by distributing source code and providing a compiler implementation for each platform. However, many developers will not want to distribute source code. The JIT compiler compiles the bytecode, which is platform independent. It does not compile the source code. There will be a time overhead for the JIT to work, but this only happens once per execution, unlike the interpreting run-time that is busy all the time.


Q4

(Mark weighting: section A - 30%; section B - 40%; section C - 20%; section D - 10%)


A. In programming, what are the meanings of syntax error, logical error, and exception? Gives examples in Java of each of these.


A syntax error is an error in the structure of the language; in Java it is sufficient to prevent the program compiling at all. For example, the lack of a semicolon between the two statements


x =1 y = 2


is a syntax error. A logical error is an error in the program's operation, usually resulting from a mistake or misunderstanding on the part of the programmer. The compiler cannot detect these, unless they are syntactically erroneous as well. For example, trying to get a loop to execute 5 times by saying


for (int i =0; i <= 5; i++)


is a logical error; this loop will execute 6 times.


An exception is any condition that arises abnormally, either as the result of an erroneous action by the user, or a system failure, or the consequences of an earlier logical error. For example, attempting to read from a file that does not exist is an exception, as is a division by zero. The former probably results from a user's mistake, the latter to an unnoticed earlier logical error.


B.

(i) What different styles of comment does Java support? What is a documentation comment? Why are comments, indentation and layout important in programming?


Java supports single-line comments, introduced by // and block comments, delimited by /* and */. A documentation comment is an extension to the block comment introduced by /**. This comment is used conventionally to signal a block of documentation that is to be extracted into a separate document. A number of software tools are available to do this, including the JDK `javadoc' utility.


(ii) Using whichever indentation convention you prefer, rewrite the following section of Java using indentation, so that the structure is clear (it is not important that the program does not do anything useful). Hence, or otherwise, detect and correct the syntax error in the code.


class X

{

int a;

public void Y()

{

for (int i = 0; i < 5; i++)

{

if (i == 2) Z(); else B(i);

}

}

}

a = 2;

}


There are many ways to lay out this code; an example is:


class X

{

int a;

public void Y()

{

for (int i = 0; i < 5; i++)

{

if (i == 2) Z();

else B(i);:w

}

}

// } extra brace here

a = 2;

}


In doing so the extra brace should be obvious.


C. In what ways is it suggested that the use of object-oriented development techniques may make it easy for the developers to handle logical errors and than might otherwise be the case?


Many programs are large and complex. The use of object orientation encourages the developers to manage this complexity by dividing the program into well-defined, self-contained classes. Of course, other development strategies are intended to manage complexity, but object orientation encourages the encapulation of information and instructions together, rather than independently. The implications are as follows. First, classes can be tested independently because their interfaces with the rest of the system are well defined. Secondly, errors are more easy to localize, as it should be relatively straightforward to isolate them to a single class. Thirdly, modications to the program are likely to lead to error, if they occur, that is limited to the class in which the modification is made. Fourthly, the self-contained nature of classes makes it easier to re-use sections of the program in later projects. If the classes that are reused are already debugged, the addition of new errors to the new project is less likely. Blah, blah...


D. In the Java example in section C, before the syntax error, an attempt to compile the code would produce an error message of the form `class or interface declaration expected' on the line ``a = 2''. What does this error message mean, and why has it arisen?


In Java, all program statements must be inside classes or interfaces (with the exception of `import'). So the error message means that a statement has been encountered outside a class. The compiler matches the extra brace to the opening brace of the declaration of class X. This means that the statement ``a = 2'' appears to be outside a class.


Q5.

(Mark weighting: section A - 40%; section B - 40%; section C - 20%)


A.

(i) Explain why the following piece of Java, which attempts to calculate `5 divided by 2', gives the `wrong' answer (that is, it displays `2' and not `2.5').


int result = 5 / 2;

System.out.println(result);


The use of an integer to store the result of a calculation with a fractional part, and the fractional part is of interest, is clearly inappropriate. Whatever the result of the division 5 / 2, assigning that result to an integer variable will lose the fractional part.


(ii) Explain why the following piece of Java does not solve the problem described in part (i).


double result = 5 / 2;

System.out.println(result);


The Java compiler treats the two sides of the equals sign separately. The right hand side is an integer division, because 5 and 2 are both assumed to be integers. The left hand side is a double, but this does not help because the division is carried out as integers, and the integer result assigned to the double.


(iii) Suggest a simple modification that would cause the program to calculate and display the result correctly


double result = 5.0 / 2.0;


(iv) Not all programming languages would give the `wrong' answer in situations like the above; why might the Java designers have made the assumptions that they did that lead to this problem?


A pragmatic answer to this question is that Java assumes that numbers with no fractional componets are integers because C++ does because C did. Another possibility is that most numbers used in a computer program are, indeed, integers, so clarity is improved if the programmer does not have to use a symbol to indicate that a number is an integer. Another possibility is that integer arithmetic is very much faster than floating-point arithmetic.


B.

(i) Illustrate three loop constructs available to the Java programmer, by showing how each can be used to add the numbers from 1 to 10.


`while':


int total = 0, i = 0;

while (i <= 10)

{

total += i;

i++;

}


`do...while':


int total = 0, i = 0;

do

{

total += i;

i++;

} while (i <= 10);


`for':


int total;

for (int i = 0; i <= 10; i++)

total += i;


(ii) In theory, one loop construct can do the work of any of the others. Why does Java provide a number of different looping mechanisms?


Although the constructs are theoretically equivalent, they express themselves in slightly different ways. For example, the `for' loop defines in its first statement the starting and ending conditions of the loop. This makes it very expressive for loops that have a fixed number of repetitions. The `while' constructs, however, are more expressive when the number of repetitions is variable, or not dictated by simple arithmetic. The `do...while' loop indicates that the loop body will be executed at least once. All these things, if used correctly, make a program easier to read.


C. In Java, what are the differences between a String, a StringBuffer, and an array of characters?


A string is an immutable object that represents a sequence of characters. Strings can be concatenated and have substrings extracted, but the contents of the particular string are never changed after its creation. A StringBuffer is a mutable string; its contents can be re-written. Neither a string not a StringBuffer can be addressed at the character level. An array of characters is a first-class language construct, not an object of a class. It can be addressed at the character level, but operations like concatenation are not defined on arrays. Java provides methods to convert between these different representations of text strings.