Collection Objective Questions

Which of these are core interfaces in the collections framework?

Select the three correct answers.

Set

Bag

LinkedList

Collection

Map

11.2 Which of these implementations are provided by the java.util package?

Select the two correct answers.

HashList

HashMap

ArraySet

ArrayMap

TreeMap

11.3 What is the name of the interface used to represent collections that maintain non-unique elements in order?

Select the one correct answer.

Collection

Set

SortedSet

List

Sequence

Example A Simple Class for Version Number

public class SimpleVNO {
    // Does not override equals() or hashCode().

    private int release;
    private int revision;
    private int patch;

    public SimpleVNO(int release, int revision, int patch) {
        this.release  = release;
        this.revision = revision;
        this.patch    = patch;
    }

    public String toString() {
        return "(" + release + "." + revision + "." + patch + ")";
    }
}

Example Natural Order and Total Order

import java.util.*;

public class ComparatorUsage {
    public static void main(String[] args) {

        // Choice of comparator.
    //  Set strSet = new TreeSet();                              // (1a)
    //  Set strSet = new TreeSet(String.CASE_INSENSITIVE_ORDER); // (1b)
        Set strSet = new TreeSet(new RhymingStringComparator()); // (1c)

        // Add each command line argument to the set.
        for (int i=0; i < args.length; i++) {                    // (2)
            strSet.add(args[i]);
        }
        System.out.println(strSet);                              // (3)
    }
}

class RhymingStringComparator implements Comparator {
    public int compare(Object obj1, Object obj2) {               // (4)

        // (5) Create reversed versions of the strings.
        String reverseStr1 = new StringBuffer((String) obj1).reverse().toString();
        String reverseStr2 = new StringBuffer((String) obj2).reverse().toString();

        // Compare the reversed strings lexicographically.
        return reverseStr1.compareTo(reverseStr2);               // (6)
    }
}
The program is run with the following program arguments on the command line:
>java ComparatorUsage court Stuart report Resort assort support transport distort
Output from the program using the natural order (1a):
[Resort, Stuart, assort, court, distort, report, support, transport]
Output from the program using the case insensitive order (1b):
[assort, court, distort, report, Resort, Stuart, support, transport]
Output from the program using the rhyming order (1c):
[Stuart, report, support, transport, Resort, assort, distort, court]

Example Using Maps

import java.util.*;

public class WeightGroups {
    public static void main(String[] args) {

        // Create a map to store the frequency for each group.
        Map groupFreqData = new HashMap();

        int numArgs = args.length;
        for (int i=0; i
Running the program with the following arguments:
>java WeightGroups 74 75 93 75 93 82 61 92 10 185
gives the following output:
10:     *
60:     *
75:     ***
80:     *
90:     *
95:     **
185:    *

Example Using Lists

import java.util.*;

public class TakeAGuess {
    final static int NUM_DIGITS = 5;

    public static void main(String[] args) {

        // Sanity check on the given data.
        if (args.length != NUM_DIGITS) {
            System.err.println("Guess " + NUM_DIGITS + " digits.");
            return;
        }
        /* Initialize the solution list. This program has a fixed solution. */
        List secretSolution = new ArrayList();                      // (1)
        secretSolution.add("5");
        secretSolution.add("3");
        secretSolution.add("2");
        secretSolution.add("7");
        secretSolution.add("2");

        // Convert the user's guess from string array to list.         (2)
        List guess = new ArrayList();
        for (int i=0; i
Running the program with the following arguments:
java TakeAGuess 3 2 2 2 7
gives the following output:
4 digit(s) correctly included.
1 digit(s) correctly placed.

Example Using Sets

import java.util.*;

public class CharacterSets {
    public static void main(String[] args) {
        int numArgs = args.length;

        // A set keeping track of all characters previously encountered.
        Set encountered = new HashSet();                              // (1)
        // For each program argument in the command line ...
        for (int i=0; i
Running the program with the following arguments:
java CharacterSets i said i am maids
results in the following output:
[i] and [] are disjunct.
[d, a, s, i] is a superset of [i]
[i] is a subset of [d, a, s, i]
[a, m] and [d, a, s, i] have [a] in common.
[d, a, s, m, i] is equivalent to [d, a, s, m, i]

Example Using an Iterator

import java.util.*;

public class IteratorUsage {
    public static void main(String[] args) {

        // (1) Create a list of Integers.
        Collection intList = new ArrayList();
        int[] values = { 9, 11, -4, 1, 13, 99, 1, 0 };
        for (int i = 0; i < values.length; i++)
             intList.add(new Integer(values[i]));

        System.out.println("Before: " + intList);         // (2)

        Iterator interator = intList.iterator();          // (3) Get an iterator.
        while (interator.hasNext()) {                     // (4) Loop
            Integer element = (Integer) interator.next(); // (5) The next element
            int value = element.intValue();
            if (value < 1 || value > 10) // (6) Remove the element if
                interator.remove();      //     its value is not between 1 and 10.
        }

        System.out.println("After:  " + intList);    // (7)
    }
}
Output from the program:
Before: [9, 11, -4, 1, 13, 99, 1, 0]
After:  [9, 1, 1]

Example Deadlock

public class DeadLockDanger {

    String o1 = "Lock " ;                        // (1)
    String o2 = "Step ";                         // (2)

    Thread t1 = (new Thread("Printer1") {        // (3)
        public void run() {
            while(true) {
                synchronized(o1) {               // (4)
                    synchronized(o2) {           // (5)
                        System.out.println(o1 + o2);
                    }
                }
            }
        }
    });

    Thread t2 = (new Thread("Printer2") {        // (6)
        public void run() {
            while(true) {
                synchronized(o2) {               // (7)
                    synchronized(o1) {           // (8)
                        System.out.println(o2 + o1);
                    }
                }
            }
        }
    });

    public static void main(String[] args) {
        DeadLockDanger dld = new DeadLockDanger();
        dld.t1.start();
        dld.t2.start();
    }
}
Possible output from the program:
...
Step Lock
Step Lock
Lock Step
Lock Step
Lock Step
...

Example Thread Termination

class Worker implements Runnable {                              // (1)
    private Thread theThread;                                   // (2)

    public void kickStart() {                                   // (3)
        if (theThread == null) {
            theThread = new Thread(this);
            theThread.start();
        }
    }

    public void terminate() {                                   // (4)
        theThread = null;
    }

    public void run() {                                         // (5)
        while (theThread == Thread.currentThread()) {           // (6)
            System.out.println("Going around in loops.");
        }
    }
}

public class Controller {
    public static void main(String[] args) {                    // (7)
        Worker worker = new Worker();                           // (8)
        worker.kickStart();                                     // (9)
        Thread.yield();                                         // (10)
        worker.terminate();                                     // (11)
    }
}
Possible output from the program:
Going around in loops.
Going around in loops.
Going around in loops.
Going around in loops.
Going around in loops.

Example Waiting and Notifying

class StackImpl {
    private Object[] stackArray;
    private volatile int topOfStack;

    StackImpl (int capacity) {
        stackArray = new Object[capacity];
        topOfStack = -1;
    }

    public synchronized Object pop() {
        System.out.println(Thread.currentThread() + ": popping");
        while (isEmpty())
            try {
                System.out.println(Thread.currentThread() + ": waiting to pop");
                wait();                             // (1)
            } catch (InterruptedException e) { }
        Object obj = stackArray[topOfStack];
        stackArray[topOfStack--] = null;
        System.out.println(Thread.currentThread() + ": notifying after pop");
        notify();                                   // (2)
        return obj;
    }

    public synchronized void push(Object element) {
        System.out.println(Thread.currentThread() + ": pushing");
        while (isFull())
            try {
                System.out.println(Thread.currentThread() + ": waiting to push");
                wait();                             // (3)
            } catch (InterruptedException e) { }
        stackArray[++topOfStack] = element;
        System.out.println(Thread.currentThread() + ": notifying after push");
        notify();                                   // (4)
    }

    public boolean isFull() { return topOfStack >= stackArray.length -1; }
    public boolean isEmpty() { return topOfStack < 0; }
}

abstract class StackUser extends Thread {           // (5) Stack user

    protected StackImpl stack;                      // (6)

    StackUser(String threadName, StackImpl stack) {
        super(threadName);
        this.stack = stack;
        System.out.println(this);
        setDaemon(true);                            // (7) Daemon thread
        start();                                    // (8) Start this thread.
    }
}
class StackPopper extends StackUser {               // (9) Popper
    StackPopper(String threadName, StackImpl stack) {
        super(threadName, stack);
    }
    public void run() { while (true) stack.pop(); }
}

class StackPusher extends StackUser {               // (10) Pusher
    StackPusher(String threadName, StackImpl stack) {
        super(threadName, stack);
    }
    public void run() { while (true) stack.push(new Integer(1)); }
}

public class WaitAndNotifyClient {
    public static void main(String[] args)
           throws InterruptedException {            // (11)

        StackImpl stack = new StackImpl(5);

        new StackPusher("A", stack);
        new StackPusher("B", stack);
        new StackPopper("C", stack);
        System.out.println("Main Thread sleeping.");
        Thread.sleep(1000);
        System.out.println("Exit from Main Thread.");
    }
}
Possible output from the program:
Thread[A,5,main]
Thread[B,5,main]
Thread[C,5,main]
Main Thread sleeping.
...
Thread[A,5,main]: pushing
Thread[A,5,main]: waiting to push
Thread[B,5,main]: pushing
Thread[B,5,main]: waiting to push
Thread[C,5,main]: popping
Thread[C,5,main]: notifying after pop
Thread[A,5,main]: notifying after push
Thread[A,5,main]: pushing
Thread[A,5,main]: waiting to push
Thread[B,5,main]: waiting to push
Thread[C,5,main]: popping
Thread[C,5,main]: notifying after pop
Thread[A,5,main]: notifying after push
...
Thread[B,5,main]: notifying after push
...
Exit from Main Thread.
...

Example Mutual Exclusion

class StackImpl {                                   // (1)
    private Object[] stackArray;
    private int topOfStack;

    public StackImpl(int capacity) {
        stackArray = new Object[capacity];
        topOfStack = -1;
    }

    public boolean push(Object element) {              // (2a) non-synchronized
//  public synchronized boolean push(Object element) { // (2b) synchronized
        if (isFull()) return false;
        ++topOfStack;
        try { Thread.sleep(1000); } catch (Exception ex) { } // (3) Sleep a little.
        stackArray[topOfStack] = element;
        return true;
    }

    public Object pop() {                           // (4a) non-synchronized
//  public synchronized Object pop() {              // (4b) synchronized
        if (isEmpty()) return null;
        Object obj = stackArray[topOfStack];
        stackArray[topOfStack] = null;
        try { Thread.sleep(1000); } catch (Exception ex) { } // (5) Sleep a little.
        topOfStack--;
        return obj;
    }
    public boolean isEmpty() { return topOfStack < 0; }
    public boolean isFull()  { return topOfStack >= stackArray.length - 1; }
}

public class Mutex {
    public static void main(String[] args) {

        final StackImpl stack = new StackImpl(20);  // (6) Shared by the threads.

        (new Thread("Pusher") {                     // (7) Thread no. 1
            public void run() {
                for(;;) {
                    System.out.println("Pushed: " +
                        stack.push(new Integer(2003)));
                }
            }
        }).start();

        (new Thread("Popper") {                     // (8) Thread no. 2
            public void run() {
                for(;;) {
                    System.out.println("Popped: " + stack.pop());
                }
            }
        }).start();

        System.out.println("Exit from main().");
    }
}
Possible output from the program:
Exit from main().
...
Pushed: true
Popped: 2003
Popped: 2003
Popped: null
...
Popped: null
java.lang.ArrayIndexOutOfBoundsException: -1
        at StackImpl.push(Mutex.java:15)
        at Mutex$1.run(Mutex.java:41)
Popped: null
Popped: null
...

Example Extending the Thread Class

class Counter extends Thread {

    private int currentValue;

    public Counter(String threadName) {
        super(threadName);                       // (1) Initialize thread.
        currentValue = 0;
        System.out.println(this);
        start();                                 // (2) Start this thread.
    }

    public int getValue() { return currentValue; }
    public void run() {                          // (3) Override from superclass.
        try {
            while (currentValue < 5) {
                System.out.println(getName() + ": " + (currentValue++));
                Thread.sleep(250);               // (4) Current thread sleeps.
            }
        } catch (InterruptedException e) {
            System.out.println(getName() + " interrupted.");
        }
        System.out.println("Exit from thread: " + getName());
    }
}

public class Client {
    public static void main(String[] args) {

        System.out.println("Method main() runs in thread " +
                Thread.currentThread().getName());   // (5) Current thread

        Counter counterA = new Counter("Counter A"); // (6) Create a thread.
        Counter counterB = new Counter("Counter B"); // (7) Create a thread.

        System.out.println("Exit from main() method.");
    }
}
Possible output from the program:
Method main() runs in thread main
Thread[Counter A,5,main]
Thread[Counter B,5,main]
Exit from main() method.
Counter A: 0
Counter B: 0
Counter A: 1
Counter B: 1
Counter A: 2
Counter B: 2
Counter A: 3
Counter B: 3
Counter A: 4
Counter B: 4
Exit from thread: Counter A
Exit from thread: Counter B

Implementing the Runnable Interface

class Counter implements Runnable {

    private int currentValue;

    private Thread worker;

    public Counter(String threadName) {
        currentValue = 0;
        worker = new Thread(this, threadName);   // (1) Create a new thread.
        System.out.println(worker);
        worker.start();                          // (2) Start the thread.
    }

    public int getValue() { return currentValue; }

    public void run() {                          // (3) Thread entry point
        try {
            while (currentValue < 5) {
                System.out.println(worker.getName() + ": " + (currentValue++));
                Thread.sleep(250);               // (4) Current thread sleeps.
            }
        } catch (InterruptedException e) {
            System.out.println(worker.getName() + " interrupted.");
        }
        System.out.println("Exit from thread: " + worker.getName());
    }
}

public class Client {
    public static void main(String[] args) {
        Counter counterA = new Counter("Counter A"); // (5) Create a thread.

        try {
            int val;
            do {
                val = counterA.getValue();       // (6) Access the counter value.
                System.out.println("Counter value read by main thread: " + val);
                Thread.sleep(1000);              // (7) Current thread sleeps.
            } while (val < 5);
        } catch (InterruptedException e) {
            System.out.println("main thread interrupted.");
        }

        System.out.println("Exit from main() method.");
    }
}
Possible output from the program:
Thread[Counter A,5,main]
Counter value read by main thread: 0
Counter A: 0
Counter A: 1
Counter A: 2
Counter A: 3
Counter value read by main thread: 4
Counter A: 4
Exit from thread: Counter A
Counter value read by main thread: 5
Exit from main() method.

Thread Important Objective Questions - Part 3


8 Which one of these events will cause a thread to die?

Select the one correct answer.

The method sleep() is called.

The method wait() is called.

Execution of the start() method ends.

Execution of the run() method ends.

Execution of the thread's constructor ends.

9 Which statements are true about the following code?

public class Joining {
    static Thread createThread(final int i, final Thread t1) {
        Thread t2 = new Thread() {
            public void run() {
                System.out.println(i+1);
                try {
                    t1.join();
                } catch (InterruptedException e) {
                }
                System.out.println(i+2);
            }
        };
        System.out.println(i+3);
        t2.start();
        System.out.println(i+4);
        return t2;
    }

    public static void main(String[] args) {
        createThread(10, createThread(20, Thread.currentThread()));
    }
}

Select the two correct answers.

The first number printed is 13.

The number 14 is printed before the number 22.

The number 24 is printed before the number 21.

The last number printed is 12.

The number 11 is printed before the number 23.

10 What can be guaranteed by calling the method yield()?

Select the one correct answer.

All lower priority threads will be granted CPU time.

The current thread will sleep for some time while some other threads run.

The current thread will not continue until other threads have terminated.

The thread will wait until it is notified.

None of the above.

11 Where is the notify() method defined?

Select the one correct answer.

Thread

Object

Applet

Runnable

12 How can the priority of a thread be set?

Select the one correct answer.

By using the setPriority() method in the class Thread.

By passing the priority as a parameter to the constructor of the thread.

Both of the above.

None of the above.

13 Which statements are true about locks?

Select the two correct answers.

A thread can hold more than one lock at a time.

Invoking wait() on a Thread object will relinquish all locks held by the thread.

Invoking wait() on an object whose lock is held by the current thread will relinquish the lock.

Invoking notify() on a object whose lock is held by the current thread will relinquish the lock.

Multiple threads can hold the same lock at the same time.

14 What will be the result of invoking the wait() method on an object without ensuring that the current thread holds the lock of the object?

Select the one correct answer.

The code will fail to compile.

Nothing special will happen.

An IllegalMonitorStateException will be thrown if the wait() method is called while the current thread does not hold the lock of the object.

The thread will be blocked until it gains the lock of the object.

15 Which of these are plausible reasons why a thread might be alive, but still not be running?

Select the four correct answers.

The thread is waiting for some condition as a result of a wait() call.

The execution has reached the end of the run() method.

The thread is waiting to acquire the lock of an object in order to execute a certain method on that object.

The thread does not have the highest priority and is currently not executing.

The thread is sleeping as a result of a call to the sleep() method.


Thread Important Objective Questions - Part 2


7 Given the following program, which statement is true?

public class MyClass extends Thread {
    static Object lock1 = new Object();
    static Object lock2 = new Object();

    static volatile int i1, i2, j1, j2, k1, k2;

    public void run() { while (true) { doit(); check(); } }

    void doit() {
        synchronized(lock1) { i1++; }
        j1++;
        synchronized(lock2) { k1++; k2++; }
        j2++;
        synchronized(lock1) { i2++; }
    }

    void check() {
        if (i1 != i2) System.out.println("i");
        if (j1 != j2) System.out.println("j");
        if (k1 != k2) System.out.println("k");
    }

    public static void main(String[] args) {
        new MyClass().start();
        new MyClass().start();
    }
}

Select the one correct answer.

The program will fail to compile.

One cannot be certain whether any of the letters i, j, and k will be printed during execution.

One can be certain that none of the letters i, j, and k will ever be printed during execution.

One can be certain that the letters i and k will never be printed during execution.

One can be certain that the letter k will never be printed during execution.


Thread Important Objective Questions - Part 1



1

Which is the correct way to start a new thread?

Select the one correct answer.

    Just create a new Thread object. The thread will start automatically.

    Create a new Thread object and call the method begin().

    Create a new Thread object and call the method start().

    Create a new Thread object and call the method run().

    Create a new Thread object and call the method resume().

2    

When extending the Thread class to provide a thread's behavior, which method should be overridden?

Select the one correct answer.

    begin()

    start()

    run()

    resume()

    behavior()



Which statements are true?

Select the two correct answers.

    The class Thread is abstract.

    The class Thread implements Runnable.

    Classes implementing the Runnable interface must define a method named start.

    Calling the method run() on an object implementing Runnable will create a new thread.

    A program terminates when the last non-daemon thread ends.

4

What will be the result of attempting to compile and run the following program?

public class MyClass extends Thread {
    public MyClass(String s) { msg = s; }
    String msg;
    public void run() {
        System.out.println(msg);
    }

    public static void main(String[] args) {
        new MyClass("Hello");
        new MyClass("World");
    }
}

Select the one correct answer.

    The program will fail to compile.

    The program will compile without errors and will print Hello and World, in that order, every time the program is run.

    The program will compile without errors and will print a never-ending stream of Hello and World.

    The program will compile without errors and will print Hello and World when run, but the order is unpredictable.

    The program will compile without errors and will simply terminate without any output when run.