Top 10 Most Asked Java Interview Questions 1. What is the difference between HashMap and ConcurrentHashMap? HashMap is not thread-safe and can cause data inconsistency in concurrent environments. ConcurrentHashMap uses fine-grained locking and CAS operations to allow safe concurrent reads and writes. 2. What is the difference between final, finally, and finalize? final → keyword used for variables, methods, and classes to restrict modification. finally → block used in exception handling to execute cleanup code. finalize → method used by GC before object collection (deprecated and rarely used). 3. What happens when hashCode() and equals() are not implemented properly? If equal objects produce different hashCodes, collections like HashMap behave incorrectly. This leads to duplicate keys and degraded lookup performance. 4. What is the difference between ArrayList and LinkedList? ArrayList uses a dynamic array and provides fast random access. LinkedList uses a doubly linked structure and is efficient for insertions and deletions. 5. What is the difference between Thread and Runnable? Thread is a class that represents a thread of execution. Runnable is an interface used to define the task that a thread executes. Using Runnable improves flexibility because it separates the task from thread management. 6. What causes memory leaks in Java? Common causes include: - Static collections holding references - Unclosed resources - ThreadLocal misuse - Listeners not removed Heap dumps and tools like MAT help identify leaks. 7. What is the difference between synchronized and Lock? synchronized is simpler and managed by JVM. Lock provides advanced features like tryLock(), fairness policies, and interruptible locks. 8. What is the difference between checked and unchecked exceptions? Checked exceptions must be handled at compile time. Unchecked exceptions occur at runtime and usually indicate programming errors. 9. What is the difference between fail-fast and fail-safe iterators? Fail-fast iterators throw ConcurrentModificationException if the collection is modified during iteration. Fail-safe iterators operate on a copy of the collection. 10. What is the JVM and what are its main components? JVM is the runtime that executes Java bytecode. Main components include: - Heap - Stack - Method Area - Garbage Collector - JIT Compiler #Java #JavaInterview #BackendEngineering #SpringBoot #CodingInterview #SoftwareEngineering
Java Interview Questions: HashMap, ConcurrentHashMap, Thread Safety, and More
More Relevant Posts
-
🚀 Java Backend Interview Series – Question #45 Q45. What is the difference between checked and unchecked exceptions in Java? Exception handling is a fundamental part of robust Java applications. But one of the most common interview questions is understanding the difference between checked and unchecked exceptions. Many developers use exceptions daily but don't fully understand why Java separates them. Let’s break it down 👇 🔹 1️⃣ Checked Exceptions Checked exceptions are checked at compile time. This means the compiler forces you to handle them, either by: Using a try-catch block Declaring them using the throws keyword Example: FileReader file = new FileReader("data.txt"); This throws a FileNotFoundException, which must be handled. Example handling: try { FileReader file = new FileReader("data.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } 📌 Common Checked Exceptions: IOException SQLException FileNotFoundException ClassNotFoundException 🔹 2️⃣ Unchecked Exceptions Unchecked exceptions are not checked at compile time. They occur during runtime, and the compiler does not force you to handle them. Example: int result = 10 / 0; This throws: ArithmeticException 📌 Common Unchecked Exceptions: NullPointerException ArrayIndexOutOfBoundsException IllegalArgumentException ArithmeticException 🔹 Why Java Designed It This Way Checked exceptions represent recoverable conditions. Examples: ✔ File not found ✔ Network issue ✔ Database failure Unchecked exceptions usually represent programming errors. Examples: ❌ Null pointer access ❌ Invalid array index ❌ Bad input handling 🎯 Interview Tip If an interviewer asks: 👉 “Should we always catch unchecked exceptions?” The best answer is: ❌ No. Unchecked exceptions usually indicate bugs that should be fixed, not silently handled. 💬 Follow-up Interview Question Why did Spring Framework convert many checked exceptions into unchecked exceptions (DataAccessException hierarchy)? #Java #ExceptionHandling #JavaDeveloper #BackendDevelopment #CodingInterview #TechInterview #SoftwareEngineering #SpringBoot #Microservices #Programming #DeveloperCommunity #CodingTips #CleanCode #JavaInterview
To view or add a comment, sign in
-
-
🚀 𝐅𝐚𝐢𝐥-𝐅𝐚𝐬𝐭 𝐯𝐬 𝐅𝐚𝐢𝐥-𝐒𝐚𝐟𝐞 𝐈𝐭𝐞𝐫𝐚𝐭𝐨𝐫𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚 If you're preparing for Java interviews, this is an important concept to understand. When iterating over collections in Java, two types of iterator behaviors exist. 🔴 Fail-Fast Iterator If the collection is modified while iterating, it immediately throws a Concurrent Modification Exception. Example collections: • ArrayList • HashMap • HashSet Example: List<String> list = new ArrayList<>(); list.add("Java"); list.add("Spring"); for (String s : list) { list.add("Docker"); // throws ConcurrentModificationException } These iterators detect structural modifications during iteration and fail immediately. 🟢 Fail-Safe Iterator Fail-Safe iterators work on a copy of the collection, so modifications during iteration do not throw exceptions. Example collections: • ConcurrentHashMap • CopyOnWriteArrayList Example: CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(); list.add("Java"); for (String s : list) { list.add("Spring"); // no exception } 📌 Key Difference Fail-Fast → Throws exception if collection is modified during iteration Fail-Safe → Works on a copy, so no exception occurs Understanding this concept is important when working with multithreading and concurrent collections. Follow for more Java internals explained simply. #Java #JavaDeveloper #Programming #CodingInterview #BackendDevelopment
To view or add a comment, sign in
-
🚨 One Java Interview Question Many Developers Still Get Wrong equals() vs hashCode() Most developers know these methods exist in Java, but many don’t fully understand why they must work together. Let’s break it down 👇 🔹 equals() • Used to compare the logical equality of two objects • By default, it compares memory references, not values • We override it when we want to compare object content 🔹 hashCode() • Returns an integer hash value for the object • Used internally by HashMap, HashSet, and HashTable • Helps Java quickly locate objects in hash buckets ⚠️ Important Rule If two objects are equal using equals(), they must return the same hashCode(). Otherwise, collections like HashSet or HashMap may behave incorrectly. 💡 Example Issue You add two logically equal objects into a HashSet, but because their hashCode values are different, both get stored. Result? Duplicate objects inside a Set. ✅ Takeaway Whenever you override equals(), always override hashCode() as well. This small rule can prevent subtle and hard-to-debug issues in real applications. 💬 Have you ever faced a bug related to equals() and hashCode()? #Java #SoftwareDevelopment #Programming #JavaDeveloper #CodingInterview #BackendDevelopment
To view or add a comment, sign in
-
🚀 Java Backend Interview Series – Question #44 Q44. What is the difference between HashSet and TreeSet in Java? Both HashSet and TreeSet are part of the Java Set interface, meaning: ✔ They do not allow duplicate elements ✔ They are commonly used when you need unique data However, they behave very differently in terms of ordering, performance, and internal implementation. Let’s break it down 👇 🔹 1️⃣ HashSet HashSet stores elements using a hash table. Example: Set<Integer> set = new HashSet<>(); set.add(30); set.add(10); set.add(20); System.out.println(set); 📌 Possible Output: [20, 10, 30] Key characteristics: ❌ No ordering guarantee ⚡ Very fast operations Average O(1) time complexity for add, remove, contains Allows one null element Best used when performance matters and ordering is not required. 🔹 2️⃣ TreeSet TreeSet stores elements using a Red-Black Tree (self-balancing binary search tree). Example: Set<Integer> set = new TreeSet<>(); set.add(30); set.add(10); set.add(20); System.out.println(set); 📌 Output: [10, 20, 30] Key characteristics: ✔ Elements are automatically sorted Uses natural ordering or custom Comparator Time complexity O(log n) ❌ Does NOT allow null values Best used when sorted data is required. 🔹 Real-world Example Use HashSet when: ✔ Removing duplicates from a large dataset ✔ Fast lookup is required Use TreeSet when: ✔ You need sorted elements ✔ You want operations like first(), last(), ceiling(), floor() 🎯 Interview Tip If an interviewer asks: 👉 “Which one is faster: HashSet or TreeSet?” The correct answer is: HashSet is faster, but TreeSet provides sorted data. 💬 Follow-up Interview Question How does TreeSet maintain sorting internally, and what happens if you insert objects that do not implement Comparable? #Java #JavaCollections #HashSet #TreeSet #JavaDeveloper #BackendDevelopment #CodingInterview #TechInterview #SoftwareEngineering #SpringBoot #Microservices #Programming #DeveloperCommunity #CodingTips #CleanCode #DataStructures
To view or add a comment, sign in
-
-
🚀 Most Asked Core Java Interview Questions (Part 2) Continuing from Part 1 — more frequently asked questions 👇 🔹 Multithreading Questions Thread vs Process What happens if you call run() instead of start()? What if you don’t override run()? Thread lifecycle Class level lock vs Object level lock Race condition (with example) Deadlock (with example) Runnable vs Callable ThreadLocal wait vs sleep notify vs notifyAll yield, join Why wait/notify/notifyAll present in Object class? 🔹 Concurrency & Advanced Synchronization ReentrantLock Semaphore CyclicBarrier CompletableFuture vs Future ThreadPoolExecutor (internal working) FixedThreadPool vs CachedThreadPool BlockingQueue 🔹 Coding Questions (Threads) Print even/odd using two threads Producer-Consumer problem Print numbers (0–N) using 3 threads (mod 3) Print ABCABC using 3 threads 🔹 Collections ArrayList vs LinkedList HashMap internal working HashSet vs LinkedHashSet ConcurrentHashMap vs HashMap ConcurrentHashMap vs Hashtable TreeMap vs TreeSet Comparable vs Comparator Iterator vs ListIterator vs Enumeration ConcurrentModificationException Default size of ArrayList 🔹 Advanced Collections Immutable Map WeakHashMap vs IdentityHashMap HashSet internal working If a class has ArrayList, how to make it immutable 🔹 Design Singleton class Double locking How to break Singleton 💡 Save this for revision — these are highly repeated interview questions 🔥 #Java #CoreJava #Multithreading #Collections #InterviewPreparation
To view or add a comment, sign in
-
☕ Java Core Concepts – Interview Question 📌 How is String creation using new() different from a literal? In Java, Strings can be created in two ways, and they behave differently in memory: 🔹 String Literal ("abc") • Stored in the String Pool (inside Heap) • JVM checks if the value already exists • If yes → returns reference of existing object • If no → creates a new object in the pool ✅ Memory efficient (reuses objects) 🔹 Using new Keyword (new String("abc")) • Always creates a new object in Heap memory • Does NOT reuse objects from String Pool ❌ Less memory efficient (creates duplicate objects) 🔹 Example: String s1 = "hello"; String s2 = "hello"; // reuses same object String s3 = new String("hello"); // new object in heap 🔹 Key Difference: ✔ Literal → Reuses existing objects (String Pool) ✔ new → Always creates a new object 💡 In Short: String literals save memory using the String Pool, while new always creates a fresh object, even if the value already exists. 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #String #JavaInterview #Programming #Coding #TechSkills#Ashokit
To view or add a comment, sign in
-
-
🚀 Java Backend Interview Series – Question #73 Q73. What are Method References in Java 8 and how are they different from Lambda expressions? With Java 8, we started writing more functional-style code using lambdas. But there’s an even cleaner and more readable alternative in some cases: 👉 Method References (::) Let’s understand what they are and how they differ from lambdas 👇 🔹 1️⃣ What is a Method Reference? A Method Reference is a shorthand way of writing lambda expressions when the lambda simply calls an existing method. Syntax: ClassName::methodName 🔹 2️⃣ Example: Lambda vs Method Reference Using Lambda: list.forEach(s -> System.out.println(s)); Using Method Reference: list.forEach(System.out::println); 📌 Both are equivalent, but: ✔ Method reference is shorter and more readable 🔹 3️⃣ Types of Method References ✔ Static Method Reference Math::abs ✔ Instance Method of a Particular Object System.out::println ✔ Instance Method of an Arbitrary Object String::toUpperCase ✔ Constructor Reference ArrayList::new 🔹 4️⃣ Key Differences FeatureLambdaMethod ReferenceSyntaxVerboseConciseReadabilityMediumHighFlexibilityMore flexibleLess flexibleUse CaseCustom logicDirect method call🔹 5️⃣ When to Use Method References? ✔ When lambda only calls an existing method ✔ When you want cleaner and readable code ❌ Avoid when: Logic is complex Multiple operations are involved 🔹 6️⃣ Real-World Backend Example List<String> users = List.of("java", "spring", "microservices"); users.stream() .map(String::toUpperCase) // Method Reference .forEach(System.out::println); 📌 Cleaner compared to full lambda expressions. 🎯 Interview Tip A tricky question: 👉 “Are method references faster than lambdas?” Answer: ❌ No major performance difference. ✔ They are mainly for code readability and maintainability. 💬 Follow-up Interview Question What are the different types of method references, and can you give real examples for each? #Java #Java8 #MethodReference #Lambda #FunctionalProgramming #JavaDeveloper #BackendDevelopment #CodingInterview #TechInterview #SoftwareEngineering #SpringBoot #Microservices #Programming #CleanCode #JavaStreams
To view or add a comment, sign in
-
-
📌 Java static Keyword – Complete Developer & Interview Guide This post provides structured, interview-focused coverage of the static keyword in Java, including static variables, methods, blocks, and nested classes with practical examples. What this document covers: • What is the static Keyword Used mainly for memory management Applies to variables, methods, blocks, and nested classes Static members belong to the class, not individual objects • Static Variables (Class Variables) Only one copy shared across all objects Memory allocated once in the class area Used for common properties (e.g., company name, interest rate) Accessed using ClassName.variable • Static Methods Belong to the class rather than an object Can be called using the class name directly Example: Math.max() Restrictions of Static Methods: Can call only other static methods Can access only static variables Cannot use this or super references • Static Block Block executed once when the class loads Runs before the main() method Used for initializing static variables Example: static { rate = 1.2; } • Static Nested Class A static class must be declared inside another class Can be created without creating an outer class object Can access only static members of the outer class Example: class Outer { static class Nested { } } • Memory Behavior (Important for Interviews) Instance variables → stored per object in heap Static variables → stored once in class/static area All objects share the same static value • Real-Time Example Banking application interest rate College name shared by all students Utility methods (like Math class methods) I’ll continue sharing high-value interview and reference content. 🔗 Follow me: https://lnkd.in/gAJ9-6w3 — Aravind Kumar Bysani #Java #CoreJava #JavaInterview #StaticKeyword #OOP #JavaProgramming #BackendDevelopment #InterviewPreparation
To view or add a comment, sign in
-
🚨 Java Interview Trap 2 Why is "Vector" rarely used in modern Java? Many developers quickly answer: “Because it’s outdated.” But the real reason is more interesting 👇 Vector was introduced in JDK 1.0, even before the Collections Framework existed. It behaves like a dynamic array and internally stores elements using an array. Some key facts: • Default capacity = 10 • Capacity usually doubles when full • All methods are synchronized • This makes Vector thread-safe by default Example: import java.util.Vector; public class Test { public static void main(String[] args) { Vector<Integer> numbers = new Vector<>(); numbers.add(10); numbers.add(20); numbers.add(30); System.out.println(numbers); } } Because every method is synchronized, multiple threads can safely modify a Vector. But there is a trade-off. Synchronization introduces performance overhead, especially in single-threaded applications. That’s why most modern Java applications prefer: • ArrayList • Collections.synchronizedList() • CopyOnWriteArrayList But here is the real interview question 👇 When the internal array inside a Vector becomes full, Java creates a new array with double the size and copies all elements into it. What do you think happens to the old array? 1️⃣ It stays in memory 2️⃣ It gets reused 3️⃣ It becomes eligible for GC Drop the correct answer in the comments 👇 Sometimes the oldest Java classes still hide the best interview traps. #Java #JavaInterview #Collections #JVM #SoftwareEngineering #Developers #Programming
To view or add a comment, sign in
-
🚨 Java Mystery That Breaks Your Brain 🧠💥 What will be the output of this code? public class Mystery { public static void main(String[] args) { Integer a = 100; Integer b = 100; Integer c = 200; Integer d = 200; System.out.println(a == b); System.out.println(c == d); } } Think carefully… it’s not as simple as it looks 👀 👇 👇 👇 Output: true false Wait… what? Same values but different results😵💫? Here’s the catch 👇 Java caches Integer values only in the range -128 to 127. So when you write: Integer a = 100; Integer b = 100; Both variables actually point to the same object in memory → that’s why it returns true. But when you write: Integer c = 200; Integer d = 200; These values are outside the cache range, so Java creates two different objects → that’s why it returns false. The real trap here is: 👉 == compares references (memory location) 👉 .equals() compares actual values This small difference can easily confuse you in interviews or even in real projects. Pro tip: Avoid using == with wrapper classes unless you clearly understand what’s happening behind the scenes. Did you get it right? Be honest 👇 And share this with someone preparing for Java interviews 😉 #Java #CodingChallenge #InterviewPrep #Developers #Programming #Tech
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