Finding The Output

Question 1 :

What will be the output of the program?

class MyThread extends Thread 
{
    MyThread() 
    {
        System.out.print(" MyThread");
    }
    public void run() 
    {
        System.out.print(" bar");
    }
    public void run(String s) 
    {
        System.out.println(" baz");
    }
}
public class TestThreads 
{
    public static void main (String [] args) 
    {
        Thread t = new MyThread() 
        {
            public void run() 
            {
                System.out.println(" foo");
            }
        };
        t.start();
    }
}


A). foo
B). MyThread foo
C). MyThread bar
D). foo bar
Answer : Option B

Explanation :

Option B is correct because in the first line of main we're constructing an instance of an anonymous inner class extending from MyThread. So the MyThread constructor runs and prints "MyThread". The next statement in main invokes start() on the new thread instance, which causes the overridden run() method (the run() method defined in the anonymous inner class) to be invoked, which prints "foo"


Question 2 :

What will be the output of the program?

class MyThread extends Thread 
{
    public static void main(String [] args) 
    {
        MyThread t = new MyThread();
        t.start();
        System.out.print("one. ");
        t.start();
        System.out.print("two. ");
    }
    public void run() 
    {
        System.out.print("Thread ");
    }
}


A). Compilation fails
B). An exception occurs at runtime.
C). It prints "Thread one. Thread two."
D). The output cannot be determined.
Answer : Option B

Explanation :

When the start() method is attempted a second time on a single Thread object, the method will throw an IllegalThreadStateException (you will not need to know this exception name for the exam). Even if the thread has finished running, it is still illegal to call start() again.


Question 3 :

What will be the output of the program?

class MyThread extends Thread 
{ 
    MyThread() {} 
    MyThread(Runnable r) {super(r); } 
    public void run() 
    { 
        System.out.print("Inside Thread ");
    } 
} 
class MyRunnable implements Runnable 
{ 
    public void run() 
    { 
        System.out.print(" Inside Runnable"); 
    } 
} 
class Test 
{  
    public static void main(String[] args) 
    { 
        new MyThread().start(); 
        new MyThread(new MyRunnable()).start(); 
    } 
}


A). Prints "Inside Thread Inside Thread"
B). Prints "Inside Thread Inside Runnable"
C). Does not compile
D). Throws exception at runtime
Answer : Option A

Explanation :

If a Runnable object is passed to the Thread constructor, then the run method of the Thread class will invoke the run method of the Runnable object.

In this case, however, the run method in the Thread class is overridden by the run method in MyThread class. Therefore the run() method in MyRunnable is never invoked.

Both times, the run() method in MyThread is invoked instead.


Question 4 :

What will be the output of the program?

class s1 implements Runnable 
{ 
    int x = 0, y = 0; 
    int addX() {x++; return x;} 
    int addY() {y++; return y;} 
    public void run() { 
    for(int i = 0; i < 10; i++) 
        System.out.println(addX() + " " + addY()); 
} 
    public static void main(String args[]) 
    { 
        s1 run1 = new s1(); 
        s1 run2 = new s1(); 
        Thread t1 = new Thread(run1); 
        Thread t2 = new Thread(run2); 
        t1.start(); 
        t2.start(); 
    } 
}


A). Compile time Error: There is no start() method
B). Will print in this order: 1 1 2 2 3 3 4 4 5 5...
C). Will print but not exactly in an order (e.g: 1 1 2 2 1 1 3 3...)
D). Will print in this order: 1 2 3 4 5 6... 1 2 3 4 5 6...
Answer : Option C

Explanation :

Both threads are operating on different sets of instance variables. If you modify the code of the run() method to print the thread name it will help to clarify the output:

public void run() 
{ 
for(int i = 0; i < 10; i++) 

System.out.println(
Thread.currentThread().getName() + ": " + addX() + " " + addY() 
); 
}


Question 5 :

What will be the output of the program?

public class Q126 implements Runnable 
{ 
    private int x; 
    private int y; 

    public static void main(String [] args) 
    { 
        Q126 that = new Q126(); 
        (new Thread(that)).start( ); /* Line 8 */
        (new Thread(that)).start( ); /* Line 9 */
    } 
    public synchronized void run( ) /* Line 11 */
    { 
        for (;;) /* Line 13 */
        { 
            x++; 
            y++; 
            System.out.println("x = " + x + "y = " + y); 
        } 
    } 
}


A). An error at line 11 causes compilation to fail
B). Errors at lines 8 and 9 cause compilation to fail.
C). The program prints pairs of values for x and y that might not always be the same on the same line (for example, "x=2, y=1")
D). The program prints pairs of values for x and y that are always the same on the same line (for example, "x=1, y=1". In addition, each value appears once (for example, "x=1, y=1" followed by "x=2, y=2")
Answer : Option D

Explanation :

The synchronized code is the key to answering this question. Because x and y are both incremented inside the synchronized method they are always incremented together. Also keep in mind that the two threads share the same reference to the Q126 object.

Also note that because of the infinite loop at line 13, only one thread ever gets to execute.


Question 6 :

What will be the output of the program?

class s1 extends Thread
{ 
    public void run() 
    { 
        for(int i = 0; i < 3; i++) 
        { 
            System.out.println("A"); 
            System.out.println("B"); 
        } 
    } 
} 
class Test120 extends Thread 
{ 
    public void run() 
    { 
        for(int i = 0; i < 3; i++) 
        { 
            System.out.println("C"); 
            System.out.println("D"); 
        } 
    } 
    public static void main(String args[]) 
        { 
        s1 t1 = new s1(); 
        Test120 t2 = new Test120(); 
        t1.start(); 
        t2.start(); 
    } 
}


A). Compile time Error There is no start() method
B). Will print in this order AB CD AB...
C). Will print but not be able to predict the Order
D). Will print in this order ABCD...ABCD...
Answer : Option C

Explanation :

We cannot predict the order in which threads are going to run.


Question 7 :

What will be the output of the program?

class s implements Runnable 
{ 
    int x, y; 
    public void run() 
    { 
        for(int i = 0; i < 1000; i++) 
            synchronized(this) 
            { 
                x = 12; 
                y = 12; 
            } 
        System.out.print(x + " " + y + " "); 
    } 
    public static void main(String args[]) 
    { 
        s run = new s(); 
        Thread t1 = new Thread(run); 
        Thread t2 = new Thread(run); 
        t1.start(); 
        t2.start(); 
    } 
}


A). DeadLock
B). It print 12 12 12 12
C). Compilation Error
D). Cannot determine output.
Answer : Option B

Explanation :

The program will execute without any problems and print 12 12 12 12.


Question 8 :

What will be the output of the program?

public class ThreadDemo 
{ 
    private int count = 1; 
    public synchronized void doSomething() 
    { 
        for (int i = 0; i < 10; i++) 
            System.out.println(count++); 
    } 
    public static void main(String[] args) 
    { 
        ThreadDemo demo = new ThreadDemo(); 
        Thread a1 = new A(demo); 
        Thread a2 = new A(demo); 
        a1.start(); 
        a2.start(); 
    } 
} 
class A extends Thread 
{ 
    ThreadDemo demo; 
    public A(ThreadDemo td) 
    { 
        demo = td; 
    } 
    public void run() 
    { 
        demo.doSomething(); 
    } 
}


A). It will print the numbers 0 to 19 sequentially
B). It will print the numbers 1 to 20 sequentially
C). It will print the numbers 1 to 20, but the order cannot be determined
D). The code will not compile.
Answer : Option B

Explanation :

You have two different threads that share one reference to a common object.

The updating and output takes place inside synchronized code.

One thread will run to completion printing the numbers 1-10.

The second thread will then run to completion printing the numbers 11-20.


Question 9 :

What will be the output of the program?

public class WaitTest 
{
    public static void main(String [] args) 
    {
        System.out.print("1 ");
        synchronized(args)
        {
            System.out.print("2 ");
            try 
            {
                    args.wait(); /* Line 11 */
            }
            catch(InterruptedException e){ }
        }
        System.out.print("3 ");
    }
}


A). It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 11.
B). 1 2 3
C). 1 3
D). 1 2
Answer : Option D

Explanation :

1 and 2 will be printed, but there will be no return from the wait call because no other thread will notify the main thread, so 3 will never be printed. The program is essentially frozen at line 11.

A is incorrect; IllegalMonitorStateException is an unchecked exception so it doesn't have to be dealt with explicitly.

B and C are incorrect; 3 will never be printed, since this program will never terminate because it will wait forever.


Question 10 :

What will be the output of the program?

public class SyncTest 
{
    public static void main (String [] args) 
    {
        Thread t = new Thread() 
        {
            Foo f = new Foo();
            public void run() 
            {
                f.increase(20);
            }
        };
    t.start();
    }
}
class Foo 
{
    private int data = 23;
    public void increase(int amt) 
    {
        int x = data;
        data = x + amt;
    }
}
and assuming that data must be protected from corruption, what—if anything—can you add to the preceding code to ensure the integrity of data?


A). Synchronize the run method.
B). Wrap a synchronize(this) around the call to f.increase().
C). The existing code will cause a runtime exception.
D). Synchronize the increase() method
Answer : Option D

Explanation :

Option D is correct because synchronizing the code that actually does the increase will protect the code from being accessed by more than one thread at a time.

Option A is incorrect because synchronizing the run() method would stop other threads from running the run() method (a bad idea) but still would not prevent other threads with other runnables from accessing the increase() method.

Option B is incorrect for virtually the same reason as A—synchronizing the code that calls the increase() method does not prevent other code from calling the increase() method.


Question 11 :

What will be the output of the program?

class Happy extends Thread 
{ 
    final StringBuffer sb1 = new StringBuffer(); 
    final StringBuffer sb2 = new StringBuffer(); 

    public static void main(String args[]) 
    { 
        final Happy h = new Happy(); 

        new Thread() 
        { 
            public void run() 
            { 
                synchronized(this) 
                { 
                    h.sb1.append("A"); 
                    h.sb2.append("B"); 
                    System.out.println(h.sb1); 
                    System.out.println(h.sb2); 
                } 
            } 
        }.start(); 

        new Thread() 
        { 
            public void run() 
            { 
                synchronized(this) 
                { 
                    h.sb1.append("D"); 
                    h.sb2.append("C"); 
                    System.out.println(h.sb2); 
                    System.out.println(h.sb1); 
                } 
            } 
        }.start(); 
    } 
}


A). ABBCAD
B). ABCBCAD
C). CDADACB
D). Output determined by the underlying platform.
Answer : Option D

Explanation :

Can you guarantee the order in which threads are going to run? No you can't. So how do you know what the output will be? The output cannot be determined.


Question 12 :

class Test 
{
    public static void main(String [] args) 
    {
        printAll(args);
    }

    public static void printAll(String[] lines) 
    {
        for(int i = 0; i < lines.length; i++)
        {
            System.out.println(lines[i]);
            Thread.currentThread().sleep(1000);
        }
    }
}
the static method Thread.currentThread() returns a reference to the currently executing Thread object. What is the result of this code?


A). Each String in the array lines will output, with a 1-second pause.
B). Each String in the array lines will output, with no pause in between because this method is not executed in a Thread.
C). Each String in the array lines will output, and there is no guarantee there will be a pause because currentThread() may not retrieve this thread.
D). This code will not compile.
Answer : Option D

Explanation :

D. The sleep() method must be enclosed in a try/catch block, or the method printAll() must declare it throws the InterruptedException.

A is incorrect, but it would be correct if the InterruptedException was dealt with.

B is incorrect, but it would still be incorrect if the InterruptedException was dealt with because all Java code, including the main() method, runs in threads.

C is incorrect. The sleep() method is static, so even if it is called on an instance, it still always affects the currently executing thread.


Question 13 :

What will be the output of the program?

class MyThread extends Thread 
{
    public static void main(String [] args) 
    {
        MyThread t = new MyThread(); /* Line 5 */
        t.run();  /* Line 6 */
    }

    public void run() 
    {
        for(int i=1; i < 3; ++i) 
        {
            System.out.print(i + "..");
        }
    }
}


A). This code will not compile due to line 5.
B). This code will not compile due to line 6.
C). 1..2..
D). 1..2..3..
Answer : Option C

Explanation :

Line 6 calls the run() method, so the run() method executes as a normal method should and it prints "1..2.."

A is incorrect because line 5 is the proper way to create an object.

B is incorrect because it is legal to call the run() method, even though this will not start a true thread of execution. The code after line 6 will not execute until the run() method is complete.

D is incorrect because the for loop only does two iterations.


Question 14 :

What will be the output of the program?

class Test116 
{ 
static final StringBuffer sb1 = new StringBuffer(); 
static final StringBuffer sb2 = new StringBuffer(); 
public static void main(String args[]) 
{ 
    new Thread() 
    { 
        public void run() 
        { 
            synchronized(sb1) 
            { 
                sb1.append("A"); 
                sb2.append("B"); 
            } 
        } 
    }.start(); 

    new Thread() 
    { 
        public void run() 
        { 
            synchronized(sb1) 
            { 
                sb1.append("C"); 
                sb2.append("D"); 
            } 
        } 
    }.start(); /* Line 28 */

    System.out.println (sb1 + " " + sb2); 
    } 
}


A). main() will finish before starting threads.
B). main() will finish in the middle of one thread.
C). main() will finish after one thread.
D). Cannot be determined.
Answer : Option D

Explanation :

Can you guarantee the order in which threads are going to run? No you can't. So how do you know what the output will be? The output cannot be determined.

add this code after line 28:

try { Thread.sleep(5000); } catch(InterruptedException e) { }

and you have some chance of predicting the outcome.


Question 15 :

What will be the output of the program?

public class ThreadTest extends Thread 
{ 
    public void run() 
    { 
        System.out.println("In run"); 
        yield(); 
        System.out.println("Leaving run"); 
    } 
    public static void main(String []argv) 
    { 
        (new ThreadTest()).start(); 
    } 
}


A). The code fails to compile in the main() method
B). The code fails to compile in the run() method
C). Only the text "In run" will be displayed
D). The text "In run" followed by "Leaving run" will be displayed
Answer : Option D

Question 16 :

What will be the output of the program?

public class Test107 implements Runnable 
{ 
    private int x; 
    private int y; 

    public static void main(String args[]) 
    {
        Test107 that = new Test107(); 
        (new Thread(that)).start(); 
        (new Thread(that)).start(); 
    } 
    public synchronized void run() 
    {
        for(int i = 0; i < 10; i++) 
        { 
            x++; 
            y++; 
            System.out.println("x = " + x + ", y = " + y); /* Line 17 */
        } 
    } 
} 


A). Compilation error.
B). Will print in this order: x = 1 y = 1 x = 2 y = 2 x = 3 y = 3 x = 4 y = 4 x = 5 y = 5... but the output will be produced by both threads running simultaneously.
C). Will print in this order: x = 1 y = 1 x = 2 y = 2 x = 3 y = 3 x = 4 y = 4 x = 5 y = 5... but the output will be produced by first one thread then the other. This is guaranteed by the synchronised code.
D). Will print in this order x = 1 y = 2 x = 3 y = 4 x = 5 y = 6 x = 7 y = 8...
Answer : Option C

Explanation :

Both threads are operating on the same instance variables. Because the code is synchronized the first thread will complete before the second thread begins. Modify line 17 to print the thread names:

System.out.println(Thread.currentThread().getName() + " x = " + x + ", y = " + y);


Question 17 :

What will be the output of the program?

public class Test 
{
    public static void main (String [] args) 
    {
        final Foo f = new Foo();
        Thread t = new Thread(new Runnable() 
        {
            public void run() 
            {
                f.doStuff();
            }
        });
        Thread g = new Thread() 
        {
            public void run() 
            {
                f.doStuff();
            }
        };
        t.start();
        g.start();
    }
}
class Foo 
{
    int x = 5;
    public void doStuff() 
    {
        if (x < 10) 
        {
            // nothing to do
            try 
            {
                wait();
                } catch(InterruptedException ex) { }
        } 
        else 
        {
            System.out.println("x is " + x++);
            if (x >= 10) 
            {
                notify();
            }
        }
    }
}


A). The code will not compile because of an error on notify(); of class Foo.
B). The code will not compile because of some other error in class Test.
C). An exception occurs at runtime.
D). It prints "x is 5 x is 6".
Answer : Option C

Explanation :

C is correct because the thread does not own the lock of the object it invokes wait() on. If the method were synchronized, the code would run without exception.

A, B are incorrect because the code compiles without errors.

D is incorrect because the exception is thrown before there is any output.


Question 18 :

What will be the output of the program?

class MyThread extends Thread 
{
    public static void main(String [] args) 
    {
        MyThread t = new MyThread();
        Thread x = new Thread(t);
        x.start(); /* Line 7 */
    }
    public void run() 
    {
        for(int i = 0; i < 3; ++i) 
        {
            System.out.print(i + "..");
        }
    }
}


A). Compilation fails.
B). 1..2..3..
C). 0..1..2..3..
D). 0..1..2..
Answer : Option D

Explanation :

The thread MyThread will start and loop three times (from 0 to 2).

Option A is incorrect because the Thread class implements the Runnable interface; therefore, in line 7, Thread can take an object of type Thread as an argument in the constructor.

Option B and C are incorrect because the variable i in the for loop starts with a value of 0 and ends with a value of 2.