Thread.currentThread().sleep(...) usage — does this code compile and what happens? class Test { public static void main(String [] args) { printAll(args); } public static void printAll(String[] lines) { for (int i = 0; i < lines.length; i++) { System.out.println(lines[i]); Thread.currentThread().sleep(1000); } } } Assume standard Java SE rules.
-
AEach String in the array lines will output, with a 1-second pause.
-
BEach String in the array lines will output, with no pause in between because this method is not executed in a Thread.
-
CEach String in the array lines will output, and there is no guarantee there will be a pause because currentThread() may not retrieve this thread.
-
DThis code will not compile.
Answer
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.