LearnFrenzy
Sign in Take a free test

Methods and Recursion · Predict the Output · Question 14

Passing null to overloaded methods Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
public class Main {
    static String p(Object o) { return "Object"; }
    static String p(String s) { return "String"; }

    public static void main(String[] args) {
        Object asObject = "hello";
        System.out.println(p(null) + " " + p("hi") + " " + p(asObject) + " " + p((Object) null));
    }
}
  • A String String Object Object Correct
  • B Object String String Object
  • C String String String Object
  • D Compilation error
Correct Answer: Option A

Overloads are chosen at compile time from the static type: null matches the more specific String; a variable declared as Object picks p(Object) even if it holds a String.

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