Challenge - 5 Problems
Method Overloading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of overloaded methods with different parameter types
What is the output of the following Java program?
Java
public class Test { public static void print(int x) { System.out.println("int: " + x); } public static void print(String x) { System.out.println("String: " + x); } public static void main(String[] args) { print(5); print("5"); } }
Attempts:
2 left
💡 Hint
Look at the parameter types used in each method call.
✗ Incorrect
The method print is overloaded with int and String parameters. The call print(5) matches the int version, and print("5") matches the String version.
❓ Predict Output
intermediateOverloading with different number of parameters
What will be printed when the following Java code runs?
Java
public class Demo { static void show() { System.out.println("No parameters"); } static void show(int a) { System.out.println("One parameter: " + a); } public static void main(String[] args) { show(); show(10); } }
Attempts:
2 left
💡 Hint
Check which method matches each call.
✗ Incorrect
The method show() with no parameters is called first, printing "No parameters". Then show(int) is called with 10, printing "One parameter: 10".
❓ Predict Output
advancedOverloading with widening and boxing
What is the output of this Java program?
Java
public class OverloadTest { static void test(long x) { System.out.println("long: " + x); } static void test(Integer x) { System.out.println("Integer: " + x); } public static void main(String[] args) { test(5); } }
Attempts:
2 left
💡 Hint
Consider how Java chooses between widening and boxing conversions.
✗ Incorrect
Java prefers widening over boxing when both are possible. The int literal 5 is widened to long, so test(long) is called.
❓ Predict Output
advancedOverloading with varargs and exact match
What will be printed when this Java code runs?
Java
public class VarargsTest { static void display(int a, int b) { System.out.println("Two ints: " + a + ", " + b); } static void display(int... nums) { System.out.println("Varargs: " + nums.length); } public static void main(String[] args) { display(1, 2); } }
Attempts:
2 left
💡 Hint
Exact matches are preferred over varargs.
✗ Incorrect
The call display(1, 2) matches the method with two int parameters exactly, so that method is called instead of the varargs version.
❓ Predict Output
expertOverloading with inheritance and null argument
What is the output of this Java program?
Java
public class InheritanceOverload { static void call(Object o) { System.out.println("Object version"); } static void call(String s) { System.out.println("String version"); } public static void main(String[] args) { call(null); } }
Attempts:
2 left
💡 Hint
When null is passed, Java chooses the most specific method.
✗ Incorrect
Between Object and String, String is more specific. So call(String) is chosen when null is passed.
