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
posted
0
Arun What is your question?
Dave
Arun Pai
Ranch Hand
Joined: Mar 11, 2002
Posts: 143
posted
0
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
posted
0
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
Joined: Mar 22, 2002
Posts: 1055
posted
0
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
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.