File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Question -JQ++ Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Question -JQ++" Watch "Thread Question -JQ++" New topic

Thread Question -JQ++

Arun Pai
Ranch Hand

Joined: Mar 11, 2002
Posts: 143
Question ID :1002727540585
Consider the following code:
class MyRunnable implements Runnable
public static void main(String[] args)
new Thread( new MyRunnable(2) ).start();
public void run(int n)
for(int i=0; i<n; i++)
System.out.println("Hello World");
What will be the output when this program is compiled and run from the command line?
1. will print Hello World once.
2. will print Hello World twice.
3. It will not compile.
4. It will compile but throw runtime exception.
5. It will compile without any output.
answer is 3, will not compile with explanation below. I answered as 2 and was trapped
When a non-abstract class implements Runnable interface, it must implement public void run() method. (run With no parameters). In this case, this class has a run method but it takes an int as a parameter.
Moreover, there is no constructor for this class that take an int. So new MyRunnable(2) is invalid.
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
What is your question?

Arun Pai
Ranch Hand

Joined: Mar 11, 2002
Posts: 143
Hi Dave ,
Do we get questions like these , JQ++ has categorised this question as easy. But it is demoralising to see these easy questions being answered wrongly. MyRunnable does implement the run() method but on carefull checking again you will be surprised to have overlooked the method signature. MyRunnable should provide a default constructor MyRunnable() but unable to handle MyRunnable(int).
Vanitha Sugumaran
Ranch Hand

Joined: Apr 11, 2001
Posts: 356
Hi Arun,
Yes, we may get some questions like this on exam. Don't worry if you get it wrong this time, you will be careful next time. You will get used to it.
You can over Maha Anna's traps to be aware in the exam, it is very helpful.
Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2591

You can definitely expect questions of this level of difficulty in the real exam. In fact I had few tougher ones on threads as well.
- Manish
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
A programming language is more precise than a natural language, hence it demands more attention. The devil is truly in the details.
In real-life code, some of the deadliest bugs are the ones that hide in plain sight.
I agree. Here's the link:
subject: Thread Question -JQ++
It's not a secret anymore!