NullPointerException vs String.valueOf in Java

👉 Question: What will be the output? String str = null; System.out.println(str.valueOf("hello")); System.out.println(str.toString()); 👉 Most developers say: “Both will throw NullPointerException” ❌ 👉 Correct Answer: hello // then exception 😮 💡 Why? ✔ "String.valueOf("hello")" 👉 It’s a static method 👉 Called using class, not object (compiler allows this syntax) 👉 So it works fine ✅ ✔ "str.toString()" 👉 Called on a null reference 👉 JVM throws ❌ NullPointerException 🔥 Important Insight: String s = null; System.out.println(String.valueOf(s)); // prints "null" ✔ Safe way to convert null to String ✔ Avoids NullPointerException 💬 Interview Tip: Explain static vs instance method behavior with null reference — interviewer will be impressed. #Java #InterviewTips #Coding #Developers #JavaConcepts #NPE

To view or add a comment, sign in

Explore content categories