1Z0-819 · Question #34
Given: 1. public class Main { 2. public static void greet(String... args) { 3. System.out.print("Hello "); 4. for (String arg : args) { 5. System.out.println(arg); 6. } 7. } 8. public static void…
The correct answer is D. Hello. Calling a static method through a null reference in Java does not throw a NullPointerException - the JVM resolves static method calls using the declared type of the variable (Main), not the object it references. So m.greet() is silently treated as Main.greet(), and since no…
Question
- public class Main {
- public static void greet(String... args) {
- System.out.print("Hello ");
- for (String arg : args) {
- System.out.println(arg);
- }
- }
- public static void main(String[] args) {
- Main m = null;
- m.greet();
- }
- } What is the result?
Options
- AA NullPointerException is thrown at line 4.
- BNullPointerException is thrown at line 10.
- CA compilation error occurs.
- DHello
How the community answered
(34 responses)- A15% (5)
- B3% (1)
- C9% (3)
- D74% (25)
Explanation
Calling a static method through a null reference in Java does not throw a NullPointerException - the JVM resolves static method calls using the declared type of the variable (Main), not the object it references. So m.greet() is silently treated as Main.greet(), and since no arguments are passed, args is an empty array, the loop body never executes, and only "Hello " is printed.
Why the distractors fail:
- A is wrong because
argsis an empty array (not null), so the enhanced for-loop simply doesn't iterate - no NPE at line 4. - B is wrong because NPE only occurs when you dereference an instance member (field or instance method) on null; static methods are dispatched by compile-time type, bypassing the null reference entirely.
- C is wrong because Java allows calling static methods via an instance reference - it compiles fine (though it's considered bad style and may generate a warning).
Memory tip: Think "static = class, not object." If the method is static, the object it's called on is irrelevant - even null works, because the JVM goes straight to the class definition.
Topics
Community Discussion
No community discussion yet for this question.