CIS 121 - Problem-solving and Programming Concepts II - DOC by ygq15756


									             CIS 121 - Problem-solving and Programming Concepts II
                        Practice Test II (Chapters 14 – 16)

Part I: Fill-in-the-blank.
   1. A(n) ____EXCEPTION__________ is an object and an indication that a problem, such as
      division by zero, occurred during a program's execution.

   2. A(n) ____DAEMON____________ thread is a thread that runs for the benefit of other
      threads, such as java's garbage collection.

   3. The code that controls a user-defined thread is placed in the _____RUN__________ method
      that comes from the ______THREAD class or the ______RUNNABLE______ interface.

   4. The capability of portions of a program to run concurrently is called

   5. A thread is launched by calling the thread's _______START____ method that in turn calls
      the ____RUN_______ method.

   6. Every Java thread has a priority in the range of ____MIN_PRIORITY_________ to
      _____MAX_PRIORITY_____ with an int value of _1___ to __10_. The default property is
      ___NORM_PRIORITY___________ with an int value of _5___.

   7. The Exception and Error classes inherit from the __THROWABLE____ class.

   8. Explain why exception handling is an effective means for handling with constructor failure.

   9. A _ARITHMETIC EXCEPTION___ exception normally occurs when we divide by zero.
      (Use the most specific instance)

   10. Problems that occur when we try to open files are _IOEXCEPTIONS____________

   11. A ___NULLPOINTEREXCEPTION___ is generated when we try to make a reference to an
       instance variable, method, or field with a null object reference.

   12. In order to write objects to a file using ObjectOutputStream, the
       ___SERIALIZABLE_______________________ interface must be implemented.

   13. According to the Data Hierarchy, a ___FILE____________________ is a group of related

   14. _RANDOM ACCESS _____ files are used for applications where “Instant Access” to the
       data is needed, such as an ATM machine.

Part II. Short answers.
   1. Describe how exception handling works. Make sure to include keywords try, catch, finally,
      throw, and throws.

Exception handling allows for clear, robust, more fault-tolerant programs. It is used for situations
from which the program should be able to recover.

Exceptions can be either thrown by a method or handled using try catch blocks. To throw an
exception you would use the keyword THROWS in the method header to indicate that the
exception will not be handled by this method and that any exceptions that occur will be thrown
back to the calling method to be handled. These exceptions can continue to be thrown back to
calling method until it reaches the interpreter which will ultimately handle the exception. To
handle an exception using a try-catch block, the programmer would put all code that could throw
and exception into a try block. Catch blocks would then be created to handle the possible
exceptions that the method will “catch” and handle. The exception handling code will be contained
in the catch blocks. Finally blocks can be added to include any code that should run regardless of
an exception being thrown. This would include closing files and releasing system resources.
Exceptions can be caused by using the keyword THROW to create an exception object.

   2. Explain three exception handling alternatives.

a) Throws Clause in the method header – return the exception to the calling method to deal with
the exception

b) Catch and Handle – Use a try-catch block in the method to catch any exceptions that might

c) Rethrow the exception – When a handler finds out it cannot properly handle the exception it
may want to throw the exception to the next catch block. This uses the keyword throw.

   3. Explain the concept of checked versus unchecked exceptions.

Checked Exceptions – These are situations that need to be handled or included in a throws clause in
the method header. These are non-Run Time exceptions such as IOExceptions.

Unchecked Exceptions – Are Run Time exceptions that should be avoided through the use of
proper coding. Examples of run time exceptions are arrayOutOfBoundsException and
NullPointerExcepton. They do not need to be included in a throws clause.

   4. List five examples of exceptions.






5. Discuss two model of exception handling. Which one does Java use?



6. Write the code that defines the class for a user defined exception, called

   public class DivideByZeroException extends Exception {

   public DivideByZeroException () {

           super (“Divide by Zero”)


   public DivideByZeroException (string message) {

           super (message);


7. Write a try-catch for handling a divide-by-zero exception.

try {

    if (count == 0)

           throw new DivideByZeroException();


           x = sum / count


catch (DivideByZeroException dbze) {

    count = 1;


8. What kind of code might go into a finally block?

Release resources –

1) Close Files

2) Destroy Objects created in an interrupted constructor

9. Briefly describe the life cycle of a thread. Explain what happens in each state. Use a

   Born – Thread had been created

   Ready – After start has been called, waiting for the processor, based on priority

   Running – The system assigns the thread to the processor and it begins executing

   Waiting - Waiting for an object then moves to ready

   Sleeping – Thread gives up processor for a specified amount of time

   Blocked – Waiting, cannot continue executing (I/O request, etc)

   Dead – Run completes or terminates (uncaught exception)

   (Diagram in book on page 842)

10. Why do some threads need to be synchronized?

Sharing of data. To ensure that the threads are running in the proper order. If multiple threads
are sharing processor time they may access the same object, the same memory location, at the
“wrong time” for the program. For example: an output message may be read in before the
correct message is sent out by the first thread. This can cause corrupt data where data may be
either lost or read in multiple times.

11. Briefly describe the purpose of a monitor.

Every object that has a synchronized method has a monitor. It is the job of the monitor to allow
only one thread at a time to execute a synchronized method on the object.

12. Briefly describe the producer/consumer relationship with thread synchronization.

The producer is writing data, the consumer is reading the data

Synchronization is needed to ensure the integrity of the shared data space. This will make sure
that all of the data written by the producer is read in by the consumer and that it is only read

13. Explain why a Runnable interface might be needed instead of extending the Thread class.

This allows for a class to have concurrent threads while extending another class, based on
Java’s single inheritance.

14. Explain the steps necessary to write to a sequential file using ObjectOutputStream.

a) Implement the serializable interface for the object class

b) Create an object of ObjectOutputStream

c) Call the constructor for ObjectOutputStream – this requires the creation of a
FileOutputStream which takes in a string file name as a parameter. This creates the connection
between the file and the program and opens the file.

d) Write the object to the file using the writeObject method from ObjectOutputStream.

e) Flush the buffer

f) Close the Output file

15.What do we do with String data when we are working with Random Access Files?

   String data must be changed into a fixed length object of a primitive data type to be used
   with Random Access Files. This can be accomplished by using an Array of char or by
   using a StringBuffer class.

III. Programming and Discussion.

1.       Write a program that reads a file with two integers on each line, tokenizes it and divides the
         first number by the second number. Write the code needed to handle invalid numbers, file
         not found, and divide by zero exceptions. Use good coding standards, good variable names
         and comments.


import    java.util.*;
import    java.awt.*;
import    java.awt.event.*;
import    javax.swing.*;

public class PracticeTest2 {

     public static void main (String args[]) {
         String aLine;
         String aNumber;
         int     num1;
         int     num2;
         float   dividend;

           try {
               FileReader aFile = new FileReader ("a:\\numbers.txt");
               BufferedReader inputFile = new BufferedReader (aFile);

            aLine = inputFile.readLine();
            while (aLine != null) {
                StringTokenizer parser = new StringTokenizer (aLine);
                num1 = Integer.parseInt(parser.nextToken());
                num2 = Integer.parseInt(parser.nextToken());
                dividend = (num1 / (float)num2);
                //catch Arithmatic exception here or put in a divident method
                //to THROW a divide by zero exception
                // divident = quotient (num1, num2);
                aLine = inputFile.readLine();
               JOptionPane.showMessageDialog (null,"The Dividend = " + dividend,
                    "The Quotient of 2 Numbers",
            } // end while
       } // end try

          catch (NumberFormatException NFE) {
               JOptionPane.showMessageDialog (null, "This is Not an Integer",
                   "Invalid Number Format", JOptionPane.ERROR_MESSAGE);
          catch (IOException IOE) {
              JOptionPane.showMessageDialog (null, "There is an error with the
                     file", "Invalid File", JOptionPane.ERROR_MESSAGE);

         catch (ArithmeticException AE) {
             JOptionPane.showMessageDialog (null, "Divide by Zero Exception",
                  "Divide By Zero Problem", JOptionPane.ERROR_MESSAGE);

//        this method requires a divide by zero exception class to be created
//        public float quotient (int numerator, int demoninator) throws
//               DivideByZeroException) {
//          if (denominator == 0)
//              throw new DivideByZeroException();
//         return (float) numerator / demoninator
//         } // end quotient

2. Read the following program and answer the questions.
   A, Individually identify at which point in the code that the blueBall thread is (1) born, (2)
      ready, and (3) running. (Look in code)
   B. Explain what is being accomplished in the mousePressed method.
      The mousePressed event gets the x and y coordinates for the bal, creates the blueBall
      thread, sets the bouncing boolean true, and calls the start method for the thread (which will
      call run)
   C. Briefly describe how this program be modified to allow for multiple bouncing balls?
      You can create multiple bouncing balls by creating multiple instances of the ball thread.
      This can be accomplished in an array of balls. Each ball will maintain it’s own thread, with
      it’s own run, start, sleep, etc. methods.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Ball extends JApplet
      implements Runnable, MouseListener {
  private Thread blueBall;
  private boolean xUp, yUp, bouncing;
  private int x, y, xDx, yDy;

 public void init()
   xUp = false;
   yUp = false;
   xDx = 1;
   yDy = 1;
   addMouseListener( this );
   bouncing = false;

 public void mousePressed( MouseEvent e )
   if ( blueBall == null ) {
      x = e.getX();
      y = e.getY();
      blueBall = new Thread( this );      Blue Ball is born (1)
      bouncing = true;
      blueBall.start();                   Blue Ball is Ready (2)

 public void stop()

    if ( blueBall != null )
       blueBall = null;

public void paint( Graphics g )
  super.paint( g );

    if ( bouncing ) {
       g.setColor( );
       g.fillOval( x, y, 10, 10 );

public void run()                       Blue ball is running (3)
  while ( true ) {

      try {
        blueBall.sleep( 100 );
      catch ( Exception e ) {
        System.err.println( "Exception: " + e.toString() );

      if ( xUp == true )
         x += xDx;
         x -= xDx;

      if ( yUp == true )
         y += yDy;
         y -= yDy;

      if ( y <= 0 ) {
         yUp = true;
         yDy = ( int ) ( Math.random() * 5 + 2 );
      else if ( y >= 190 ) {
         yUp = false;

      if ( x <= 0 ) {

              xUp = true;
              xDx = ( int ) ( Math.random() * 5 + 2 );
            else if ( x >= 190 ) {
              xUp = false;


    public void mouseExited( MouseEvent e ) {}
    public void mouseClicked( MouseEvent e ) {}
    public void mouseReleased( MouseEvent e ) {}
    public void mouseEntered( MouseEvent e ) {}

3.       Enhance the following method to implement exception handling for the

  // Original version without exception handling.
  public void actionPerformed( ActionEvent e )
     DecimalFormat precision3 = new DecimalFormat( "0.000" );
     output.setText( "" ); // empty the output JTextField
     number1 = Integer.parseInt( input1.getText() );
     number2 = Integer.parseInt( input2.getText() );

      result = quotient( number1, number2 );
      output.setText( precision3.format( result ) );

  // Your modified code with exception handling.
  public void actionPerformed( ActionEvent e )
     DecimalFormat precision3 = new DecimalFormat( "0.000" );
     output.setText( "" ); // empty the output JTextField
try {
            number1 = Integer.parseInt( input1.getText() );
            number2 = Integer.parseInt( input2.getText() );

catch (NumberFormatException nfe) {
       System.err.printLn (“Please enter 2 numbers”);

      result = quotient( number1, number2 );               These lines could go in the
      output.setText( precision3.format( result ) );       try/catch because they could cause
                                                          a divide by zero exception

4. Fill in the blanks for the following methods:

  public void writeRecord( PineTreeData record )
  {                   // Writes record as an object.
   try {

          outputFile._writeObject (record)_______;     // Write record.

      catch ( IOException io ) {
        JOptionPane.showMessageDialog( this, "Error adding record",
              "Error", JOptionPane.ERROR_MESSAGE );

  private void closeInputFile( )
     try {
        inputFile._close_____( );

      catch ( _IOException e______ ) {
        JOptionPane.showMessageDialog( this, "Error closing input file",
              "Error", JOptionPane.ERROR_MESSAGE );


Method/Class List
          a.   Throwable Class
          b.   Exception Class
          c.   PrintStackTrace
          d.   Thread class
          e.   Run
          f.   Start
          g.   Sleep
          h.   Runnable Interface
          i.   FileInputSream Class
          j.   FileOutputSream Class
          k.   ObjectInputSream Class
          l.   ObjectInputSream Class
          m.   Serializable Interface

     a.   Exception
     b.   Error
     c.   Resource leak
     d.   try block
     e.   catch block
     f.   finally block
     g.   throw
     h.   throws
     i.   concurrency
     j.   starvation
     k.   deadlock
     l.   Producer/Consumer relationship
     m.   synchronization
     n.   monitor
     o.   priority concurrency management
     p.   time slice concurrency
     q.   thread state
     r.   termination model of exception
     s.   resumption model of exception
     t.   Sequential Access Files
     u.   Random Access Files


To top