Java Interview Trap: Null with Method Overloading

🔥 Java Interview Trap – Null with Method Overloading 🔥 This one looks EASY… but breaks many developers in interviews 😏 👉 Question: public class Test { static void print(String str) { System.out.println("String"); } static void print(Object obj) { System.out.println("Object"); } public static void main(String[] args) { print(null); } } 👉 Output: String 💡 Why this happens? 👉 "null" can match any reference type But Java chooses the MOST SPECIFIC method - String is more specific than Object ✔️ - So "print(String)" is called 🚨 Now the REAL trap: 👉 Add this method: static void print(Integer i) { System.out.println("Integer"); } 👉 Now call: print(null); 💥 Result: Compilation Error ❌ 💡 Why error? 👉 Now Java is confused: - String OR Integer → both are equally specific 👉 So it becomes AMBIGUOUS 💥 Golden Rule: 👉 Java always picks MOST SPECIFIC method 👉 If confusion → COMPILE-TIME ERROR 🎯 Interview Tip: When you see "null" + overloading → think AMBIGUITY #Java #JavaInterview #CodingInterview #Developers #Programming #TechTips

To view or add a comment, sign in

Explore content categories