Java Exam Examples and Notes

  1. Sun's Objectives for the Java 1.2 Programmer's Exam and my old study notes:
    1. Declarations and Access Control:
    2. Flow Control and Exception Handling:
    3. Exceptions and Runtime errors
      1. simple catch statement
                catch(Exception ex){ System.out.println("" + ex);}

      2. a better catch statement
           catch(Exception ex){ 
                System.err.println("" + ex);  

    4. RuntimeException

      java.lang.RuntimeException are exceptions like dividing by zero, or invoking a method on a null object. The JVM catches and handles these for us. They are not declared in the method signature (read: way tedious). These are also called "unchecked" exceptions. They can be caught with a "catch(Throwable t)" clause.

    5. PrintStackTrace()

      A method on Throwable class to print where in the call tree an exception was thrown. Also has two overridden methods, printStackTrace(PrintStream) and printStackTrace(PrintWriter)

    6. finally
      The finally clause is always executed whether the try/catch blocks fail or not. Good for cleaning up files and databases. Be careful about throwing exceptions inside finally. It can hide previous exceptions.

          catch(Exception ex){...}
          finally {...}

    7. A static method to dump Throwables (eg, Exceptions) messages to the browser (example only, in real life you would use a template)
       * writes the contents of a Throwable to the browser
       * @author mitch fincher
       * @param e - the Throwable thrown
       * @param res - the response object
       * example usage:
       * <code>
       * try {
       *    ... your way cool code that could throw an Exception or Throwable...
       *    } catch(Exception e) 
       *  {
       *     writeExceptionToBrowser(out, e, res); 
       *      return;
       *    } 
       *    } catch(NoClassDefFoundError ec) 
       *  {
       *     writeExceptionToBrowser(out, ec, res); 
       *      return;
       *    } 
       * </code>
      public static void writeExceptionToBrowser(PrintStream out, Throwable e, 
                                                  HttpServletResponse res)
          try {
          out.print("<head>\n  <title>Servlet Error</title>\n");
          out.print("Date:"+new java.util.Date()+"<br />");
          // do custom work...
          if(e instanceof SAXParseException) {
              out.println("<br>SAXParseException: error on line " + 
      	((SAXParseException)e).getLineNumber() );
              out.println("<br>SAXParseException: error in column " + 
      	((SAXParseException)e).getColumnNumber() );
          if(e instanceof SQLException) {
              int i=0;
              do {
              System.out.println("**********\nSQLException Number: " + i++);
              System.out.println("ex.getMessage():" + ex.getMessage());
              System.out.println("ex.getSQLState(): " + ex.getSQLState() );
              System.out.println("ex.getErrorCode(): " + ex.getErrorCode() );
              } while ( (ex = ex.getNextException()) != null);
          catch(Exception ex)
              System.out.println("writeExceptionToBrowser: " + ex);

      Yet another method for exception handling:

      public static void formatException(Object obj, Exception e, String message)
          if(obj != null) {
          System.out.println(""+new java.util.Date()+ "\n  "+message +"\n     ****\n  " + e);
          if(e != null) {
          if(e instanceof SAXParseException) {
      	System.out.println("SAXParseException: error on line " + 
      	((SAXParseException)e).getLineNumber() );
      	System.out.println("SAXParseException: error in column " + 
      	((SAXParseException)e).getColumnNumber() );
      	System.out.println("getPublicId():" + 
      	((SAXParseException)e).getPublicId() );
      	System.out.println("getMessage():" + 
      	((SAXParseException)e).getMessage() );
      	System.out.println("getSystemId():" + 
      	((SAXParseException)e).getSystemId() );
      	System.out.println("getException() : " + 
    8. An overridden method cannot throw a more general or different type of Exception than it predecessor, otherwise it could not "stand in" for its parent class.

    9. test variable in a switch statement must be a byte, char, short, or int, "long" will not work.

    10. - Garbage Collection:
    11. - Language Fundamentals:
    12. - Operators and assignments:
    13. - Overloading, Overriding, Runtime Type, and Object Orientation:
    14. - Threads Notes
      1. Threads have four states:
        1. new
        2. runnable
        3. blocked
        4. dead
      2. When two methods are "synchronized" in a class, the lock is placed on the object itself, so the two methods cannot run in parallel in that object instance.
      3. Static methods may acquire a lock on the Class, but this is different than a lock on any particular instance of the class. Its useful for updating static variables.
    15. The java.awt package

      AWT Notes

      1. Default visibility for all components is "true" except for Window, Frame, and Dialog
      2. Component is abstract
      3. Window class cannot be nested into other containers
      4. Windows are seldom used; its subclasses, Dialog and Frame, are more common. In awt, pack() can only be used on a Window or extension
      5. The number of visible rows in a List component can only be set in the constructor
      6. Component only has one "add" method and it takes a PopupMenu.
      7. Container only has three direct awt children: Panel, Window, and ScrollPane.
      8. Menu Inheritance hierarchy for MenuComponent
        1. MenuBar
        2. MenuItem
          1. Menu
            1. PopupMenu
          2. CheckboxMenuItem
      9. To add a menubar to a frame use setMenuBar(), not add().
      10. Layout Managers - java.awt has 5 of them
        1. FlowLayout - the default Panel and Applet. Arranges the components from left to right. Does not resize components - only shows those that fit. Tries to place components in a long row left to right, and starts wrapping when it runs out of room. The alignment, horizontal and vertical gaps, can be set in the constructor.

          panel.setLayout(new FlowLayout(FlowLayout.RIGHT,horizGap,vertGap));

          Default alignment is CENTER and gaps are 5 pixels.

        2. BorderLayout - the default for Window, Frame and Dialog. It tries to preserve the height of North and South and the width of East and West. North and South are streched horizontally to fill the space and East and West are streched vertically. In BorderLayout, the last item placed in a position replaces the previous one. The last is the only one you see. Default gap is zero pixels. If no direction is given in the constructor, CENTER is used. Oddly enough "BorderLayout.NORTH" is not an int, but a string, "North". The CENTER component streches vertically and horizontally.
        3. GridLayout- Divides area into equally sized cells. All cells have the same dimension. Components are resized to fit the cell. Default gap is zero pixels.

          panel.setLayout(new GridLayout(rowNum,colNum,1,1));

          Note: rowNum or colNum can be zero (but not both), in which case the other number is used. The code below will create a single vertical column with all the components since the number of rows is set to zero.

          panel.setLayout(new GridLayout(0,1));

        4. CardLayout - shows only one component at a time. Has the following methods which take the name of the parent as an argument, first(),last(),next(),previous()
        5. GridbagLayout -

          When passed to the add() method, the GridBagConstraints object gets cloned.

          Notes on GridBagConstraints fields.
          1. gridx,gridy - specifies which cell the component will go in. "GridBagConstraints.RELATIVE" specifies the component goes to the right for gridx and beneath for gridy.
          2. gridwidth, gridheight - specifies how many cells wide and tall this component will occupy. Default is (1,1). "RELATIVE" implies this is the second to last component, "REMAINDER" implies this is the last one for the row or column.
          3. fill - determines if the component can grow. Default is NONE, may also be VERTICAL, HORIZONTAL, or BOTH.
          4. weightx, weighty - determines how much a component can grow to occupy its alloted space. By default its zero, meaning it will not grow.
          5. anchor - places the component in this direction inside its alloted area, e.g., NORTHEAST, CENTER (default).
          6. ipadx, ipady - specifies the internal border area
          7. insets - new Insets(int top,int left,int bottom,int right), determines the external border area, default is (0,0,0,0).

          A small example:

              GridBagLayout gridbag1 = new GridBagLayout();
              GridBagConstraints constraints1 = new GridBagConstraints();
              constraints1.insets = new Insets(0,5,0,5);
              constraints1.weighty = 1;
              constraints1.weightx = 1;
              constraints1.fill = GridBagConstraints.HORIZONTAL;
              constraints1.gridwidth = GridBagConstraints.REMAINDER;
    16. Events Notes:

      AWT event hierachy:
      java.lang.Object -> java.util.EventObject -> java.awt.AWTEvent(abstract).

      getID() returns an int that describes the event type. e.g., FocusEvent.FOCUS_LOST.

      Object getSource() returns the source of the event.

      Events come in two basic flavors, Semantic and Low level.

      1. Semantic, or high level
        1. ActionEvent - generated by Button, List(when double clicked), MenuItem, or TextField (when "Enter" is pressed). Interesting methods: String getActionCommand(), int getModifiers()
        2. AdjustmentEvent - generated by Scrollbar. Interesting methods: int getValue() returns internal value.
        3. ItemEvent - generated by Checkbox, CheckboxMenuItem, Choice, or List. Interesting methods: Object getItem(), int getStateChange()
        4. TextEvent - generated by TextArea and TextField. No interesting methods, well except for paramString()
      2. Low level
        1. ComponentEvent - a component is hidden, resized, moved, or shown
        2. ContainerEvent - a component is added or removed from a container
        3. FocusEvent - a component has lost or gained focus
        4. KeyEvent - key has been pressed, released, or "typed"
        5. MouseEvent - a component has mouse activity
        6. PaintEvent - a compoment needs its paint() method invoked
        7. WindowEvent - a window has been opened, closed, closing, iconified, deiconified, activated, or deactivated. Note: if the window is moved or resized, a ComponentEvent is generated.
      3. Notes:

        MouseEvent has two listener interfaces, MouseListener and MouseMotionListener

        Adapter classes implement stubs for all low level event interfaces, eg, ComponentAdapter implements the interface ComponentListener. No adapters are needed for semantic events since they only have 1 method.

        Any number of listeners may be added to a component.

        Delegation of the events: The AWT system invokes processEvent() on a componet, which then, if appropriate, invokes the more defined processXEvent() where X is Focus, Mouse, Key etc... These methods may be overridden to provide custom event handling, but enableEvent() must be called.

        Example of anonymous inner class adapter

           writejpegMenuItem.addActionListener (new ActionListener() {
        	   public void actionPerformed (ActionEvent e) {
        	   } });
  2. The java.lang package
  3. The java.util package

    Collection Notes: Three main parts:

    1. Interfaces: Collection, Set, SortedSet, List
    2. Implementations: HashSet, HashMap, Hashtable, ArrayList, Vector, TreeSet, TreeMap, LinkedList
    3. Algorithms via java.util.Collections: binarySearch(), fill(), shuffle(), sort()

    Some methods in the Collection interface are optional, like removeAll(). If the collection object does not support the optional operation, an unchecked UnsupportedOperationException is thrown.

    The Set interface adds no new methods, just restriction in the operations. The major implementor of Set is HashSet.

    If a set obtained from keySet on a map is changed, the map itself is changed.

    Hashtable and Vector are the only thread safe collections.

    Lists have a ListIterator that extends Iterator and adds methods to move backwards thru the list. The set(int i, Object o) method replaces the element at the position, while add(int i, Object o) pushes the others down starting with that position.

  4. The package
  5. Java References:
    2. Struts overview - a java MVC framework
    3. Austin Java User's Group
    4. Java Language Specification, Basic language constructs (like switch) not in the classes documentation.
    5. Java Certification: documentation
        1. Mock Exams:
        2. Mock Exams.
        3. Mock Exam Index
        4. Java Links
        5. 3 mock exams from
        6. Mock exam by objectives - The TestCafe MockTest
      1. jguru's JavaCertification FAQ
      2. Certification Sites
      4. Sun's objectives
      5. Sun's Certification Site with practice exams
      7.'s certification pages
      8. Java Certification Exam info
      10. Java Programmer Certification Exam And Training by Marcus Green
      12. javaprepare - how to get signed up to take an exam
      13.    Sample Questions on Fundmentals
      14. Inner Class Tutorial
      15. Excellent overview of objectives and notes
      16. Java Cert Tutorial on
    6. Richard G Baldwin's Java Links
    8. or
    9. A java tutorial
    11. Another java tutorial
    12. Yet Another java tutorial
    13. Gnu java software repository (things like getopt, regexp...)
    14. GifEncoder
    16. Ed Roman's book on EJB
    17. Baldwin's java tutorials
    19. ... Swing tutorial
    20. an open source servlet environment
    21. bean shell, way cool. Interpreted Java, what a concept.
    22. JavaDoc, A wonderful way to document your java code.
    23. Java Programmer Help Center
    24. java_network_programming FAQ, Good info for network java
    25. Online Tutorials, From
    26. JGL, Free java classes like LinkedLists, Sets, and Queues from objectspace.
    27., Java Q & A FAQ
    28., IBM's java site
    30. Thinking in Java, Gamelan
    31. Java Certification, Gamelan
    32. Java 2D tutorial, JavaBoutique
    33., earthweb's java newsgroup
    34., earthweb's java tutor
    35., EJB Intro
    37. Jave Development Environment for emacs
    39. - Good index of Java Links
    41. EMF a modeling framework for the Eclipse dev environment for java.
  6. Misc Java Questions for Exam Study
    1. What is the maximum length of a java identifier?

    2. Can Unicode characters be in a java identifier?

    3. What are the four data types?

    4. Member variables of type "boolean" are set to what?

    5. What does it mean that Strings are immutable? unextendable?

    6. If a primitive type "midint" (12 bits) had a maximum value of +2047, what would the minimum value be?


    8. What are the three types of comments?

    9. public static void main(String args[]) { int i; System.out.println(i); }

    10. How to make a short int constant?

    11. Do all bitwise operations on shorts create ints?

Go to Home page. Kindly report errors, typos, or misspellings here.