Sample Exam Questions

Introduction

1.      [4 marks]  Write a complete Java program to print the message “Hello, world!” on the console.

2.      [5 marks]  Write the content of a Java main function that declares a single-precision floating-point constant for the radius of a circle equal to 7.3 and then displays on the console “The area of the circle is ” and the area of the corresponding circle.  The formula for calculating the area of a circle is πr2.

3.      [5 marks]  List 5 Java numeric data types and give their approximate ranges.

4.      [3 marks]  Write a program fragment that declares two string variables, assigns “Pizza” to the first one and “tonight!” to the second one, and displays the concatenation of them on the console to give “Pizza tonight!”.

5.      [8 marks]  Write a complete Java program that prompts the user for two numbers n and m, reads them in, and displays the value of nm on the console.

6.      [10 marks]  Write a complete Java program that corresponds closely to the following C++ program.

 

#include <iostream>

using namespace std;

 

int main()

{

      const int MAX_SIZE = 1024;

      int numbers[MAX_SIZE];

      int numberCount = 0;

      bool notDoneYet = true;

 

      cout << "Enter the numbers to read, one per line, ending with 0.";

      cout << endl;

 

      while (notDoneYet)

      {

            cin >> numbers[numberCount];

 

            if (numbers[numberCount] == 0)

                  notDoneYet = false;

            else

                  numberCount++;

      }

 

      cout << "Numbers in reverse order:" << endl;

 

      for (int i = numberCount - 1; i >= 0; i--)

            cout << numbers[i] << endl;

 

      return 0;

}

 

7.      [4 marks]  Briefly explain what a Java package is and gives the commands to compile several Java files in the same package into a single .jar file on hercules.

 

Applets

8.      [2 marks]  What is an applet?

9.      [6 marks]  Write a complete Java applet that displays the string “Hello, world!” in green letters on a web page.  You will need a paint function and you will need to make use of the drawString function.

10.  [2 marks]  Explain in general terms how an applet can be added to a web page such that the applet is run when the web page is loaded into a web browser.

11.  [3 marks]  List three advantages of using .jar files.

12.  [6 marks]  Write a fragment of a paint function that displays a filled yellow rectangle that is 40 pixels high and 20 pixels wide at location (200, 400).

13.  [6 marks]  Write a fragment of a paint function that displays a hollow orange oval such the smallest enclosing rectangle is 20 pixels high and 50 pixels wide with its upper left corner at (300, 400).

THE NEXT TWO QUESTIONS ARE ALSO 2D ARRAY QUESTIONS

14.  [10 marks]  Suppose that a getImage function is available that takes a string representing the filename as a parameter and returns an Image.  Give a code fragment to read image files called image00.gif, image01.gif, …, image49.gif and store them in a 5x10 2D array such that the first 10 images are stored in the first row of the array, etc.

15.  [15 marks]  Suppose that a 5x10 2D array of Images has been loaded.  Each image is 20x20 pixels in size.  Give code for a paint function that displays the images arranged in 5 rows and 10 columns.  The images should be displayed with no spaces between them, such that the upper left corner is at (20, 30) on the screen.

Classes

16.  [15 marks]  Write a Java class called Book.

a.        [3 marks] There should be data fields for the author, title, and number of pages.  These data fields should be hidden from all other parts of the program. 

b.      [3 marks] Provide a default constructor that sets both the author and title to “Unknown” and the number of pages to 100. 

c.       [3 marks] Provide an initializing constructor that takes an author, title, and number of pages as parameters and constructs an instance of the Book class. 

d.      [3 marks] Provide a display function that prints the author, title, and number of pages to the console.  This function should be available to all other parts of the program.

e.       [3 marks] Write a Java program fragment that creates two instances of the Book class, called book1 and book2, such that the first has the default information and the second corresponds to “Data Structures” by “Connie Smith”, which has 488 pages.

17.  [2 marks]  If book1 and book2 are two instances of a Java class called Book, what effect does the following statement have:
        book1 = book2; .

18.  [4 marks]  With reference to Java, what is garbage collection and when is it performed?

19.  [4 marks] Which access specifier (public, private, (default), protected) should be chosen:

1.      [1 mark] For a class that should be visible only in the same package.

2.      [1 mark] For a function that should be visible in its class, in its package and in any class that extends its class.

3.      [1 mark] For a class that should be visible throughout the program.

4.      [1 mark] For a function that should be visible in its package but not elsewhere.

Arrays

SEE THE APPLETS SECTION FOR TWO QUESTIONS

20.  [10 marks]  Write a complete Java program that reads the number of rows R and number of columns C from the console and then reads RxC integers from input and stores them in a 2D array that is RxC in size.  The program should then ask the user for a column number and then display the values from only that column, one per line.

21.  [8 marks]  Write a complete Java class called Triangle.  Its default constructor should create a jagged array and store random numbers in it with 2 entries in the first row, 4 in the second row, and so on until 100 entries in the 50th row.

Widgets

22.  [8 marks]  Write a complete Java program to display a small message box.  The message box should have the words “My Message” in the title bar, an ‘i’ in a circle icon, a message that says “This is my message”, and an OK button.  Put in any code necessary to include required libraries.

23.  [8 marks]  Write a fragment of a Java program that displays an input dialog box.  The dialog box should have the word “Input” in the title bar, a ‘?’ in a square icon, a message that says “Enter number of years:”, a text field for entering a numeric value, and an OK button and a cancel button.  Put in any code necessary to include required libraries.

24.  [5 marks] Explain the purpose of each of the following Java functions:

setLayout(null);

getContentPane().add(my_widget);

my_widget.setBounds(x, y, width, height);

my_widget.setLocation(x, y);

my_widget.setSize(width, height);

25.  [10 marks] Explain with code segments how you can display a text field that is 50 pixels wide, 30 pixels high, and position it at location (300, 400) on the screen.

26.  [10 marks] Explain with code segments how your Java program can retrieve a numeric value from the text field described in the previous question and use it to change the value of the mooseCount variable.

27.  [10 marks] Explain, using the terms event, event listener, and event handler, how a program can respond to a mouse click on an OK button by setting a variable entryCount to 0.

28.  [8 marks] Explain the purpose of the following code and how it accomplishes this purpose by referring to every variable, function, and class/interface.

myButton.addActionListener(

     new ActionListener() {

          public void actionPerformed(ActionEvent evt)

              { myButtonAction(); }});

 

Threads

29.  [6 marks] Describe two methods of providing a separate thread of execution in Java.  What is the main difference?  Where does the run function come from in each case?

30.  [10 marks] Write Java code to create a thread of execution that repeatedly performs two actions for 10 minutes: (1) prints the time on the console and (2) sleeps for 5 seconds.  Assume that you can obtain the current time with: (new Date()).getTime().

ANOTHER QUESTION IS GIVEN WITH IMAGES

Object Oriented Programming

  1. [8 marks] Suppose that we want to design an abstract class called Dinosaur and two non-abstract subclasses called TRex and Brontosaurus.  Dinosaur has an abstract function called getBiteSize that returns the crunch-power of the bite of a dinosaur, where a TRex has 200 crunch-power and a Brontosaurus has 50 crunch-power.  Dinosaur also has a non-abstract function called isTerrifying that yields true if the crunch-power of a dinosaur is more than 100.
  2. [8 marks] Redo question (1) immediately above using an interface.
  3. [6 marks] Explain the difference between composition and inheritance with respect to forming new classes from existing classes.  Use an example as part of your answer.
  4. [20 marks] Classes:

a)      Design an abstract class called Food with MainCourse, Dessert and Beverage subclasses, each with (1) a string variable to represent their data, (2) an initializing constructor, and (3) a print function that prints the name of the subclass followed by its value, such as “Main Course: pasta”.  Encapsulate all data.

b)      Using your results from part (a), design a class called Meal, where a Meal consists of a MainCourse, a Dessert, and a Beverage.  Give an initializing constructor and a print function for the Meal class.

Exceptions

  1. [2x5=10 marks] Exceptions:

a.       Write a complete public Java function called makeCandy with a single String variable called candyType that throws an IllegalArgumentException if the value of candyType is not “Jaw Breaker”,Lollipop”, or “Toffee”.  Otherwise, it simply prints the word “Make” followed by the type of candy.

b.      Show how the makeCandy function can be called on a string variable called candyToMake.  If an exception occurs, show a message dialog box explaining the problem to the user.

  1. [2x3=6 marks] Describe three reasons, each with an example, of why a function might explicitly throw an exception using the throw keyword.
  2. [5 marks] Explain with an example why we might write several different catch statements after a single try statement.

Program Organization

  1. [5 marks] Explain how to specify an Abstract Data Type for a Counter class in Java or give Java code to do so.
  2. [5 marks] Define defensive programming.  Describe Java language constructs that allow defensive programming to be implemented.
  3. [5 marks] Define design-by-contract.  Describe Java language constructs that allow the design-by-contract methodology to be implemented.
  4. [6 marks] Given the following Java function, show how to add comments that will allow documentation in the javadocs format to be generated.  Specify that this function has been present since version 2.0 of the Cylinder class.

public static double getCylinderVolume

                        (double radius, double height)

                        throws IllegalArgumentException

{

     if(radius < 0)

          throw new IllegalArgumentException

                        (“Radius must be non-negative”);

 

     double area = radius * radius * Math.PI;

     return area * height;
}

 

  1. [6 marks] Given the following Java class, show how to add comments that will allow documentation in the javadocs format to be generated for the class.  Specify your name as the programmer and the version as 3.1.

public class Cylinder

{

     private double radius;

     private double height;

 

     public static double getCylinderVolume

                        (double radius, double height)

                        throws IllegalArgumentException

     { same as above }

}

 

  1. [2 marks] Where should a comment be inserted that describes a package so that it will be available in javadocs format?
  2. [2x2=4 marks] Suppose the following statement is inserted in a Java program:

assert length > 0;

    1. What is the intended effect of inserting the statement?
    2. Describe two circumstances under which the statement will have no noticeable effect on execution?

Files

  1. [10 marks] Write a complete Java program (rather than an applet) that reads in a text file called input.txt, removes all non-letters, converts all letters to lowercase, and writes the result to a text file called output.txt.  Assume a Boolean function called Character.isLetter(char c) is available that yields true if a particular character is a letter and false otherwise.
  2. [12 marks] Suppose that we have a non-serializable class called Mine that includes three fields: an integer array called x that contains 50 integer values, a float called y, and a char called z.  Explain with sample code how the values in an instance (called myMine) of this class could be stored in a binary file called Mine1.dat.
  3. [8 marks] Suppose that we have a serializable class called Mine that includes three fields: an integer array called x that contains 50 integer values, a float called y, and a char called z.  Explain with sample code how the values in an instance (called myMine) of this class could be stored in a binary file called Mine2.dat.
  4. [10 marks] Suppose a class has three string variables called name, address, and phoneNumber and they have been set to default values.  A text file called config.txt may contain values for these variables.  If a line begins with “Name:” the remainder of the line gives a new value for the name variable, and similarly for “Address:” (gives the address), and “Phone Number:” (gives the phone number).  These lines may appear in any order.  Give a function suitable for a Java program (not an applet) that reads the file and updates any of these variables according to the values given in the file.
  5. [5 marks] Compare and contrast the methods required in a Java applet to read a file from the web server versus from the machine where the browser is running.
  6. [6 marks] Explain why an applet might be signed and explain in detail how this is done.

Images and Audio

  1. Design a Java applet that will allow the user to choose an image file, such as a .JPG, .GIF, or .PNG file, and then create a new image with a copy of the image with a black circle of radius 100 drawn over top it.  (For the purpose of this question, you do not have to display or save the modified image.)

THE NEXT QUESTION ALSO APPLIES TO THREADS

  1. Explain how to write a Java applet (or give the code for it) that displays an animation of a green circle (radius 20) revolving around a large yellow circle (radius 200). Mention what goes in each of the start, stop, run, and paint functions.
  2.  Create a FlashImageFilter class as a subclass of RGBImageFilter.  This filter should fade an image towards white by an amount based on an argument passed to the constructor.  This argument should be a floating-point value in the range [0, 1], where 0 indicates the image should be identical to the original and 1 indicates the image should be completely white.  The transparency of the pixels should always be the same as in the original image.  For example, if the constructor argument is 0.5 and the initial pixel is dark blue (0, 0, 127), the new pixel should have each component adjusted by half (0.5) of the difference between itself and white (255, 255, 255) to give a light grey-blue (127, 127, 191).

Ø      Remember: You will need to override the filterRGB function from the RGBImageFilter class
public int filterRGB (int x, int y, int pixel)
{
     int newPixel;
     ...
     return newPixel;
}

Ø      Hint: You should handle each of the RGB components separately.

Ø      Hint: You can find the new red component with
red = pix & 0x000000FF;
red += (int)((0x000000FF - red)*fraction) & 0x000000FF;

  1. Write a Java function named createFlashArray that, given an initial Image named original, returns a new array of Images created with the FlashImageFilter.  The Images produced should be evenly distributed between unmodified and pure white, including a pure white Image but not an entirely unmodified Image.  The pure white Image should have the largest index.  For example, if there were five Images in the array, their constructors should be passed values of 0.2, 0.4, 0.6, 0.8, and 1.0.  The number of elements in the array should be passed as a parameter to the createFlashArray function.
  2. Suppose you had a class called Game that played a simple interactive game from an applet.  Explain how to do the following:

a)      Load a looping sound file containing your music in your Game class.

Ø      Note: The AudioClip class is in the java.applet package and can be loaded with the static Applet.newAudioClip function.

b)      Start the music playing in the start function of your Game class.

c)      Stop the music playing in the stop function of your Game class.

d)      Ensure the music is stopped when the user leaves the web page containing the applet.

 

 

Terminology

31.  [nx1 marks]  Define the following terms.

·         bytecode

·        Java Virtual Machine

·        Java Runtime Environment

·        package

·        applet

·        client computer

·        server computer

·        HTML

·        HTML tag

·        class

·        instance (of a class)

·        object

·        instance variable

·        method

·        constructor

·        reference variable

·        garbage collection

·        access modifiers

·        subclass

·        dialog

·        dialog icon

·        widget

·        event-driven programming

·        event

·        event listener

·        event handler

·        registering an event

·        triggering an event

·        listener method

·        secondary event handler

·        thread

·        program counter

·        synchronized threads

·        monitor

·        lock

·        statement-level lock

·        function-level lock

·        structured programming

·        object oriented programming

·        test-driven development

·        test case

·        regression testing

·        principle of information hiding

·        data abstraction

·        composition

·        inheritance

·        dynamic binding

·        parent class / superclass

·        child class / subclass

·        implementation inheritance / strong inheritance

·        interface inheritance / weak inheritance

·        overriding a function

·        overloading a function

·        pure interface inheritance

·        impure interface inheritance

·        declared type

·        subtype

·        supertype

·        polymorphism

·        dynamic binding

·        static binding

·        polymorphic function

·        type casting

·        upcasting

·        downcasting

·        implicit casting

·        explicit casting

·        exception

·        abstract data type

·        abstract operation

·        functional interface

·        data encapsulation

·        defensive programming

·        design by contract

·        error detection

·        error correction

·        javadoc

·        javadoc format

·        assertion

·        file I/O

·        text file

·        binary file

·        sequential file

·        random access file

·        overwriting a file

·        appending to a file

·        stream

·        serialized class

·        server file

·        client file

·        unsigned applet

·        signed applet

·        digital signature

·        double buffering

·        hexadecimal

·        bitwise operation

·        image filter

·        sound

·        amplitude

·        oscillate

·        wave cycle

·        frequency

·        hertz

·        pitch

·        digital audio

·        sample (2 related meanings)

·        sample rate

·        bit depth

·        MIDI

·        sampled audio

·        audio clip