Java Programming - Threads - Discussion
Discussion Forum : Threads - Finding the output (Q.No. 18)
18.
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 + "..");
}
}
}
Answer: Option
Explanation:
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.
Discussion:
10 comments Page 1 of 1.
Neha singh chauhan said:
8 years ago
Since the value of x < 4
Therefore, it will print 0 1 2 3 only.
Therefore, it will print 0 1 2 3 only.
Anonymous said:
8 years ago
Guys the class mythread doesn't implement the runnable here in the code it extends the thread class.
Ashu said:
9 years ago
In main method the method start is called run is not even called then. How is D correct?
John said:
9 years ago
Is it possible to construct a Thread with an instance of Thread as an argument?
Png said:
9 years ago
Read basics of for loop. @Rahul is correct.
Kamlesh Choubey said:
9 years ago
After condition check control always goes to body part directly and after body execution it increments the value.
Harsh said:
1 decade ago
But the thing is before printing the value of i, it is incremented because of ++i. So according to me the answer is B.
Rahul said:
1 decade ago
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.
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.
Akshay said:
1 decade ago
Yes, agree with Neha. As it is ++i it will print from 1 and output will be 1. 2.
Neha said:
1 decade ago
But in loop there is ++i, so value of I ll be increase before it print. Thus in my opinion the ans is B.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers