Interview Questions

Output question 13.

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

73. Output question 13.

package o13_k15;
class Class2 {
void method2(String name) {
for (int x = 1; x <=2; x++) {
System.out.println(Thread.currentThread().getName());
}
}
}

public class MyClass implements Runnable {
Class2 obj2;
public static void main(String[] args) {
new MyClass().method1();
}
void method1() {
obj2 = new Class2();
new Thread(new MyClass()).start();
new Thread(new MyClass()).start();
}
public void run() {
obj2.method2(Thread.currentThread().getName());
}
}



Answer.
Program will face NullPointerException at Class2 obj2, we must make it static. As new Thread(new MyClass()).start(); creates thread on new instance of MyClass.
If Class2 obj2 is made static, than Thread-0 and Thread-1 will be printed twice but in unpredictable order.

So, output will be different in subsequent executions,(as shown below)-


/*OUTPUT
Thread-1
Thread-1
Thread-0
Thread-0
*/
/*OUTPUT
Thread-0
Thread-1
Thread-1
Thread-0
*/

(Continued on next question...)

Other Interview Questions