SCJP : Thread and Concurrency Mock Exam Practice Questions
Questions no -1
What is the output for the below code ?
public class B extends Thread{
public static void main(String argv[]){
B b = new B();
b.run();
}
public void start(){
for (int i = 0; i < 10; i++){
System.out.println("Value of i = " + i);
}
}
}
options
A)A compile time error indicating that no run method is defined for the Thread class
B)A run time error indicating that no run method is defined for the Thread class
C)Clean compile and at run time the values 0 to 9 are printed out
D)Clean compile but no output at runtime
Correct answer is : D
Explanations : This is a bit of a sneaky one as I have swapped around the names of the methods you need to define and call when running a thread. If the for loop were defined in a method called public void run() and the call in the main method had been to b.start() The list of values from 0 to 9 would have been output.
Questions no -2
What is the output for the below code ?
public class Test extends Thread{
static String sName = "good";
public static void main(String argv[]){
Test t = new Test();
t.nameTest(sName);
System.out.println(sName);
}
public void nameTest(String sName){
sName = sName + " idea ";
start();
}
public void run(){
for(int i=0;i < 4; i++){
sName = sName + " " + i;
}
}
}
options
A)good
B)good idea
C)good idea good idea
D)good 0 good 0 1
Correct answer is : A
Explanations : Change value in local methods wouldn’t change in global in case of String ( because String object is immutable).
Questions no -3
What is the output for the below code ?
public class Test{
public static void main(String argv[]){
Test1 pm1 = new Test1("One");
pm1.run();
Test1 pm2 = new Test1("Two");
pm2.run();
}
}
class Test1 extends Thread{
private String sTname="";
Test1(String s){
sTname = s;
}
public void run(){
for(int i =0; i < 2 ; i++){
try{
sleep(1000);
}catch(InterruptedException e){}
yield();
System.out.println(sTname);
}
}
}
options
A)Compile error
B)One One Two Two
C)One Two One Two
D)One Two
Correct answer is : B
Explanations : If you call the run method directly it just acts as any other method and does not return to the calling code until it has finished. executing
Questions no -4
What is the output for the below code ?
public class Test extends Thread{
public static void main(String argv[]){
Test b = new Test();
b.start();
}
public void run(){
System.out.println("Running");
}
}
options
A)Compilation clean and run but no output
B)Compilation and run with the output "Running"
C)Compile time error with complaint of no Thread import
D)Compile time error with complaint of no access to Thread package
Correct answer is : B
Explanations :
The Thread class is part of the core java.lang package and does not need any explicit import statement.
|