Java Programming - Threads - Discussion


What will be the output of the program?

class MyThread extends Thread 
    public static void main(String [] args) 
        MyThread t = new MyThread();
        Thread x = new Thread(t);
        x.start(); /* Line 7 */
    public void run() 
        for(int i = 0; i < 3; ++i) 
            System.out.print(i + "..");

[A]. Compilation fails.
[B]. 1..2..3..
[C]. 0..1..2..3..
[D]. 0..1..2..

Answer: Option D


The thread MyThread will start and loop three times (from 0 to 2).

Option A is incorrect because the Thread class implements the Runnable interface; therefore, in line 7, Thread can take an object of type Thread as an argument in the constructor.

Option B and C are incorrect because the variable i in the for loop starts with a value of 0 and ends with a value of 2.

Neha said: (Jul 7, 2011)  
But in loop there is ++i, so value of I ll be increase before it print. Thus in my opinion the ans is B.

Akshay said: (Apr 10, 2012)  
Yes, agree with Neha. As it is ++i it will print from 1 and output will be 1. 2.

Rahul said: (Jun 30, 2013)  
No,I disagree with @Akhay because here the control is as follows:

1. Goes to int i=0;
2. Then to i<3;
3. Body part will be executed.
4. Finally ++i will be executed.

So, i++ or ++i both will give same result i.e 0..1..2.

Harsh said: (Mar 1, 2014)  
But the thing is before printing the value of i, it is incremented because of ++i. So according to me the answer is B.

Kamlesh Choubey said: (Sep 15, 2015)  
After condition check control always goes to body part directly and after body execution it increments the value.

Png said: (Sep 18, 2015)  
Read basics of for loop. @Rahul is correct.

John said: (Dec 2, 2015)  
Is it possible to construct a Thread with an instance of Thread as an argument?

Ashu said: (Jan 10, 2016)  
In main method the method start is called run is not even called then. How is D correct?

Anonymous said: (Jul 3, 2016)  
Guys the class mythread doesn't implement the runnable here in the code it extends the thread class.

Neha Singh Chauhan said: (Aug 11, 2016)  
Since the value of x < 4

Therefore, it will print 0 1 2 3 only.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.