🔥 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
Java Interview Trap: Null with Method Overloading
More Relevant Posts
-
💥 Java Interview Question 👉 What are the different types of Thread Priorities in Java? 👉 And what is the default priority assigned by JVM? Many developers ignore this… but it’s a very common interview question 👇 . 🧠 Core Concept In Java, every thread has a priority that helps the JVM decide: 👉 Which thread should get more CPU time Thread priority is represented by numbers from 1 to 10 . 🔢 Types of Thread Priorities ✔ MIN_PRIORITY = 1 👉 Lowest priority thread ✔ NORM_PRIORITY = 5 👉 Default priority assigned by JVM ✔ MAX_PRIORITY = 10 👉 Highest priority thread ⚡ Important Rule 👉 By default, every new thread gets: 🔥 NORM_PRIORITY (5) Unless you manually change it ⚠️ Real-World Understanding 👉 Higher priority does NOT guarantee execution . Why? ✔ Thread scheduling depends on OS ✔ JVM uses priority as a hint, not a rule . 💻 Example Code 𝒄𝒍𝒂𝒔𝒔 𝑻𝒆𝒔𝒕 { 𝒑𝒖𝒃𝒍𝒊𝒄 𝒔𝒕𝒂𝒕𝒊𝒄 𝒗𝒐𝒊𝒅 𝒎𝒂𝒊𝒏(𝑺𝒕𝒓𝒊𝒏𝒈[] 𝒂𝒓𝒈𝒔) { 𝑻𝒉𝒓𝒆𝒂𝒅 𝒕1 = 𝒏𝒆𝒘 𝑻𝒉𝒓𝒆𝒂𝒅(); 𝑺𝒚𝒔𝒕𝒆𝒎.𝒐𝒖𝒕.𝒑𝒓𝒊𝒏𝒕𝒍𝒏(𝒕1.𝒈𝒆𝒕𝑷𝒓𝒊𝒐𝒓𝒊𝒕𝒚()); // 𝑫𝒆𝒇𝒂𝒖𝒍𝒕 = 5 𝒕1.𝒔𝒆𝒕𝑷𝒓𝒊𝒐𝒓𝒊𝒕𝒚(𝑻𝒉𝒓𝒆𝒂𝒅.𝑴𝑨𝑿_𝑷𝑹𝑰𝑶𝑹𝑰𝑻𝒀); 𝑺𝒚𝒔𝒕𝒆𝒎.𝒐𝒖𝒕.𝒑𝒓𝒊𝒏𝒕𝒍𝒏(𝒕1.𝒈𝒆𝒕𝑷𝒓𝒊𝒐𝒓𝒊𝒕𝒚()); // 10 } } 🎯 Interview Gold Answer 👉 “In Java, thread priority ranges from 1 to 10. The default priority is NORM_PRIORITY (5). However, thread scheduling is OS-dependent, so higher priority does not guarantee execution.” . 🚀 Why This Matters ✔ Helps understand thread scheduling ✔ Important for performance tuning ✔ Frequently asked in interviews . 👉 What is the default thread priority in Java? A) 1 B) 5 C) 10 💬 Comment your answer 👇 . 👉 Want more Java interview content? Comment “JAVA” 👇 👉 Follow for daily tech content 🚀 . . #Java #Multithreading #JavaDeveloper #Programming #SoftwareEngineering #CodingInterview #TechInterview #LearnJava #Developers #JavaInterview #Threading #Concurrency #Upskill #TechCareers
To view or add a comment, sign in
-
-
🔥 Java Interview Must-Know: == vs equals() vs hashCode() This is one of the most asked questions in interviews. 💡 Key Differences: ✔ == - Compares references - Works for primitives & objects ✔ equals() - Compares values - Defined in Object class - Can be overridden ✔ hashCode() - Used in hashing collections - Must be consistent with equals() 🔹 Important Rule: If two objects are equal → their hashCode must be same 🔹 Real Example: Map<String, String> map = new HashMap<>(); map.put(new String("key"), "value"); 👉 Without proper equals & hashCode → data retrieval may fail ⚠️ Common Mistake: Overriding equals() but not hashCode() Master this → You clear many Java interviews easily. #JavaInterview #HashMap #Java #CodingInterview #Developers
To view or add a comment, sign in
-
-
Just faced a classic Java backend interview question: "𝗛𝗼𝘄 𝗱𝗼𝗲𝘀 𝗖𝗼𝗻𝗰𝘂𝗿𝗿𝗲𝗻𝘁𝗛𝗮𝘀𝗵𝗠𝗮𝗽 𝘄𝗼𝗿𝗸 𝗶𝗻𝘁𝗲𝗿𝗻𝗮𝗹𝗹𝘆 𝗶𝗻 𝗝𝗮𝘃𝗮 𝟴+?" 🚀 Saying "it's thread-safe" is easy, but explaining how it stays so fast is what interviewers are actually looking for. Here is the quick, jargon-free breakdown: 1️⃣ 𝗡𝗼 𝗠𝗼𝗿𝗲 𝗦𝗲𝗴𝗺𝗲𝗻𝘁 𝗟𝗼𝗰𝗸𝘀: Java 8 ditched the old segment-locking mechanism for a much finer-grained, per-bucket approach. 2️⃣ 𝗘𝗺𝗽𝘁𝘆 𝗕𝘂𝗰𝗸𝗲𝘁𝘀 = 𝗡𝗼 𝗟𝗼𝗰𝗸𝘀: If you insert data into an empty bucket, it uses a lock-free CPU operation called CAS (Compare-And-Swap). Pure speed! ⚡ 3️⃣ 𝗖𝗼𝗹𝗹𝗶𝘀𝗶𝗼𝗻𝘀 = 𝗕𝘂𝗰𝗸𝗲𝘁-𝗟𝗲𝘃𝗲𝗹 𝗟𝗼𝗰𝗸𝘀: If a bucket already has data, it uses synchronized to lock only the first node (the head) of that specific bucket. The rest of the map remains wide open for other threads. 4️⃣ 𝗧𝗿𝗲𝗲𝗶𝗳𝗶𝗰𝗮𝘁𝗶𝗼𝗻 : If a single bucket gets too crowded (8+ nodes), the linked list converts into a Red-Black Tree, boosting search speed from O(n) to O(log n). 5️⃣ 𝗟𝗼𝗰𝗸-𝗙𝗿𝗲𝗲 𝗥𝗲𝗮𝗱𝘀: get() operations never lock! It uses volatile variables to ensure threads always read the most up-to-date values directly from memory. (I’ve attached a quick handwritten mind-map I put together to visualize this!) What’s the most interesting core Java question you’ve encountered recently? Let me know below! 👇 #Java #BackendDevelopment #SoftwareEngineering #InterviewPreparation #ConcurrentHashMap #Java8
To view or add a comment, sign in
-
-
🚀 Java Interview Questions – Test Your Fundamentals As part of my interview preparation, I’ve been revising core Java concepts. Sharing some real interview questions I came across 👇 --- 🔹 Q1: What are the 4 pillars of OOP? 🔹 Q2: What is the difference between Encapsulation and Abstraction? 🔹 Q3: Why does Java not support multiple inheritance using classes? 🔹 Q4: What is the difference between Method Overloading and Method Overriding? --- 🔹 Q5: Difference between List, Set, and Map? 🔹 Q6: Why is HashMap so fast? 🔹 Q7: What is hashCode() and equals()? Why are they important? 🔹 Q8: What is collision in HashMap and how is it handled? --- 🔹 Q9: Why is ArrayList fast for reading but slow for insertion? 🔹 Q10: Why is String immutable in Java? --- 🔹 Q11: Difference between Checked and Unchecked exceptions? 🔹 Q12: What is finally block? Will it always execute? --- 🔹 Q13: What is a race condition in multithreading? 🔹 Q14: Difference between start() and run()? --- 🔹 Q15: What is a Lambda expression? 🔹 Q16: Difference between map() and filter() in Streams? --- 💡 Trying to strengthen my fundamentals step by step and become interview-ready 💻 👉 How many can you answer correctly? #Java #JavaDeveloper #InterviewQuestions #LearningInPublic #SoftwareEngineering #TechCareers
To view or add a comment, sign in
-
🚀 30 Days of Java Interview Questions – Day 23 💡 Question: What is ThreadLocal in Java and how does it work internally? This is a rare and tricky question often asked in backend and multithreading interviews. 🔹 What is ThreadLocal? ThreadLocal is a class that provides thread-specific variables. Each thread has its own independent copy of the variable. 🔹 Why Use ThreadLocal? Used when you want to avoid sharing data between threads. Example use cases: • Database connections • User sessions • Transactions 🔹 How It Works Internally Each Thread has its own ThreadLocalMap Thread → ThreadLocalMap → (ThreadLocal, Value) So every thread stores its own value separately 🔹 Example ```java class Test { static ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); public static void main(String[] args) { threadLocal.set(100); System.out.println(threadLocal.get()); // 100 } } ``` 🔹 Important Methods set(value) → store value get() → retrieve value remove() → remove value (important to prevent memory leaks) 🔹 Important Points • Each thread has its own copy • No synchronization required • Must call remove() to avoid memory leaks ⚡ Quick Summary • ThreadLocal → thread-specific storage • Internally uses ThreadLocalMap • Helps in thread isolation 📌 Interview Tip Mention this line to stand out: “ThreadLocal avoids synchronization by giving each thread its own copy of data.” Follow this series for more advanced Java interview questions. #java #javadeveloper #multithreading #threadlocal #codinginterview #backenddeveloper #softwareengineer #programming
To view or add a comment, sign in
-
-
💡 Java Concept: == vs equals() (String Comparison) One of the most commonly asked Java interview questions — but many still get it wrong. 🔹 == checks reference equality 👉 Are both variables pointing to the same object in memory? 🔹 equals() checks value equality 👉 Do both strings have the same content? 📌 Example: s1 == s2 → ❌ false (different objects) s1.equals(s2) → ✅ true (same value) s1 == s3 → ✅ true (String Pool optimization) 🧠 Key Insight: Java uses a String Pool to optimize memory. When we create strings using literals, they may point to the same object. 🚀 Pro Tip for Interviews: Always use equals() for string comparison unless we specifically want to compare memory references. #Java #SoftwareEngineering #CodingInterview #JavaDeveloper #ProgrammingTips #TechInterview #FullStackDeveloper
To view or add a comment, sign in
-
-
🚀 Java Constructors – Complete Interview Cheat Sheet (With Edge Cases) Constructors may look simple, but in interviews, they’re used to test depth, fundamentals, and real understanding. Here’s a crisp, no-fluff guide 👇 ⸻ 🔹 What is a Constructor? • Special method used to initialize objects • Same name as class • No return type • Called automatically during object creation ⸻ 🔹 Types of Constructors • Default (JVM provided) • No-Arg (explicit) • Parameterized • Copy Constructor (user-defined concept) ⸻ 🔹 Core Rules 🔥 • Cannot have return type • Can be overloaded • Cannot be overridden or inherited • First statement must be this() or super() ⸻ 🔹 this() vs super() ⚠️ • this() → calls current class constructor • super() → calls parent class constructor • Must be FIRST line • Cannot use both together ⸻ 🔹 Constructor Overloading • Same name (class name) • Different parameters • Return type does NOT matter ⸻ 🔹 Constructor Chaining • One constructor calls another • Improves code reuse ⸻ 🔹 Inheritance Behavior (Very Important) • Parent constructor executes first • If parent has no default constructor → must call super(params) ⸻ 🔹 Execution Flow 🧠 1. Static block 2. Instance block 3. Constructor ⸻ 🔹 Access Modifiers • public / protected / default / private 👉 Private constructor → used in Singleton pattern ⸻ 🔹 Keywords Not Allowed ❌ • static • final • abstract ⸻ 🔹 Tricky Edge Cases 🚨 • If no constructor → JVM provides default • If any constructor is defined → no default constructor • Constructor with return type = NOT constructor • Cannot call constructor like a method • Constructors can throw exceptions ⸻ 🔹 Real-Time Usage • Object initialization • Dependency Injection • Singleton pattern • Immutable classes ⸻ 💡 Final Takeaway: Constructors are a favorite interview topic to test: ✔ Execution flow ✔ Chaining ✔ Inheritance ✔ Edge cases Master this → You already stand out as a strong Java engineer. ⸻ 💬 What’s the toughest constructor question you’ve faced in interviews? #Java #SDET #AutomationTesting #InterviewPrep #JavaDeveloper #Programming :::
To view or add a comment, sign in
-
🚀 30 Days of Java Interview Questions – Day 27 💡 Question: What is the difference between fail-fast and fail-safe iterators in Java? This is a very important and commonly asked interview question in collections. --- 🔹 Fail-Fast Iterator Fail-fast iterators immediately throw an exception if the collection is modified during iteration. They work on the original collection. Example: ```java id="p3k9q1" List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); for (Integer i : list) { list.add(3); // causes exception } ``` Output: ConcurrentModificationException --- 🔹 Fail-Safe Iterator Fail-safe iterators do not throw an exception if the collection is modified. They work on a copy of the collection. Example: ```java id="v7l2m4" CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>(); list.add(1); list.add(2); for (Integer i : list) { list.add(3); // no exception } ``` --- 🔹 Key Differences Fail-Fast • Throws ConcurrentModificationException • Works on original collection • Faster Fail-Safe • No exception • Works on copy • Slower --- ⚡ Quick Facts • Most Java collections use fail-fast iterators • Fail-safe is used in concurrent collections • Helps avoid unexpected behavior --- 📌 Interview Tip Fail-fast is used for safety and debugging, while fail-safe is used for concurrency. --- Follow this series for 30 Days of Java Interview Questions. #java #javadeveloper #codinginterview #backenddeveloper #softwareengineer #programming #developers #tech
To view or add a comment, sign in
-
-
🚀 30 Days of Java Interview Questions – Day 21 💡 Question: How does Java ClassLoader work internally? This is a rare and advanced JVM question that can really impress interviewers. 🔹 What is ClassLoader? ClassLoader is a part of JVM responsible for loading .class files into memory at runtime. 🔹 ClassLoader Hierarchy Bootstrap ClassLoader • Loads core Java classes (rt.jar) Extension (Platform) ClassLoader • Loads classes from extension libraries Application ClassLoader • Loads classes from classpath 🔹 Parent Delegation Model Java follows a delegation model for security: 1. Check if class is already loaded 2. Delegate to parent ClassLoader 3. Bootstrap tries first 4. Then Extension 5. Finally Application loads it 🔹 Why Delegation? • Prevents duplicate class loading • Ensures core classes are secure • Improves performance 🔹 Important Points • Classes are loaded only once • Stored in Method Area • Class.forName() triggers loading ⚡ Quick Summary • ClassLoader loads classes at runtime • Follows Parent Delegation Model • Works in hierarchy (Bootstrap → Extension → Application) 📌 Interview Tip Always mention “Parent Delegation Model” — this is the key highlight interviewers look for. Follow this series for more advanced Java interview questions. #java #javadeveloper #jvm #classloader #codinginterview #backenddeveloper #softwareengineer #programming
To view or add a comment, sign in
-
-
Java interview question on Memory Leaks — here's everything you need to know! Had a great technical interview recently where Memory Leaks came up as a deep-dive topic. Here's a concise breakdown that I think every Java developer should know 🔍 What is a Memory Leak in Java? A memory leak happens when objects are no longer needed by the application, but the Garbage Collector (GC) cannot reclaim them — because references still exist. The JVM keeps them in heap, and over time, this causes OutOfMemoryError. ⚠️ Common Causes 1. Static fields holding object references 2. Unclosed resources (streams, connections, sessions) 3. Listeners / callbacks never removed 4. Inner classes holding implicit reference to outer class 5. ThreadLocal variables not cleaned up 6. Caches without eviction policies 🛠️ How to Detect It 1. JVisualVM / JConsole — monitor heap usage over time 2. Eclipse MAT (Memory Analyzer Tool) — analyze heap dumps 3. YourKit / JProfiler — commercial profilers, powerful for production 4. verbose:gc JVM flag — observe GC behavior 5. Heap dumps with jmap -dump:live,format=b,file=heap.hprof <pid> ✅ How to Fix / Prevent It 1. Use WeakReference / SoftReference for caches 2. Always close resources with try-with-resources 3. Remove listeners when done 4. Avoid unnecessary static references 5. Use tools like Caffeine / Guava Cache with TTL/max-size 6. Review ThreadLocal.remove() usage in thread pools Memory leaks are silent killers in production. If you're preparing for Java interviews — bookmark this. Drop a comment if you've faced memory leak issues in production. Let's learn together! 🙌 #Java #JavaDeveloper #MemoryLeak #JVM #PerformanceTuning #JavaInterview #SoftwareEngineering #Programming #TechInterview #BackendDevelopment #ProductionIssue #Interview #MemoryLeaks #Spring
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