The Java Explorer

Tips and insights on Java

  • Subscribe

  • If you find this blog useful, please enter your email address to subscribe and receive notifications of new posts by email.

    Join 35 other followers

Java Quiz

Posted by Eyal Schneider on September 17, 2009

This time I posted a 20 questions quiz, developed for testing general Java skills.
Most of the questions address fundamental topics in Java(5), but the test is not a trivial one.  The right answers plus their explanations can be found on the bottom. You are welcome to add your comments.

Enjoy, and good luck!

Question 1

public class CrazyCount {
    private static volatile int count = 0;

    public static void main(String[] args) {
        for(int i=0;i<1000;i++)
            new Thread(new Runnable(){
                public void run() {


What will be the value of count after all 1000 threads finish their work?

(a) Garbage, because the writes are not synchronized
(b) A value between 1 and 1000
(c) Exactly 1000
(d) At least 1000

Question 2

Consider the following multi threaded producer/consumer model:

 public class ProducerConsumer {
    private Job currentJob = null;

    public synchronized void addJob(Job job) throws InterruptedException{
        while (currentJob!=null)

    public synchronized Job consumeJob(){
        Job res = currentJob;
        return res;

Which of the following is correct?

(a) addJob will wait till the current job is executed, but consumeJob will never block.
(b) Jobs will be executed in the exact order in which they are added with addJob.
(c) This code may not work because of deadlocks
(d) ‘while’ in addJob can be replaced by ‘if’, without changing the behavior.

Question 3

Consider the following Singleton design pattern implementation:

public class ConnectionsMgr {
    private static ConnectionsMgr instance = null;

    public static ConnectionsMgr getInstance(){
        if (instance==null){
		if (instance==null)
		    instance = new ConnectionsMgr();
	return instance;


Why is this implementation problematic?

(a) An uninitialized ConnectionsMgr object may be returned
(b) Synchronizing on ConnectionsMgr.class is not allowed
(c) The instance may be created more than once

Question 4

Which of the following statements regarding the final reserved word is correct?

(a) A final method can not be overriden by subclasses, and a final class can not be subclassed
(b) A final data member must be given a value in its declaration line
(c) A local variable declared as final can still be mutated using setter methods
(d) (a) and (c) are correct

Question 5

public static void main(String[] args) {
	String s = null;
    catch(Exception e){
	System.out.println("Caught exception!");
    catch(RuntimeException e){
	System.out.println("Caught a runtime exception!");

This code:

(a) Displays “Caught exception!” when executed
(b) Displays “Caught runtime exception!” when executed
(c) Runs without throwing an exception
(d) Does not compile

Question 6

Which of the following statements regarding exceptions is correct?

(a) IOException can be thrown without the need to declare it in the method header
(b) catch(Exception) will catch OutOfMemoryError
(c) ClassCastException can be thrown without the need to declare it in the method header
(d) (b) and (c) are correct

Question 7

Which of the following is the preferred way to stop a thread?

(a) Calling the Thread’s interrupt() method
(b) Calling interrupt() and then stop()
(c) Calling the stop() method
(d) Calling join() to wait for the thread to end

Question 8

public class Swap {
    public static void swapStrings(String x, String y){
	String temp = x;

    public static void main(String[] args) {
	String a = "1";
	String b = "2";
	swapStrings(a, b);
	System.out.println("a="+a+" ,b="+b);

What will be the output when executing this main?

(a) An exception will be thrown
(b) “a=2 ,b=1”
(c) “a=1 ,b=2” because strings are immutable
(d) “a=1 ,b=2” because Java passes parameters by value

Question 9

public static void main(String[] args) {
    ArrayList<Point> list = new ArrayList<Point>();
    list.add(new Point(100,200));

    ArrayList<Point> listCopy = (ArrayList<Point>) list.clone();



What will be the output of this main?

(a) [java.awt.Point[x=100,y=200]]

(b) [java.awt.Point[x=150,y=250]]

(c) [java.awt.Point[x=100,y=200]]

(d) [java.awt.Point[x=150,y=250]]

Question 10

Assume that class B extends class A.
Consider a method that is declared as follows:  public void callMe(List<A> l)

Which of the following data types can be passed as parameters to callMe(..)?
(a) List<B>
(b) ArrayList<B>
(c) ArrayList<A>
(d) All answers are correct

Question 11

Assumes that class B extends class A.

public void callMe(List<? extends A> l){
    l.add(new A());
    l.add(new B());

This method:

(a) Compiles, but with a warning
(b) Does not compile
(c) Runs correctly
(d) May cause ClassCastException

Question 12

What will be the output of the following code?

class Base {
    int i = 10;

    public Base(){

    public int get(){
        return i;

public class Derived extends Base{
    int j = 20;

    public int get(){
        return j;

    public static void main(String argv[]){
        Base b = new Derived();

(a) 0
(b) 10
(c) 20
(d) None of the above

Question 13

What will be the output of the following code?

class Base {
    protected int i = 10;

    public int get(){
        return i;

public class Derived extends Base{
    protected int i = 20;

    public int get(){
        return i;

    public static void main(String argv[])
        Base b = new Derived();

(a) 10

(b) 10

(c) 20


Question 14

What is the output of the following code?

String s1 = new String("Test");
String s2 = "Test";
if (s1==s2)
if (s1.equals(s2))

(a) Same
(b) Equals
(c) Same
(d) No output

Question 15

What is the output of the following code?

class Parent{
    private void f(){

    public void g(){

public class Child extends Parent{
    public void f(){

    public static void main(String args[]){
        Parent p = new Child();

(a) Parent.g()
(b) Parent.g()
(c) The code does not compile
(d) An exception is thrown

Question 16

Consider the following overloading scenario:

public class Overloader{
    public static void read(String s){

    public static void read(Integer i){

    public static void read(Object o){

    public static void main(String args[]){
        Object s = new String("Java");
        Integer i = 10;

What would be the output of each of the 3 read commands in comment?

(a) read(s) prints “read(String)”
read(i) prints “read(Integer)”
read(null) prints “read(Object)”

(b) read(s) prints “read(Object)”
read(i) prints “read(Integer)”
read(null) prints “read(Object)”

(c) read(s) prints “read(Object)”
read(i) prints “read(Integer)”
read(null) does not compile

(d) None of the above

Question 17

Which of the following statements is correct?

(a) A daemon thread is terminated when all non-daemon threads terminate
(b) A thread is created as a daemon thread if and only if it is created by a daemon thread
(c) Non daemon threads may keep the application from shutting down, even if the main thread is terminated.
(d) All of the above are correct

Question 18

class Parent{
    protected void x(){}
    public void y(){}

public class Child extends Parent{
    public void x(){}
    protected void y(){}

When compiling this code:
(a) It compiles successfully
(b) Compilation error – x can’t have its visibility increased
(c) Compilation error – y can not have its visibility reduced
(d) Compilation error – neither x nor y can have their visibility changed

Question 19

String s = new String("Wanna live forever!");
WeakReference<String> r1 = new WeakReference<String>(s);
SoftReference<String> r2 = new SoftReference<String>(s);
String s2 = r1.get();
s = null;

Assuming that no garbage collection took place, what is the reference strength of the string created at line #1, after these lines of code?
(a) Not referenced
(b) Weakly referenced
(c) Softly referenced
(d) Strongly referenced

Question 20

int x=0;
int y=0;
    if ((++x==10) && (++y==10))

When executed, this code:
(a) Performs 10 iterations and ends
(b) Performs more than 10 iterations and ends
(c) Performs less than 10 iterations and ends
(d) Enters an infinite loop


1)  (b)
A race condition between threads may cause a a write to cancel other writes, thus multiple concurrent “incrementations” may result in a single incrementation.

2) (a)
(b) is incorrect, since there is no guarantee about the order in which waiting threads are awakened using Object.notify().
(d) is incorrect because when a producer thread is awakened, there is no guarantee that another producer thread was not awakened just before, setting the current job to another value.
Besides, Java documentation recommends always to use ‘while’ loops on wait() rather than ‘if’.

3) (a)
The line “instance=new ConnectionsMgr()” is not atomic. It results in multiple machine instructions, one of which is the reference assignment itself. Due to the Java memory model rules, this specific instruction is allowed to be reordered with respect to the other instructions. This reordering may cause the assignment to take effect before the object is initialized. Another thread calling getInstance() may therefore receive a non null reference to an uninitialized memory block.  See this article for more details.

4) (d)
An object data member or a local object variable declared as final can not change its address. However, the referenced object can be freely mutated.
(b) is not true because the member can be initialized in the constructor/s also.

5) (d)
RuntimeException derives from Exception, so the ordering of the catch blocks makes the second unreachable.

6) (c)
ClassCastException is an unchecked exception, so it does not need to be declared. IOException, however, is a checked exception, and you must either catch it or declare the method as “throws IOException”. OutOfMemoryError is a Throwable, but it derives from Error and not from Exception.

7)  (a)
Thread.stop() is a deprecated method that is not recommended for use. It stops a thread violently without guaranteeing anything about the integrity of the data manipulated by that thread. This may cause corrupt data to be viewed by other threads. Furthermore, there are some cases in which Thread.stop() will not terminate a thread.
Thread.interrupt() is preferred, but it relies on the code run by the thread to be friendly and react to the interruption.

8) (d)
Since Java passes parameters by value (not by reference!), there is no way to implement a swap method in Java. In C++ for example, it is possible, using references (&).

9) (d)
Collections such as java.util.ArrayList do not perform deep copying when cloned. Item references stay the same.

10) (c)
(a) and (b) are incorrect because if legal, they would have break the type safety. The method callMe could have added an instance of type A, and the caller now has a collection of both A’s and B’s, while it assumes that it has only elements of type B. See my previous post for more details.

11) (b)
Assume that C descends from B. The method callMe may receive as a parameter an object of type List<C>. If the additions were considered legal, this would result in a list defined as List<C> containing instances of super classes such as B and A. That breaks the generics type safety, since it will not protect the collection from an unexpected ClassCastException. See my previous post for more details.

12) (a)
Overriding methods that are called directly/indirectly by the superclass’ constructor should be done with care. If the overriden method uses data members belonging to the subclass, then they are still not initialized at that point! In this example, the data member is of type int, so the default initialization will give it a value 0.
For more explanations and a workaround for this problem, see posts 86 and 86b of the Java Specialists’ Newsletter.

13) (b)
Methods are invoked virtually – the exact method to be executed is determined at runtime according to the actual class of the object on which it was called. Data members, however, do not really override each other. Each class has its member i, and the one to be retrieved is determines at compile time, according to the declared class of the reference (in this case Base).

14) (b)
Using new String(…) forces Java to actually create a new instance of a string. Strings defined as literals (e.g. String x=”hello”), however, will always be represented by the same object reference at runtime.

15) (b)

16) (c)
The method signature to be invoked is determined at compile time. Therefore, it depends on the declared type and not the runtime type of the argument/s.
Regarding the null parameter – the compiler can not determine which signature is the correct one, since all the three reads are legitimate.

17) (d)

18) (c)
Reducing visibility of methods when overriding is not permitted.

19) (d)
s2 still hard-references the string.

20) (b)
Tricky thing… The Java language specification specifies that the second operand of && is never evaluated when the first operand evaluates to false (See this section). Consequently, only when x reaches 10 y will become 1. Later, x will overflow and reach 10 again, and so on; until both counters reach 10 and the loop will stop.


10 Responses to “Java Quiz”

  1. Seva said

    Good that you finally posted your famous quiz here!

    Off Topic: WordPress has an automatic code syntax highlighter. You can see the example here.

  2. david-zzz said

    Very good quiz. thanks a lot.
    But for the question 20, the answer should be (d). I tested it.

    • Eyal Schneider said

      Thanks :)

      Regarding Q20, I don’t see the behavior you describe. Can you describe the Java environment/s where you tested it? Are you sure you waited long enough?
      My answer is based on 2 Java language specifications:
      1) Numeric primitives have a “cyclic” behavior when incremented beyond their max value
      2) The boolean operator && must not evaluate the second operand if the first evaluates to false (See the Java spec)

  3. Meir said

    Thanks for the interesting quiz.

    I have 2 comments that I will be happy if you could refer to.
    1. Q5 – I tried it and it looks like wrong explenation. The code does not compile, but because ‘Exception’ is not thrown from the code in the try section. Your explenation was correct in case instead of ‘Exception’ you had ‘Throwable’.

    2. Q8 – the sentence ‘Since Java passes parameters by value (not by reference!)’ is lets say misleading. Imagine that you would have StringBuffer instead of String, would you then could not change the original values in swap function?!

    • Eyal Schneider said

      Regarding Q5: If you check carefully, you’ll see that the compile time error is “Unreachable catch block for RuntimeException”, and not “Unreachable catch block for Exception”.
      Since RuntimeException descends from Exception, it’s “hided” by the previous catch block therefore becoming unreachable.
      Catching “Exception” is always allowed (though usually not recommended). The reason is that the inheritance tree under Exception includes both checked and unchecked exceptions, so it may still catch unchecked exceptions even if no checked exception are expected.

      Regarding Q8: Java is considered a “pass by value” language because the language provides no means for modifying the parameter references themselves (they still point to the same heap location after the call).
      In Q8, even if you replace String with StringBuffer (without changing swap’s implementation), the swap method will not work. You can swap the contents, but not the references themselves.
      When I say “there is no way to implement a swap method in Java”, I mean a reference swap. Any other kind of swap is specific and depends on the class structure.

  4. David said

    Thanks for the quiz.
    There is a problem i guess. Question 15, I think the correct answer is b.
    there is no overriding for f() within Parent’s method g(), f() is a private one of Parent

  5. Bálint Balázs said

    Thanks for this excellent quiz.
    For Question 17, however, I feel the answer b is not true. The ‘only if’ part is false, because daemon threads can be created by a non-daemon thread as well.

    • Eyal Schneider said

      The way I phrased (b) may be confusing. What I meant is that the *initial* daemon/non-daemon status of a thread is determined by the creating thread, where the constructor is invoked.
      You can always call setDaemon(..) later, of course.

      From Java documentation of java.lang.Thread:
      “When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon. “

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: