Interview Questions

What will happen if we don’t override run method?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

37. What will happen if we don’t override run method?

This question will test your basic knowledge how start and run methods work internally in Thread Api.

When we call start() method on thread, it internally calls run() method with newly created thread. So, if we don’t override run() method newly created thread won’t be called and nothing will happen.

class MyThread extends Thread {
//don't override run() method
}
public class DontOverrideRun {
public static void main(String[] args) {
System.out.println("main has started.");
MyThread thread1=new MyThread();
thread1.start();
System.out.println("main has ended.");
}
}
/*OUTPUT
main has started.
main has ended.
*/


As we saw in output, we didn’t override run() method that’s why on calling start() method nothing happened.

(Continued on next question...)

Other Interview Questions