Questions: Java Programming

By David R. Tribble
Revision 1.2, 2003-05-07


The following questions are designed to test your knowledge of Java programming.

Note that some of the code has been simplified, omitting extraneous statements, import directives, etc., which would otherwise clutter the examples.

  1. Show four ways the class below can be changed so that other classes cannot extend it.
     1: public class MineAlone
     2: {
     3:     protected int   m_val;
     4:
     5:     public MineAlone()
     6:     {
     7:     }
     8:
     9:     public MineAlone(int n)
    10:     {
    11:         m_val = n;
    12:     }
    13: }
    

  2. Java strings (i.e., objects of type String) are immutable. What does this mean?

  3. a) What makes the class below mutable?

    b) How can the class be made immutable?

     1: class Frob
     2: {
     3:     private Date    m_time;
     4:
     5:     public Frob(Date d)
     6:     {
     7:         m_time = d;
     8:     }
     9:
    10:     public Date getTime()
    11:     {
    12:         return (m_time);
    13:     }
    14:
    15:     public void setTime(Date d)
    16:     {
    17:         m_time = d;
    18:     }
    19: }
    

  4. a) What effect does declaring a variable volatile have?

    b) When should a variable be declared volatile?

    c) What would happen if all the member variables in a program were declared volatile?

  5. How can the code below be improved?
     1: class Log
     2: {
     3:     /** Error messages. */
     4:     private static String[]     MESSAGES =
     5:     {
     6:         new String("Okay"),
     7:         new String("Write error"),
     8:         new String("Read error"),
     9:         new String("Unknown I/O error"),
    10:         ...
    11:     };
    12:
    13:     public static String formatMessage(int msgno, int a)
    14:     {
    15:         StringBuffer    buf;
    16:
    17:         // Format a log message
    18:         buf = new StringBuffer();
    19:         buf.append(MESSAGES[msgno]);
    20:         buf.append(": ");
    21:         buf.append((new Integer(a)).toString());
    22:         return (buf.toString());
    23:     }
    24: }
    

  6. Describe how each of the standard classes below is related to the others.
        Error
        Exception
        NullPointerException
        RuntimeException
        Throwable
    

  7. How can the code below be improved?
     1: try
     2: {
     3:     item.process();
     4: }
     5: catch (Exception ex)
     6: {
     7:     if (ex instanceof ItemException)
     8:         throw (ItemException) ex;
     9:     else
    10:         throw ex;
    11: }
    

  8. The following code fails to compile. Why?
     1: class GetterBase
     2: {
     3:     public int getNext()
     4:         throws Exception
     5:     {
     6:         ...code omitted for brevity...
     7:     }
     8:
     9:     ...code omitted for brevity...
    10: }
    11:
    12: public class Getter
    13:     extends GetterBase
    14: {
    15:     public int getNext()
    16:     {
    17:         ...code omitted for brevity...
    18:     }
    19:
    20:     public static void main(String[] args)
    21:     {
    22:         Getterbase  rd;
    23:
    24:         rd = new Getter();
    25:         rd.getNext();
    26:         System.exit(0);
    27:     }
    28: }
    

  9. a) What is the difference between a checked exception and an unchecked exception?

    b) How is a class defined as being an unchecked exception type?

  10. Consider the code fragment below. On a typical JVM implementation, the resulting Byte object array bobj uses about 16 times as much memory space as the byte array barr. Why?
     1: byte[]  barr;
     2: Byte[]  bobj;
     3:
     4: // Allocate an array of bytes
     5: barr = new byte[n];
     6:
     7: // Allocate an array of Byte objects
     8: bobj = new Byte[n];
     9: for (int i = 0;  i < n;  i++)
    10:     bobj[i] = new Byte(0);
    

  11. A typical JVM implementation allocates a minimum of 20 bytes of storage for a String object, even if it is empty (""). Why?

  12. a) What must be done to rewrite the following class as an interface?

    b) Why would you want to rewrite a class as an interface?

     1: public class Sale
     2: {
     3:     private String      m_vendor;
     4:     private Item[]      m_items;
     5:
     6:     public Sale(String vendor, Item[] items)
     7:     {
     8:         m_vendor = vendor;
     9:         m_items =  items;
    10:     }
    11:
    12:     public int numItems()
    13:     {
    14:         return (m_items.length);
    15:     }
    16:
    17:     public Item getItem(int n)
    18:     {
    19:         return (m_items[n]);
    20:     }
    21:
    22:     public String getVendor()
    23:     {
    24:         return (m_vendor);
    25:     }
    26:
    27:     private void clearItems()
    28:     {
    29:         for (int i = 0;  i < m_items.length;  i++)
    30:             m_items[i] = null;
    31:     }
    32: }
    

  13. The standard Java library provides interface Runnable and class Thread. Given that class Thread implements the Runnable interface, why would you ever need to implement Runnable instead of just extending class Thread?

  14. Find and fix the bugs in this code.
     1: int computeTaxFor(Person pers)
     2: {
     3:     // Exempt people under 18 and over 65 years old
     4:     if (pers.m_age < 18  &&  pers.m_age > 65)
     5:         return (0);
     6:     // Exempt blind people and handicapped people
     7:     if (pers.m_blind  &&  pers.m_handicapped)
     8:         return (0);
     9:     // Otherwise, apply the basic tax rules
    10:     return (pers.m_income * pers.getTaxRate());
    11: }
    

  15. Find and fix the bugs in this code.
     1: int findSentinel(byte[] b)
     2: {
     3:     // Scan the array until a '0xFF' byte is found
     4:     if (b == null)
     5:         return (-1);
     6:     for (int i = 0;  i < b.length;  i++)
     7:         if (b[i] == 0xFF)
     8:             return (i);
     9:     return (-1);
    10: }
    

  16. a) A program requires a main thread to create and execute several children threads, then wait until all of the children threads complete their tasks. How does this kind of program accomplish this?

    b) What are the two standard library methods used to allow the main parent thread to synchronize with and communicate with all of its children threads?

    c) How are these two methods used?

  17. Consider the execution of the method below.

    a) What happens when method accessItem() throws an ItemException?

    b) What happens when method accessItem() throws an ArrayIndexOutOfBoundsException?

    c) What happens when method accessItem() causes a NoClassDefFoundError to be thrown because the Item class (or some other class it refers to) could not be loaded from the CLASSPATH?

    d) How can this code be improved?

     1: String getName(int n)
     2:     throws NameException
     3: {
     4:     String  id = "unknown";
     5:     int     rc = 0;
     6:
     7:     try
     8:     {
     9:         rc = m_item.accessItem(n);      // May throw
    10:         id = m_item.getItemName(n);
    11:         return (id);
    12:     }
    13:     catch (ItemException ex)
    14:     {
    15:         if (rc != 0)
    16:             throw new NameException(ex.getMessage());
    17:         return (null);
    18:     }
    19:     finally
    20:     {
    21:         if (rc != 0)
    22:             throw new NameException("Fail: " + n);
    23:         return (id);
    24:     }
    25: }
    

  18. Show how class Abc can insure that class Xyz gets loaded by the JVM class loader.

  19. A given piece of code was changed from this:
     1: public class Driver
     2: {
     3:     public int getSpeed()
     4:     { ... }
     5:
     6:     ...
     7: }
    
    to this:
     1: public interface Drivable
     2: {
     3:     public int getSpeed();
     4: }
     5: 
     6: public class DriverBase
     7:     implements Drivable
     8: {
     9:     public int getSpeed()
    10:     { ... }
    11: }
    12:
    13: public class Driver
    14:     extends DriverBase
    15: {
    16:     ...
    17: }
    
    On a typical JVM implementation, will the new code execute faster or slower than the original code?

  20. Match each standard library class with its package name.

    ArrayList
    Arrays
    BigInteger
    Calendar
    Cipher
    Class
    Comparable
    Component
    Date
    Error
    EventListener
    Exception
    File
    Frame
    Hashtable
    InputStream
    Integer
    IOException
    JButton
    MessageDigest
    NullPointerException
    NumberFormat
    Object
    OutputStream
    PrintWriter
    PublicKey
    Reader
    RuntimeException
    SecurityException
    Serializable
    SimpleDateFormat
    Socket
    String
    StringBuffer
    System
    Thread
    URL
    Vector
    
    A) com.sun.java
    B) java.awt
    C) java.awt.event
    D) java.beans
    E) java.io
    F) java.lang
    G) java.lang.reflect
    H) java.math
    I) java.net
    J) java.security
    K) java.text
    L) java.util
    M) javax.crypto
    N) javax.swing
    O) javax.swing.event
    

  21. How can the code below be improved to perform better in multithreaded execution environments?
     1: public class Bittle
     2: {
     3:     ...
     4: 
     5:     public synchronized boolean isEnabled()
     6:     {
     7:         return ((getFlags() & 0x00C1) == 0x00C1);
     8:     }
     9: 
    10:     public synchronized void enable(boolean f)
    11:     {
    12:         setFlags(f ? 0x00C1 : 0x0000);
    13:     }
    14: 
    15:     synchronized int getFlags()
    16:     {
    17:         ...
    18:     }
    19: 
    20:     synchronized void setFlags(int f)
    21:     {
    22:         ...
    23:     }
    24: }
    

  22. Show how method getVal() below can return the value of the m_val member variable of the outer class object of argument x.
     1: public class Outer
     2: {
     3:     private int     m_val;
     4: 
     5:     public class Inner
     6:     {
     7:         public int getVal(Inner x)
     8:         {
     9:             ... (return m_val member of x) ...
    10:         }
    11: 
    12:         ...
    13:     }
    14:
    15:     ...
    16: }
    

  23. Show how the code below can be changed so that the contents of the static variables cannot be modified by other classes.
     1: public class Ramble
     2: {
     3:     public static final int     initSize =  1024;
     4:     public static final String  initName =  "Sally";
     5:     public static final Date    initTime =  new Date();
     6: 
     7:     ...
     8: }
    

  24. A program needs to store a dynamically resizable Vector of int values. Show how this can be done.

  25. The Hashtable and Vector classes provide synchronized methods.

    a) What are the equivalent classes for these classes that provide unsynchronized methods?

    b) What are the advantages and disadvantages of using synchronized methods?

  26. A program uses a third-party class (no source is available) that provides only unsynchronized methods. How can the same methods be provided as synchronized methods?

  27. When the following program is run, the resulting output file (out.dat) is empty. Why?
     1: class WriteSomething
     2: {
     3:     public static void main(String[] args)
     4:         throws IOException
     5:     {
     6:         Writer  out;
     7: 
     8:         // Open the output file and write some data to it
     9:         out = new BufferedWriter(new FileWriter("out.dat"));
    10:         out.write("Some data");
    11: 
    12:         // Done
    13:         System.out.println("Done");
    14:         System.exit(0);
    15:     }
    16: }
    

  28. In the code below, class Customer implements the Account interface, yet the interface contains no methods or constants. Of what use is this empty interface?
     1: public interface Account
     2: {
     3:     // Empty
     4: }
     5:
     6: public class Customer
     7:     implements Account
     8: {
     9:     ...
    10: }
    

  29. Is method CarLoan.getAccountNo() below accessible from other classes outside of package my.code?
     1: package my.code;
     2: 
     3: class Loan      // Not public
     4: {
     5:     public int getAccountNo()
     6:     {
     7:         ...
     8:     }
     9: }
    10:
    11: public class CarLoan
    12:     extends Loan
    13: {
    14:     ...
    15: }
    

  30. a) In what order will the static members be initialized in the class below?

    b) Should the initialization order be changed, and if so, how?

     1: public class Hoople
     2: {
     3:     private static Hoop         s_default = new Hoople("default");
     4:     private static Hashtable    s_table =   new Hashtable();
     5:     private static int          s_tableSz = 0;
     6: 
     7:     static
     8:     {
     9:         s_table.put("default", s_default);
    10:     }
    11:
    12:     public Hoople(String id)
    13:     {
    14:         s_table.put(id, this);
    15:         s_tableSz++;
    16:     }
    17: }
    


Author's email: david@tribble.com
Author's home page: http://david.tribble.com

Copyright ©2003 by David R. Tribble, all rights reserved.
Permission is granted to copy this document in whole or in part, or to make reference to, link to, or embed this document within other documents, provided that the original copyright notice remains visible and unaltered.

@(#)www/text/ques-java.html $Revision: 1.2 $ $Date: 2003/05/08 03:33:56 $