Java Daily, Quiz 6

Welcome to Java daily quiz 6 of Java daily quiz series, you can test yourself with this Java quiz. The answer and explanation are given at the end for your reference.
Check out all the Java daily quiz questions at https://www.javaguides.net/p/java-daily-quiz.html.
Check out my YouTube channel at https://www.youtube.com/c/javaguides.

What is the output of the following program?

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("In run method; thread name is: " + Thread.currentThread().getName());
    }
}

public class ThreadTest {

    public static void main(String args[]) {
        Thread myThread = new MyThread();
        myThread.run(); // #1
        System.out.println("In main method; thread name is: " + Thread.currentThread().getName());
    }
}
a) The program results in a compiler error at statement #1.
b) The program results in a runtime exception.
c) The program prints the following:
     In run method; thread name is: main
     In main method; thread name is: main
d) The program prints:
    In the run method; the thread name is: thread-0
    In the main method; the thread name is: main

Answer

c)
The program prints the following:
In run method; thread name is: main
In main method; thread name is: main
Explanation: The correct way to invoke a thread is to call the start() method on a Thread object. If you directly call the run() method, the method will run just like any other method (in other words, it will execute sequentially in the same thread without running as a separate thread).
Check out all the Java daily quiz questions at https://www.javaguides.net/p/java-daily-quiz.html.
Check out my YouTube channel at https://www.youtube.com/c/javaguides.

Comments