Question 14
Back to Exercise
What is the output of the following Java program?
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!