👉 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
NullPointerException vs String.valueOf in Java
More Relevant Posts
-
🚀 Java Backend Interview Series – Day 6 Think JVM basics are enough? Interviewers go one level deeper 👇 ☕ JVM Deep Dive: 1️⃣ What are different types of ClassLoaders in JVM? 2️⃣ Bootstrap vs Extension vs Application ClassLoader? 3️⃣ How does ClassLoader delegation work? 4️⃣ What is Execution Engine in JVM? 5️⃣ What is JIT Compiler and how does it improve performance? 6️⃣ What is Code Cache in JVM? 7️⃣ What happens step-by-step when a Java program runs? 8️⃣ How are objects created and stored in memory? 9️⃣ What are stack frames in JVM? 🔟 What causes memory leaks in Java and how to detect them? 💡 This is where average developers get filtered out 📌 Save this for revision 👇 Comment “NEXT” for Day 7 #Java #JVM #BackendDevelopment #InterviewPreparation #SoftwareEngineering #Developers #Tech #Coding
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽: 𝗜𝗻𝘁𝗲𝗴𝗲𝗿 𝗖𝗮𝗰𝗵𝗶𝗻𝗴 & 𝗪𝗿𝗮𝗽𝗽𝗲𝗿 𝗚𝗼𝘁𝗰𝗵𝗮𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱! Consider this simple code: class Main { public static void main(String[] args) { Integer a = 128; Integer b = 128; System.out.println(a == b); // ? System.out.println(a.equals(b)); // ? } } 🔍 Output: false true 🤔 Why does this happen? Java internally caches Integer objects in the range -128 to 127. ✅ Within range → same object → == is true ❌ Outside range → new objects → == is false 👉 == compares references (memory address) 👉 .equals() compares actual values 🔥 What about other wrapper classes? ✔ Cached Wrappers: Integer → -128 to 127 Byte → all values cached Short → -128 to 127 Long → -128 to 127 Character → 0 to 127 Boolean → only true & false (always cached) 👉 Example: Integer x = 100; Integer y = 100; System.out.println(x == y); // true ✅ ❗ NOT Cached: Float Double 👉 Example: Float f1 = 10.0f; Float f2 = 10.0f; System.out.println(f1 == f2); // false ❌ Double d1 = 10.0; Double d2 = 10.0; System.out.println(d1 == d2); // false ❌ 💥 Why no caching for Float/Double? Extremely large range of values Precision & representation complexity Not memory-efficient to cache 📌 Golden Rule: 👉 Never use == for wrapper comparison 👉 Always use .equals() or unbox to primitive 🚀 Pro Tip: You can extend Integer cache using JVM option: -XX:AutoBoxCacheMax=<value> 🎯 Interview Insight: This is a classic trap to test: Java memory concepts Autoboxing & unboxing Object vs primitive understanding 💡 Bonus Tip: Be careful with null values when unboxing: Integer i = null; int j = i; // Throws NullPointerException ⚠️ #Java #Programming #InterviewPrep #JavaTips #Coding #Developers #TechCareers
To view or add a comment, sign in
-
ConcurrentHashMap vs HashMap (Thread Safety Deep Dive) Most developers know: "HashMap" is NOT thread-safe "ConcurrentHashMap" is thread-safe But interviews go deeper Interview-Level Insights - Why "HashMap" fails in multithreading? - What is race condition? - How "ConcurrentHashMap" avoids full locking? - Difference between synchronizedMap vs ConcurrentHashMap - Internal working: CAS (Compare-And-Swap) --- Code Example Map<Integer, String> map = new HashMap<>(); // Not thread-safe new Thread(() -> map.put(1, "A")).start(); new Thread(() -> map.put(1, "B")).start(); // Can lead to inconsistent state Thread-safe version: Map<Integer, String> cmap = new ConcurrentHashMap<>(); new Thread(() -> cmap.put(1, "A")).start(); new Thread(() -> cmap.put(1, "B")).start(); Deep Concept (Must Know) Java 7: Segment-based locking Java 8+: Node-level locking + CAS This improves performance significantly under high concurrency. --- Common Interview Trap Why "ConcurrentHashMap" does NOT allow null? Because: - It avoids ambiguity between “key absent” vs “key mapped to null” in concurrent reads --- #helpful If interviewer asks: “How to make HashMap thread-safe?” Answer: - "Collections.synchronizedMap()" (basic) - OR use "ConcurrentHashMap" (preferred in real systems). Challenge Can you explain how read operations in ConcurrentHashMap are lock-free? What happens during resize in concurrent environment? Let’s discuss in comment ? #Java #Multithreading #ConcurrentHashMap #DSA #InterviewPrep #BackendDevelopment #CodingJourney
To view or add a comment, sign in
-
-
✅ Solved: Majority Element — LeetCode | Boyer-Moore Voting Algorithm Just got accepted on all 53/53 test cases with 2ms runtime (beats 70.59% of Java submissions)! 🎯 Here's what I learned: 🧠 The Problem: Given an array, find the element that appears MORE than ⌊n/2⌋ times. It's guaranteed to always exist. 💡 The Approach — Boyer-Moore Voting Algorithm: Instead of using a HashMap (O(n) space), I used a clever O(1) space trick: Treat elements like "votes" — keep a candidate and a counter When count hits 0 → pick the current element as the new candidate When you see the same element → count++ When you see a different element → count-- The majority element always "survives" the cancellation 🔑 Key Insight: The majority element appears more than all other elements COMBINED. So even if every other element "cancels" one occurrence of the majority, it still has votes left at the end. 🗓️ Submitted: April 13, 2026 If you're preparing for DSA interviews, this is a must-know pattern. It shows up in stream processing, voting systems, and distributed consensus problems too. Drop a comment if you've solved this a different way — I'd love to compare approaches! 🚀 #LeetCode #DSA #Java #BoyerMoore #CodingInterview #ProblemSolving #100DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Hello Everyone 👋 Good morning! If you’re preparing for Java interviews, understanding #JVMarchitecture is a game changer ✅ This visual breaks down how JVM works internally — the actual flow behind execution 👇 🔹 Class Loader Subsystem → Loads ".class" files into memory 🔹 Runtime Data Areas → Manages memory (Heap, Stack, Method Area, etc.) 🔹 Execution Engine → Runs bytecode using Interpreter + JIT Compiler 🔹 Garbage Collector → Automatically cleans unused memory 🔹 JNI & Native Libraries → Connect Java with native code 💡 Key takeaway: JVM is the reason behind “Write Once, Run Anywhere” — it converts bytecode into machine-specific execution while handling memory, security, and performance. 👉 Being able to explain JVM flow step-by-step (not just definitions) makes a strong impression. Hope this helps anyone revising core Java concepts 🙌 #Java #BackendDevelopment #InterviewPreparation #Programming #LetsLearnTogether #SimplifiedLearning
To view or add a comment, sign in
-
-
🚀 Can you find the first non-repeating character in a string? Here’s a simple Java approach 👇 String str = "aabbcd"; for(int i = 0; i < str.length(); i++) { boolean unique = true; for(int j = 0; j < str.length(); j++) { if(i != j && str.charAt(i) == str.charAt(j)) { unique = false; break; } } if(unique) { System.out.println(str.charAt(i)); break; } } 💡 Output: c 🔍 How it works: For each character, we check if it appears anywhere else in the string If it appears → not unique ❌ If it does NOT appear → first non-repeating character ✅ 👉 Time Complexity: O(n²) 💭 Interview Insight: This question is commonly asked to test your understanding of: ✔ Strings ✔ Nested loops ✔ Logic building 📌 Bonus: Can you optimize this to O(n) using HashMap? 👀 Drop your approach in comments 👇 #Java #Coding #DSA #InterviewPrep #Developers #100DaysOfCode
To view or add a comment, sign in
-
🚀 Java Backend Interview Series – Day 8 If you think Collections are easy… interviews will prove you wrong 👇 📦 Collections – Advanced: 1️⃣ Internal working of TreeMap? 2️⃣ TreeMap vs HashMap – when to use which? 3️⃣ What is WeakHashMap? When is it useful? 4️⃣ What are SoftReference and WeakReference? 5️⃣ What is immutable class? How to design one securely? 6️⃣ Shallow vs Deep Copy – differences and use cases? 7️⃣ Why can’t we create generic arrays in Java? 8️⃣ What is PriorityQueue and how does it work internally? 9️⃣ Difference between synchronized and concurrent collections? 🔟 How does ConcurrentHashMap achieve thread safety? 💡 Advanced collections = strong backend foundation 📌 Save this for revision 👇 Comment “NEXT” for Day 9 #Java #Collections #DataStructures #BackendDevelopment #InterviewPrep #SoftwareEngineering #Developers #Coding
To view or add a comment, sign in
-
Two Coding Questions which I have faced in recent interview. 1️⃣ Problem: String Transformation Question: Given a string like "hello world", the output should be #HelloWorld. 👉 The output string must start with # and each word should be converted to CamelCase. Solution (Java): public static String transform(String input) { return "#" + Arrays.stream(input.split("\\s+")) .map(word -> word.substring(0,1).toUpperCase() + word.substring(1)) .collect(Collectors.joining()); } public static void main(String[] args) { System.out.println(transform("hello world")); // #HelloWorld } Explanation: Split the string by spaces. Capitalize the first letter of each word. Join them together and prepend #. 2️⃣ Problem: Reverse Character Array In-Place Question: Given a character array, reverse the elements in place. Solution (Java): public static void reverse(char[] arr) { int left = 0, right = arr.length - 1; while (left < right) { char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } public static void main(String[] args) { char[] arr = {'h','e','l','l','o'}; reverse(arr); System.out.println(Arrays.toString(arr)); // [o, l, l, e, h] } Explanation: Use two pointers (left and right). Swap characters until they meet in the middle. This runs in O(n) time and uses O(1) extra space.
To view or add a comment, sign in
-
🔥 Day 2 of Java Exception Handling — Things got real today Moved beyond basics into edge cases that actually get asked in interviews. Here’s what I tackled: ⚡ Exception Propagation → How exceptions move up the call stack → What happens if no one handles it ⚡ final vs finally vs finalize → 3 similar names, completely different behavior ⚡ Try-with-resources → Why it’s better than finally → AutoCloseable & preventing resource leaks ⚡ Exceptions inside finally → The dangerous part: it can override other exceptions ⚡ printStackTrace vs getMessage vs toString → Different levels of debugging info 💥 Biggest takeaway: Some exceptions don’t just fail… They hide other exceptions 😳 🎯 Next: → Day 3: Output-based questions (Time to stop knowing and start thinking) #Java #SoftwareEngineering #InterviewPrep #Developers #LearningJourney
To view or add a comment, sign in
-
-
Spring Boot Interview Series — Post 6 Two ways to register beans in Spring. Very different purposes. @Component - class-level annotation. You put it on your own class. Spring detects it automatically via @ComponentScan and registers it as a bean. @Bean - method-level annotation inside a @Configuration class. You write a method that returns the object. Spring calls that method and registers the return value as a bean. Key differences: @Component - only works on classes you own and can modify. Less control over how the object is created. @Bean - works on any class including third party libraries. You have full control - pass constructor args, configure properties, customize before returning. When to use which: Use @Component for your own classes - DepositValidator, AuditLogger, JwtUtil. Use @Bean for third party classes you cannot annotate - KafkaTemplate, ObjectMapper, RestTemplate. Use @Bean when you need full control over how the object is constructed. #SpringBoot #Java #JavaDeveloper #BackendDevelopment #SpringFramework
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development