LearnFrenzy
Sign in Take a free test

Static and Final Keywords · Predict the Output · Question 13

Calling a static method through a null reference Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 13 Back to Exercise

What is the output of the following Java program?

Main.java
class Util {
    static String hello() { return "hello"; }
    String hi() { return "hi"; }
}

public class Main {
    public static void main(String[] args) {
        Util u = null;
        System.out.print(u.hello() + " ");
        try {
            System.out.println(u.hi());
        } catch (NullPointerException e) {
            System.out.println("NPE");
        }
    }
}
  • A hello NPE Correct
  • B NPE
  • C hello hi
  • D Compilation error
Correct Answer: Option A

A static call is resolved by the declared type, so u is never dereferenced. The instance call needs an object and throws.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links