Thread.currentThread().sleep(...) usage — does this code compile and what happens?\n\nclass Test \n{\n public static void main(String [] args) \n {\n printAll(args);\n }\n\n public static void printAll(String[] lines) \n {\n for (int i = 0; i < lines.length; i++)\n {\n System.out.println(lines[i]);\n Thread.currentThread().sleep(1000);\n }\n }\n}\n\nAssume standard Java SE rules.

Difficulty: Easy

Correct Answer: This code will not compile.

Explanation:


Introduction / Context:
The snippet uses Thread.currentThread().sleep(1000) to pause after printing each line. The key point is not whether sleep applies to the current thread (it does) but that sleep(long) throws InterruptedException, which must be handled or declared.



Given Data / Assumptions:

  • Thread.sleep(long) is a static method that throws InterruptedException.
  • Calling it via Thread.currentThread() is legal but still static.
  • Method printAll does not declare throws InterruptedException and does not catch it.


Concept / Approach:
Checked exceptions in Java must be caught or declared. Because sleep throws InterruptedException, the compiler requires a try/catch around the call or a throws clause in printAll (and in main if not handled there). Absent either, compilation fails regardless of whether a thread is explicitly created.



Step-by-Step Solution:

Encounter call to Thread.currentThread().sleep(1000).sleep(long) declares throws InterruptedException.No try/catch present; no throws on printAll.Compiler error: unreported exception InterruptedException; must be caught or declared to be thrown.


Verification / Alternative check:
Fix by writing: try { Thread.sleep(1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); }



Why Other Options Are Wrong:

  • They presume successful compilation and execution.
  • Whether or not the code runs in a separate thread is irrelevant to compile-time checked exception rules.


Common Pitfalls:
Forgetting that calling a static method through an expression does not change its checked-exception behavior.



Final Answer:
This code will not compile.

More Questions from Threads

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion