Thread Question -JQ++

Arun Pai

Ranch Hand

Posts: 143

posted 15 years ago

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

Posts: 3244

posted 15 years ago

Arun What is your question?

Dave

Arun Pai

Ranch Hand

Posts: 143

posted 15 years ago

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

Posts: 356

posted 15 years ago

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. Vanitha

Yes! 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. HTH, - Manish

Anthony Villanueva

Ranch Hand

Posts: 1055

posted 15 years ago

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. -anthony