Object-Oriented Programming · Question 12 · Hard
What is the output of the following Java code?
static void m(Object o) { System.out.println("Object"); }
static void m(String s) { System.out.println("String"); }
// in main:
m(null);
- Object
- String
- Compilation error: ambiguous call
- NullPointerException at runtime
Answer and explanation
Answer: B. String
Explanation: null can be passed to both overloads, so Java chooses the most specific one. String is a subclass of Object, so m(String) is chosen and "String" is printed.
Previous: What is printed when new C() is executed? · Next: What is the output of the following Java code?
Practise object-oriented programming
Try a fresh set of object-oriented programming questions with an explanation after every answer, free and without signing up: Object-Oriented Programming practice. Or sit a full placement mock test.
More object-oriented programming questions
- In C++, how is the "diamond problem" (two copies of a common base class…
- Which pair of method declarations CANNOT both appear in the same Java class?
- What is printed when new C() is executed?
- What is the output of the following Java code?
- What is the output of the following Java code?
- Which SOLID principle states that objects of a subclass should be usable…
- A Logger class keeps a list of log entries in a private field and offers only…
- Inside an instance method or constructor in Java, which keyword refers to the…
- Inheritance, as in 'SavingsAccount extends Account', models which kind of…
- Creating an object of a class, for example with new Student() in Java, is…
More technical & programming practice
DBMS · SQL · Operating Systems · Computer Networks · Software Engineering · Cloud & DevOps · GenAI Basics · Pseudo-code
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge