The Collected "Hardest" Questions

When I started on the first Java Exam Cram book in 1999, I realized that creating good sample questions was not all that simple. As I worked up questions for the book I made them available for comment on-line using an applet that emulates the real test environment. Thanks to many useful comments from users, I was able to get rid of ambiguous or incorrect questions. Furthermore, by collecting every set of answers I was able to determine the question topics that caused users the most trouble. I selected a total of 19 questions that seemed to cover most of the exam objective areas and put them in a separate "Hardest" collection.

Taking these questions has been one of the options at my certification resources page since December 1999. There have been slight improvements in the questions as users have raised concerns (thanks folks!) I recently analyzed the collected results from over 65,000 individual tests, resulting in the following statistics. Note that the multiple choice - multiple correct answers questions did NOT give a hint as to the number correct because that was the style of the Sun exam at the time.


Question 1 type: Multiple choice - multiple correct answers possible

Category reference cast

Here is the class hierarchy showing the ActionEvent family tree:

java.lang.Object
  |--- java.util.EventObject
         |---java.awt.AWTEvent
               |---- java.awt.event.ActionEvent
Suppose we have the following code to count events and save the most recent event.

1. int evtCt = 0 ;
2. AWTEvent lastE ;
3. public void saveEvent( AWTEvent evt ){
4.   lastE = evt ;
5.   evtCt++ ;
6. }
Which of the following calls of saveEvent would run without causing an exception. Select all which are correct.
OptionCountOption
A* 46663call with an AWTEvent object reference
B* 39434call with an ActionEvent object reference
C. 12275call with an EventObject object reference
D* 27850call with null value

Total answering = 65742 of which 22536 got it right.

OptionDiscussion
A* Answer a is correct because it matches the method signature.
B* Answer b is correct because a subclass reference can always be cast up the hierarchy.
C. Answer c is wrong because the reference can not be cast to a subclass down the hierarchy.
D* Answer d is correct because any reference can be set to null. (Missing this was the most frequent error.)

Question 2 type: Multiple choice - multiple correct answers possible

Category interface cast

Suppose we have two classes defined as follows:

 class ApBase extends Object implements Runnable
 class ApDerived extends ApBase implements Observer
Given two variables created as follows:

  ApBase aBase = new ApBase() ;
  ApDerived aDer = new ApDerived();
Which of the following Java code fragments will compile and execute without error?
OptionCountOption
A. 11554
 Object obj = aBase ;
Runnable rn = obj ;
B* 41378
 Object obj = aBase ;
Runnable rn = (Runnable) obj ;
C. 8327
 Object obj = aBase ;
Observer ob = (Observer)aBase ;
D. 10281
 Object obj = aDer  ;
Observer ob2 = obj ;

Total answering = 65771 of which 26448 got it right.

OptionDiscussion
A. Answer a fails to compile. As far as the compiler is concerned, obj is a plain Object so it objects to the assignment to a Runnable reference. (Most frequently chosen wrong answer.)
B* Answer b compiles and runs. The compiler assumes you know what you are doing with the cast to Runnable.
C. Answer c compiles but fails to run. Because of the specific cast, the compiler thinks you know what you are doing, but the type of the aBase reference is checked when the statement executes and a ClassCastException is thrown.
D. Answer d fails to compile. As far as the compiler is concerned, obj is a plain Object so it objects to the assignment to an Observer reference.

Question 3 type: Multiple choice - multiple correct answers possible

Category local inner class

In the following code for a class in which methodA has an inner class.

 1. public class Base {
 2.   private static final int ID = 3 ;
 3.   private String name ;
 4.   public void methodA( final int nn ){
 5.     int serialN = 11 ;
 6.     class inner {
 7.       void showResult(){
 8.            System.out.println("Rslt= " + XX );
 9.       }
10.     } // end class inner
11.     new inner().showResult();
12.   } // end methodA
13. }
Which variables would the statement in line 8 be able to use in place of XX? Check all which apply.
OptionCountOption
A* 40257the
int ID
in line 2
B* 35897the
String name 
in line 3
C* 41236the
int nn
in line 4
D. 8146the
int serialN
in line 5

Total answering = 65735 of which 29649 got it right.

OptionDiscussion
A* Answer a is correct because inner classes can access any static or member variable in the enclosing class.
B* Answer b is correct because inner classes can access any static or member variable in the enclosing class. (This answer was frequently missed.)
C* Answer c is correct because although it is a local variable, it is declared final.
D. Answer d is wrong because the local variable is not declared final. (This incorrect option was frequently checked.)

Question 4 type: Multiple choice - single correct answer

Category equals method

What happens on trying to compile and run the following code?

1. public class EqualsTest{
2.   public static void main(String args[]){
3.     Long L = new Long( 7 );
4.     Integer J = new Integer( 7 ) ;
5.     if( L.equals( J )) System.out.println("Equal");
6.     else System.out.println("Not Equal");
7.   }
8. }
OptionCountOption
A. 10331The program compiles and prints "Equal".
B* 26355The program compiles and prints "Not Equal".
C. 6893The compiler objects to line 5.
D. 2505A runtime cast error occurs at line 5.

Total answering = 65702 of which 26355 got it right.

OptionDiscussion
A. No, J is not a Long object so the test fails. (This was the most frequently chosen bad answer.)
B* Option b is correct, the test results in a false value because J is not a Long Object.
All of the primitive wrapper Object
equals
tests only compare content once they have determined that the input Object is of the correct class.
C. Options c and d do not occur because the signature of the equals method will take any Object.
D. D does not occur because the signature of the equals method will take any Object.

Question 5 type: Multiple choice - single correct answer

Category shift operators

What happens when we attempt to compile and run the following code?

1. public class Logic {
2.    static int minusOne = -1 ;
3.    static public void main( String args[] ){
4.       int N = minusOne >> 31 ;
5.       System.out.println("N = " + N );
6.    }
7. }
OptionCountOption
A* 29984The program will compile and run, producing the output "N = -1".
B. 7751The program will compile and run, producing the output "N = 1".
C. 2309A runtime ArithmeticException will be thrown.
D. 4453The program will compile and run, producing the output "N = 0".

Total answering = 65698 of which 29984 got it right.

OptionDiscussion
A* Option a is correct, the >> operator extends the sign as the shift operation is performed.
B. No, the >> operator extends the sign as the shift operation is performed, it is the >>> operator which does not sign extend. (This was the most frequently chosen wrong answer.)
C. No, an ArithmeticException is typically thrown due to integer division by zero.
D. No, the sign is extended while shifting.

Question 6 type: Multiple choice - single correct answer

Category files

The following lists the complete contents of the file named Derived.java.

 1.  public class Base extends Object {
 2.      String objType ;
 3.      public Base(){  objType = "I am a Base type" ;
 4.      }
 5. }
 6.
 7. public class Derived extends Base {
 8.    public Derived() { objType = "I am a Derived type";
 9.    }
10.    public static void main(String args[] ){
11.       Derived D = new Derived();
12.    }
13. }
What will happen when this file is compiled?
OptionCountOption
A. 11486Two class files, Base.class and Derived.class will be created.
B* 22989The compiler will object to line one.
C. 9735The compiler will object to line seven.

Total answering = 65692 of which 22989 got it right.

OptionDiscussion
A. No, the compiler will object because the public class name does not match the file name. (This was the most common error.)
B* Right, the compiler error message is 'Public class Base must be defined in a file called "Base.java".' Although it is common for a single Java source file to generate more than one class file on compilation, two public classes can not occupy the same Java source file.
C. No, but if the source file had been named Base.java, then option c would be correct.

Question 7 type: Multiple choice - multiple correct answers possible

Category wrapper classes

Once created, some Java objects are "immutable", meaning they can not have their contents changed. Which of the following classes produce immutable objects?

OptionCountOption
A* 33215java.lang.Double
B. 4182java.lang.StringBuffer
C* 33661java.lang.Boolean
D. 14829java.lang.Math

Total answering = 65688 of which 23751 got it right.

OptionDiscussion
A* Double is a "wrapper" class which produces an immutable object.
B. No, the StringBuffer class is provided with many methods for manipulating its contents.
C* Both the Double and Boolean classes produce immutable objects.
D. The Math class can not be used to create an object, it consists entirely of static methods. (This was the most common bad answer)

Question 8 type: Multiple choice - multiple correct answers possible

Category initializing

Trying to compile the following source code produces a compiler warning to the effect that the variable tmp may not have been initialized.

1. class Demo{
2.   String msg = "Type is " ;
3.   public void showType( int n ) {
4.    String tmp ;
5.    if( n > 0 ) tmp = "positive";
6.    System.out.println( msg + tmp );
7.  }
8. }
Which of the following line revisions would eliminate this warning? Select all that apply.
OptionCountOption
A* 36364
4.  String tmp = null ;
B* 40609
4.  String tmp = "" ;
C* 30007Insert line
6.    else tmp = "not positive" ;
D* 36814Remove line 4 and insert a new line after 2 so that tmp becomes a member variable instead of a local variable in showType as follows:
 3.   String tmp ;

Total answering = 65693 of which 24479 got it right.

OptionDiscussion
A* All of these changes would eliminate the warning. Both a and b provide for initializing the reference.
B* All of these changes would eliminate the warning. Both a and b provide for initializing the reference.
C* Option C ensures that tmp gets initialized no matter what the value of n. (The most common error was not realizing that all four options could be correct.)
D* Option D makes tmp a member variable which will be initialized to null.

Question 9 type: Short text entry - case matters

Category initializing

The Greek letter pi in the Unicode used by Java has the value 3c0 in hexadecimal representation. Write the Unicode literal which would be used to initialize a char variable to pi. Just write the Unicode literal char, not the complete expression, in other words, what should replace XXXX in the following statement?

 char pic = XXXX ;
OptionCountOption
A* 7718'\u03c0'
B* 272'\u03C0'

Total answering = 65690 of which 7990 got it right. A total of 4093 different text answers were recorded.

OptionDiscussion
A* The answer is '\u03c0' or '\u03C0'. Unicode literals always start with "\u" and have four hexadecimal digits. The hexadecimal digits can be either upper or lower case.
B* Either '\u03C0' or '\u03c0' works. Unicode literals always start with "\u" and have four hexadecimal digits. The hexadecimal digits can be either upper or lower case. (On this type of question pay very close attention to what is asked for.)

Question 10 type: Multiple choice - single correct answer

Category local variable scope

The following method definition is designed to parse and return an integer from an input string which is expected to look like "nnn,ParamName". In the event of a NumberFormatException, the method is to return -1.

1. public int getNum( String S ){
2.   try {
3.     String tmp = S.substring( 0,S.indexOf(','));
4.     return Integer.parseInt( tmp );
5.   }catch(NumberFormatException e){
6.     System.out.println("Problem in " + tmp );
7.   }
8.   return -1 ;
9. }
What happens when we try to compile this code and execute the method with an input string which does not contain a comma separating the number from the text data?
OptionCountOption
A* 17004A compiler error in line 6 prevents compilation.
B. 8132The method prints the error message to standard output and returns -1.
C. 5983A NullPointerException is thrown in line 3.
D. 10778A StringIndexOutOfBoundsException is thrown in line 3.

Total answering = 65683 of which 17004 got it right.

OptionDiscussion
A* Option a is correct because the scope of the "tmp" String is confined to the "try" block. (An astonishing 84% missed this.)
B. No, there is compiler error related to the scope of the "tmp" variable.
C. Option c would not occur even if the scope of the "tmp" variable was fixed.
D. Option d would occur only if the scope of the "tmp" variable was fixed.

Question 11 type: Multiple choice - multiple correct answers possible

Category default constructor

Given the following class definition:

1. public class DerivedDemo extends Demo{
2.   int M, N, L ;
3.   public DerivedDemo( int x, int y ){
4.     M = x ; N = y ;
5.   }
6.   public DerivedDemo( int x ){
7.     super( x );
8.   }
9. }
Which of the following constructor signatures MUST exist in the Demo class for DerivedDemo to compile correctly?
OptionCountOption
A. 3769
 public Demo( int a, int b )
B* 39827
 public Demo( int c )
C* 29806
 public Demo( )

Total answering = 65669 of which 27764 got it right.

OptionDiscussion
A. Option a is not required because no constructor with that signature is explicitly called.
B* Option b is required because it is called in line 7.
C* Option c is required because a default (no arguments) constructor is needed to compile the constructor starting in line 3. (Many people missed this option.)

Question 12 type: Multiple choice - multiple correct answers possible

Category class modifiers

Which of the following class declarations for a normal top level class are incorrect use of modifier keywords?

OptionCountOption
A* 32099
  public synchronized class FastClass extends Thread
B* 37846
  private protected class FastClass
C. 5167
  public abstract class FastClass
D. 5438
  class FastClass extends Thread

Total answering = 65664 of which 29258 got it right.

OptionDiscussion
A* Both a and b are incorrect usage, the synchronized, protected and private keywords can not be applied to classes. (Option a was frequently missed.)
B* Both a and b are incorrect usage, the synchronized, protected and private keywords can not be applied to classes.
C. The abstract keyword in c indicates that the class can not be directly instantiated. Typically due to at least one abstract method but this is not necessary. (Many seem to miss the fact that the question calls for incorrect uses. Watch out for this wording on the real test.)
D. d is a legal class declaration.

Question 13 type: Multiple choice - single correct answer

Category method modifiers

Given the following listing of the Widget class:

1. class Widget extends Thingee{
2.    static private int widgetCount = 0 ;
3.    public String wName ;
4.    int wNumber ;
5.
6.    static synchronized int addWidget(){ widgetCount++ ;
7.        wName = "I am Widget # " + widgetCount ;
8.        return widgetCount ;
9.    }
10.    public Widget(){
11.      wNumber = addWidget();
12.    }
13. }
What happens when we try to compile the class and use multiple Widget objects in a program?
OptionCountOption
A. 16545The class compiles and each Widget will get a unique wNumber and wName reflecting the order in which the Widgets were created.
B* 22544The compiler objects to line 7.
C. 2141A runtime error occurs in the addWidget method.

Total answering = 65659 of which 22544 got it right.

OptionDiscussion
A. No, a compiler error is generated by line 7. (Most people did not notice the fact that wName is a member variable and picked this option.)
B* Option b is correct, the static method addWidget can not access the member variable wName. Static methods can only refer to static variables such as widgetCount.
C. Option c is wrong because it is the compiler which catches incorrect use of access modifiers such as static.

Question 14 type: Multiple choice - multiple correct answers possible

Category Thread class

(Questions like this with multiple correct answers are hard because you don't get partial credit, you have to get every one.) Select all of the following methods that are instance methods of the Thread class, excluding any methods deprecated in Java 1.2.

OptionCountOption
A* 37980start()
B. 15308stop()
C* 35232run()
D. 11716suspend()
E. 19176sleep( long msec )
F* 27009toString()

Total answering = 65651 of which 12030 got it right.

OptionDiscussion
A* Answer a is correct, start is an instance method of Thread which makes a new Thread runnable.
B. Option b is wrong because stop is a deprecated method. It is felt that abruptly stopping a Thread may leave an object in a damaged condition.
C* Answer c is correct. The run method is the key to Thread operation.
D. Answer d is wrong, suspend is a deprecated method because a suspended Thread may retain a lock on an important system object.
E. Answer e is wrong because sleep is a static (class) method, not an instance method.
F* Answer f is correct because all Java objects have a toString method.

Question 15 type: Multiple choice - multiple correct answers possible

Category wait & notify

You are working on an applet which does animation. There is a single object animC, derived from java.awt.Canvas, which holds all the animation data and a memory image. There is a single Thread, animT which uses this data to create a new image for the next animation frame and then calls the following method.

1. synchronized void waitForPaint(){
2.    painted = false ; repaint();
3.    while( !painted ){
4.      try{ wait();
5.      }catch(InterruptedException x){}
6.    }
7. }
The paint method in animC executes the following code after the new animation frame has been shown.

  synchronized(this){painted = true ; notify();}
After animT has entered the wait() method in waitForPaint and before the paint method has been executed, which of the following statements is true?
OptionCountOption
A. 9676Other Threads can not modify data in the animC object.
B. 9207Other Threads can only modify data in the animC object using synchronized methods.
C* 20074Other Threads can modify data in the animC object using synchronized or unsynchronized methods.
D. 14970If the animT Thread is interrupted, it will exit the waitForPaint method.

Total answering = 65645 of which 13759 got it right.

OptionDiscussion
A. Answers a and b are wrong. Other Threads can modify data in animC using any method since animT does not hold a lock on the object while in the wait state. (Many people missed this point.)
B. Answers a and b are wrong. Other Threads can modify data in animC using any method since animT does not hold a lock on the object while in the wait state.
C* Answer c is correct. When animT calls wait, the lock on the animC object is released.
D. Answer d is wrong because when a blocked Thread is interrupted, an InterruptedException is thrown. Since this exception is caught inside the while loop, animT will re-enter the wait method. (Many people missed this point.)

Question 16 type: Multiple choice - multiple correct answers possible

Category overloading

The GenericFruit class declares the following method.

 public void setCalorieContent( float f )
You are writing a class Apple to extend GenericFruit and wish to add methods which overload the method in GenericFruit.

Select all of the following which would constitute legal declarations of overloading methods.

OptionCountOption
A* 29878
 protected float setCalorieContent(String s )
B. 4052
 protected void setCalorieContent( float x )
C* 38350
 public void setCalorieContent( double d )
D* 32637
 public void setCalorieContent(String s ) throws NumberFormatException

Total answering = 65638 of which 24949 got it right.

OptionDiscussion
A* Answer a is a valid overloading method declaration because the parameter list differs from the method in GenericFruit.
B. Answer b is wrong for two reasons.
1. It overrides, not overloads, the parent class method because it has the same parameter list.
2. It would cause a compiler error because it is more private than the method it overrides.
C* Answer c is a valid overloading method declaration because the parameter list differs from the method in GenericFruit.
D* Answer d is a valid overloading method declaration because the parameter list differs from the method in GenericFruit.

Question 17 type: Multiple choice - multiple correct answers possible

Category exception rules

Here is the hierarchy of Exceptions related to array index errors.

 Exception
    +-- RuntimeException
           +-- IndexOutOfBoundsException
                  +-- ArrayIndexOutOfBoundsException
                  +-- StringIndexOutOfBoundsException
Suppose you had a method X which could throw both array index and string index exceptions. Assuming that X does not have any try - catch statements, which of the following statements are correct?
OptionCountOption
A. 15532The declaration for X must include "throws ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException".
B* 31280If a method calling X catches IndexOutOfBoundsException, both array and string index exceptions will be caught.
C. 12412If the declaration for X includes "throws IndexOutOfBoundsException", any calling method must use a try - catch block.
D* 20424The declaration for X does not have to mention exceptions.

Total answering = 65634 of which 13372 got it right.

OptionDiscussion
A. No, the significant word here is "must". Because these exceptions descend from RuntimeException, they do not have to be declared.
B* Yes, exceptions obey a hierarchy just like other objects.
C. No, the significant word here is "must". Because these exceptions descend from RuntimeException, they do not have to be caught even if declared by method X.
D* Yes, because these exceptions descend from RuntimeException, they do not have to be declared.

Question 18 type: Multiple choice - multiple correct answers possible

Category try catch finally

The following method is designed to convert an input string to a floating point number, while detecting a bad format. Assume that

factor
is correctly defined elsewhere.

1. public boolean strCvt( String s ){
2.   try {
3.     factor = Double.valueOf( s ).doubleValue();
4.     return true ;
5.   }catch(NumberFormatException e){
6.     System.out.println("Bad number " + s );
7.     factor = Double.NaN ;
8.   }finally { System.out.println("Finally");
9.   }
10.  return false ;
11. }
Which of the following descriptions of the results of various inputs to the method are correct?
OptionCountOption
A* 30472Input = "0.234" - Result: factor = 0.234, "Finally" is printed, true is returned.
B. 6104Input = "0.234" - Result: factor = 0.234, "Finally" is printed, false is returned.
C. 15038Input = null - Result: factor = NaN, "Finally" is printed, false is returned.
D* 20306Input = null - Result: factor unchanged, "Finally" is printed, NullPointerException is thrown.

Total answering = 65624 of which 16598 got it right.

OptionDiscussion
A* Answer a is correct and b is wrong because the return value in line 4 is used.
B. Answer b is wrong because the return value in line 4 is used.
C. Answer c is wrong because a NullPointerException is thrown in line 3 and is not caught in the method.
D* Answer d is right because a NullPointerException is thrown in line 3 and is not caught in the method. (This answer was frequently missed.)

Question 19 type: Multiple choice - multiple correct answers possible

Category switch

Given the following code fragment:

 XXXX x ; // variable x is declared and initialized here
 switch( x ) {
   case 100 : System.out.println("One hundred");break ;
   case 200 : System.out.println("Two hundred");break ;
   case 300 : System.out.println("Three hundred");break ;
 }
Choose all of the declarations of x which will not cause a compiler error.
OptionCountOption
A. 19685
byte x = 100 ;
B* 36740
short x = 200 ;
C* 39418
int x = 300 ;
D. 5875
long x = 400 ;

Total answering = 65617 of which 15749 got it right.

OptionDiscussion
A. No, x can not be a byte type because the value 300 is not compatible. The type used in the switch statement must accommodate all of the values in the case statements. (Many people missed this point.)
B* Yes, x can be a short since all of the cases can be accommodated.
C* Yes, x can be an int since all of the cases can be accommodated.
D. No, switch statements can not use long values. You would have to have a specific cast:
 switch((int)x) {

Summary of Scores

Number scoring 100% 1021
Number scoring between 90.0% and 99.9% = 1727
Number scoring between 80.0% and 89.9% = 3588
Number scoring between 70.0% and 79.9% = 4108
Number scoring between 60.0% and 69.9% = 4701
Number scoring between 50.0% and 59.9% = 5284
Number scoring between 40.0% and 49.9% = 5754
Number scoring between 30.0% and 39.9% = 5669
Number scoring between 20.0% and 29.9% = 5666
Number scoring between 10.0% and 19.9% = 6366
Number scoring between 0.0% and 9.9% = 21857


HtmlQanalyzer version May 14, 2003