public static synchronized void main(String[] args) throws InterruptedException { Thread t = new Thread(); t.start(); System.out.print("X"); t.wait(10000); System.out.print("Y"); } What is the result of this code?

  1. It prints X and never exits.

  2. The code does not compile.

  3. It prints XY with a 10-second delay between X and Y.

  4. An exception is thrown at runtime.


Correct Option: D

AI Explanation

To answer this question, let's go through the code step by step:

  1. The code starts by creating a new thread t and calling its start() method. This starts the thread and allows it to run concurrently with the main thread.

  2. After starting the thread, the code prints "X" using System.out.print("X").

  3. Next, the code calls the wait() method on the t thread object with a timeout of 10,000 milliseconds (10 seconds). This causes the main thread to wait for the t thread to notify it or until the timeout expires.

  4. Finally, the code prints "Y" using System.out.print("Y").

Now, let's analyze the options:

Option A) It prints X and never exits. This option is incorrect. While the code does print "X", it does not exit immediately. It waits for the t thread to notify it or until the timeout expires.

Option B) The code does not compile. This option is incorrect. The code is valid and compiles without any errors.

Option C) It prints XY with a 10-second delay between X and Y. This option is incorrect. The code does print "X", but it does not wait for exactly 10 seconds before printing "Y". The time it takes for the t thread to notify the main thread or for the timeout to expire is not guaranteed to be exactly 10 seconds.

Option D) An exception is thrown at runtime. This option is correct. The wait() method can only be called within a synchronized block or method. In the given code, the wait() method is called on the t thread object, but there is no synchronized block or method surrounding it. This will result in a java.lang.IllegalMonitorStateException being thrown at runtime.

Therefore, the correct answer is D) An exception is thrown at runtime.

Find more quizzes: