{"id":9456,"date":"2026-10-15T15:26:15","date_gmt":"2026-10-15T09:56:15","guid":{"rendered":"https:\/\/www.monsterindia.com\/career-advice\/java-interview-questions-and-answers-for-2-to-3-years-experience-9456\/"},"modified":"2026-10-21T16:18:52","modified_gmt":"2026-10-21T10:48:52","slug":"java-interview-questions-and-answers-for-2-to-3-years-experience","status":"publish","type":"post","link":"https:\/\/www.foundit.in\/career-advice\/java-interview-questions-and-answers-for-2-to-3-years-experience\/","title":{"rendered":"Java Interview Questions and Answers for 2 to 3 years Experienced: Top 50"},"content":{"rendered":"<p class=\"wp-block-paragraph\">Preparing for <strong>Java interview questions for 2 to 3 years of experience<\/strong> requires more than recalling definitions. At this stage, interviewers may ask you to explain why a particular collection, design approach or concurrency mechanism was used, identify limitations and describe how you handled technical problems in your projects.<p class=\"wp-block-paragraph\">This guide covers <strong>50 Java interview questions and answers<\/strong> across object-oriented programming, the Collections Framework, strings, exception handling, multithreading, JVM fundamentals and Java 8 features. The answers include comparisons, code examples and practical considerations relevant to developers with approximately two to three years of experience.<\/p><div class=\"wp-block-group has-yellow-background-color has-background\"><div class=\"wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow\">\n\n<h3 class=\"wp-block-heading\">Java Interview Preparation: Key Highlights<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Core Java:<\/strong> Revise inheritance, polymorphism, interfaces, method overriding, immutability and exception handling.<\/li>\n\n\n\n<li><strong>Collections:<\/strong> Understand the differences between lists, sets and maps, including their ordering, equality and thread-safety characteristics.<\/li>\n\n\n\n<li><strong>Concurrency:<\/strong> Be prepared to explain <code>volatile<\/code>, synchronisation, thread coordination and common race conditions.<\/li>\n\n\n\n<li><strong>Practical coding:<\/strong> Review short Java programs and explain both their output and the reasoning behind your implementation.<\/li>\n\n\n\n<li><strong>Project discussions:<\/strong> Prepare real examples of debugging, collection selection, exception handling and performance trade-offs from your development experience.<\/li>\n<\/ul>\n<\/div><\/div><h2 id=\"top-50-java-interview-questions\" class=\"wp-block-heading\">Top 50 Java Interview Questions for 2 to 3 Years of Experience<\/h2><p class=\"wp-block-paragraph\">The following questions move from core language concepts to collections, concurrency and application-level scenarios. Use the answers to revise technical fundamentals, then connect them to projects you have actually worked on. Examples use standard Java syntax unless a specific Java version is mentioned.<\/p><h3 class=\"wp-block-heading\">1. What Is the Difference Between Method Overloading and Method Overriding in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>Method overloading<\/strong> means declaring methods with the same name but different parameter lists. The compiler selects an applicable overload using the argument types and other language rules. Overloading can occur within a class or across inherited methods.<\/p><p class=\"wp-block-paragraph\"><strong>Method overriding<\/strong> occurs when a subclass provides an implementation of an inherited instance method with an override-compatible signature and return type. For an overridden instance method, runtime dispatch determines which implementation executes based on the actual object.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>Method Overloading<\/th><th>Method Overriding<\/th><\/tr><\/thead><tbody><tr><td>Same method name with different parameter lists<\/td><td>Override-compatible instance method in a subclass<\/td><\/tr><tr><td>Overload selection occurs at compile time<\/td><td>Overridden implementation is selected at runtime<\/td><\/tr><tr><td>Does not require inheritance<\/td><td>Requires inheritance or interface implementation<\/td><\/tr><tr><td>Return type alone cannot distinguish overloads<\/td><td>Return type must meet overriding rules, including covariant returns<\/td><\/tr><tr><td>Static methods can be overloaded<\/td><td>Static methods are hidden, not overridden<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Java example:<\/strong><\/p><pre class=\"wp-block-code\"><code>class Calculator  \n\n    double add(double a, double b)  \n}\n\nclass Animal  \n}\n\nclass Dog extends Animal  \n}<\/code><\/pre><p class=\"wp-block-paragraph\">The two <code>add()<\/code> methods demonstrate overloading, while <code>Dog.speak()<\/code> demonstrates overriding. If <code>Animal animal = new Dog();<\/code> is followed by <code>animal.speak();<\/code>, the output is <code>Bark<\/code> because the object is a <code>Dog<\/code>.<\/p><h3 class=\"wp-block-heading\">2. What Is a ClassLoader in Java?<\/h3><p class=\"wp-block-paragraph\">A <strong>ClassLoader<\/strong> is responsible for locating and defining classes for the Java runtime. Java can load class definitions when needed, rather than requiring every application class to be loaded at startup.<\/p><p class=\"wp-block-paragraph\">The standard Java runtime includes these built-in class loaders:<\/p><ul class=\"wp-block-list\">\n<li><strong>Bootstrap ClassLoader:<\/strong> The JVM&rsquo;s built-in loader, responsible for fundamental Java runtime classes, including core classes from <code>java.base<\/code>.<\/li>\n\n\n\n<li><strong>Platform ClassLoader:<\/strong> Loads platform classes and modules assigned to it by the runtime.<\/li>\n\n\n\n<li><strong>Application or System ClassLoader:<\/strong> Commonly loads application classes and dependencies from the application classpath and applicable module path.<\/li>\n<\/ul><p class=\"wp-block-paragraph\">Java class loaders normally use a <strong>parent-delegation model<\/strong>: before attempting to find a class themselves, they delegate loading to their parent. Custom class loaders may implement different arrangements for specific requirements.<\/p><p class=\"wp-block-paragraph\">For example, application servers and plugin systems may use separate class loaders to isolate dependencies or load components dynamically. Class identity in Java depends on both the class&rsquo;s binary name and its defining class loader.<\/p><p class=\"wp-block-paragraph\"><strong>Version note:<\/strong> References to the Extension ClassLoader and <code>rt.jar<\/code> describe older Java environments. Java 9 introduced the module system and a revised built-in class-loading arrangement. The <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/25\/docs\/api\/java.base\/java\/lang\/ClassLoader.html\" target=\"_blank\" rel=\"noopener noreferrer\">Oracle ClassLoader API documentation<\/a> explains the modern structure.<\/p><h3 class=\"wp-block-heading\">3. What Is Inheritance in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>Inheritance<\/strong> allows a class to extend another class, gaining access to its inheritable methods and fields. The parent is called the superclass and the extending class is the subclass.<\/p><p class=\"wp-block-paragraph\">Java supports single, multilevel and hierarchical class inheritance. A class cannot extend multiple classes, although it can implement multiple interfaces.<\/p><ul class=\"wp-block-list\">\n<li><strong>Single inheritance:<\/strong> One class extends another class.<\/li>\n\n\n\n<li><strong>Multilevel inheritance:<\/strong> A subclass is extended by another subclass.<\/li>\n\n\n\n<li><strong>Hierarchical inheritance:<\/strong> Multiple subclasses extend the same superclass.<\/li>\n\n\n\n<li><strong>Multiple interface implementation:<\/strong> One class implements several interfaces, subject to Java&rsquo;s method-conflict rules.<\/li>\n<\/ul><p class=\"wp-block-paragraph\"><strong>Practical consideration:<\/strong> Inheritance is appropriate when a genuine &ldquo;is-a&rdquo; relationship exists. Composition is often preferable when a class simply needs to use another component&rsquo;s functionality, because it can reduce coupling between implementations.<\/p><h3 class=\"wp-block-heading\">4. Why Can&rsquo;t We Override Static Methods in Java?<\/h3><p class=\"wp-block-paragraph\">Static methods belong to a class rather than an object instance. They are resolved according to the class or reference type used in the call, so they do not participate in runtime overriding.<\/p><p class=\"wp-block-paragraph\">When a subclass declares a static method with the same signature as an accessible static method in its superclass, the subclass method <strong>hides<\/strong> the superclass method.<\/p><pre class=\"wp-block-code\"><code>class Parent  \n}\n\nclass Child extends Parent  \n}\n\npublic class Main  \n}<\/code><\/pre><p class=\"wp-block-paragraph\">The first call prints <code>Parent<\/code> because the reference type is <code>Parent<\/code>. The second call explicitly invokes <code>Child.show()<\/code>. This is method hiding, not runtime polymorphism.<\/p><h3 class=\"wp-block-heading\">5. What Is Dynamic Method Dispatch in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>Dynamic method dispatch<\/strong> is the process Java uses to select an overridden instance method at runtime according to the actual object type.<\/p><pre class=\"wp-block-code\"><code>class Vehicle  \n}\n\nclass Car extends Vehicle  \n}\n\nVehicle vehicle = new Car();\nvehicle.move(); \/\/ Car moves<\/code><\/pre><p class=\"wp-block-paragraph\">Although the reference is declared as <code>Vehicle<\/code>, the object is a <code>Car<\/code>, so the overridden method in <code>Car<\/code> executes.<\/p><p class=\"wp-block-paragraph\">Dynamic dispatch supports polymorphic designs in which application code works with a superclass or interface while different implementations provide specialised behaviour. Static, private and final methods do not participate in overriding in the same way.<\/p><h3 class=\"wp-block-heading\">6. What Is the Classpath in Java?<\/h3><p class=\"wp-block-paragraph\">The <strong>Java classpath<\/strong> identifies directories and JAR files where Java tools and class loaders can find application classes and dependencies.<\/p><p class=\"wp-block-paragraph\">Classpath entries can be supplied through the <code>-cp<\/code> or <code>-classpath<\/code> command-line option or through the <code>CLASSPATH<\/code> environment variable. Build tools such as Maven and Gradle commonly manage the required dependencies when compiling and running applications.<\/p><p class=\"wp-block-paragraph\"><strong>Example:<\/strong> On systems using a colon as the path separator, a command might look like this:<\/p><pre class=\"wp-block-code\"><code>java -cp \"app.jar:libs\/*\" com.example.Main<\/code><\/pre><p class=\"wp-block-paragraph\">On Windows, classpath entries are separated with a semicolon rather than a colon. Modern Java also has a <strong>module path<\/strong> for named modules, which is distinct from the traditional classpath.<\/p><h3 class=\"wp-block-heading\">7. What Is the volatile Keyword in Java?<\/h3><p class=\"wp-block-paragraph\">The <code>volatile<\/code> keyword is used for fields shared between threads when visibility and ordering guarantees are required. Under the Java Memory Model, a write to a volatile field <strong>happens-before<\/strong> a subsequent read of that field.<\/p><p class=\"wp-block-paragraph\">For example, a volatile status flag can communicate that a background task should stop:<\/p><pre class=\"wp-block-code\"><code>class Worker implements Runnable  \n\n    @Override\n    public void run()  \n    }\n}<\/code><\/pre><p class=\"wp-block-paragraph\">When another thread calls <code>stop()<\/code>, the worker can observe the updated flag. The example illustrates visibility; a real application should also consider interruption and avoid unnecessary busy-waiting.<\/p><p class=\"wp-block-paragraph\"><strong>Important limitation:<\/strong> <code>volatile<\/code> does not make compound operations such as <code>count++<\/code> atomic. Use appropriate synchronisation or classes such as <code>AtomicInteger<\/code> when several threads must update shared counters safely.<\/p><h3 class=\"wp-block-heading\">8. When Does a finally Block Not Execute in Java?<\/h3><p class=\"wp-block-paragraph\">A <code>finally<\/code> block normally executes when control leaves the associated <code>try<\/code> statement, whether execution completes normally, returns from a method or throws an exception.<\/p><p class=\"wp-block-paragraph\">However, execution is not guaranteed if the JVM or process terminates before the block can run. Calling <code>System.exit()<\/code>, forcibly terminating the process or experiencing a JVM crash can prevent pending <code>finally<\/code> blocks from executing.<\/p><p class=\"wp-block-paragraph\">A thread that becomes permanently blocked before leaving the <code>try<\/code> block may also never reach the associated <code>finally<\/code> block.<\/p><p class=\"wp-block-paragraph\"><strong>Interview tip:<\/strong> Distinguish a method returning from a <code>try<\/code> block, where <code>finally<\/code> normally executes, from JVM termination, where it may not. For resources such as files and database connections, use try-with-resources when appropriate.<\/p><h3 class=\"wp-block-heading\">9. What Is the Difference Between StringBuffer and StringBuilder in Java?<\/h3><p class=\"wp-block-paragraph\">Both <code>StringBuffer<\/code> and <code>StringBuilder<\/code> are mutable character-sequence classes. They allow applications to append, insert or modify characters without creating a new <code>String<\/code> object for every operation.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>StringBuffer<\/th><th>StringBuilder<\/th><\/tr><\/thead><tbody><tr><td>Provides synchronised methods<\/td><td>Does not synchronise its methods<\/td><\/tr><tr><td>Supports thread-safe individual operations<\/td><td>Requires external coordination when shared mutable access is possible<\/td><\/tr><tr><td>Can introduce synchronisation overhead<\/td><td>Usually preferable for local, single-threaded string building<\/td><\/tr><tr><td>Legacy class available since early Java versions<\/td><td>Introduced in Java 5<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Example:<\/strong><\/p><pre class=\"wp-block-code\"><code>StringBuilder builder = new StringBuilder();\nbuilder.append(\"Java\");\nbuilder.append(\" Interview\");\n\nSystem.out.println(builder.toString());\n\/\/ Java Interview<\/code><\/pre><p class=\"wp-block-paragraph\">For assembling text within one method or thread, <code>StringBuilder<\/code> is generally the simpler choice. Synchronised methods in <code>StringBuffer<\/code> do not automatically make a sequence of several operations atomic.<\/p><h3 class=\"wp-block-heading\">10. What Is the Difference Between Vector and ArrayList in Java?<\/h3><p class=\"wp-block-paragraph\"><code>Vector<\/code> and <code>ArrayList<\/code> are resizable-array implementations of the <code>List<\/code> interface. Both preserve element order, allow duplicates and support indexed access.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>Vector<\/th><th>ArrayList<\/th><\/tr><\/thead><tbody><tr><td>Legacy collection implementation<\/td><td>Widely used modern List implementation<\/td><\/tr><tr><td>Synchronises many public operations<\/td><td>Not synchronised by default<\/td><\/tr><tr><td>Individual method calls use synchronisation<\/td><td>Requires a suitable strategy for concurrent modification<\/td><\/tr><tr><td>May incur additional synchronisation overhead<\/td><td>Generally preferred when built-in synchronisation is unnecessary<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>When should you use ArrayList?<\/strong> For a list managed by one thread or protected by another appropriate concurrency mechanism, <code>ArrayList<\/code> is generally a good default.<\/p><p class=\"wp-block-paragraph\">When several threads need to access or modify a collection, choose a design that matches the operations being performed. Depending on the workload, alternatives may include synchronised wrappers, <code>CopyOnWriteArrayList<\/code> or explicit locking.<\/p><h3 class=\"wp-block-heading\">11. Why Is String Immutable in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>String immutability<\/strong> means that the sequence of characters represented by a <code>String<\/code> object cannot be changed after the object is created. Operations such as concatenation or replacement return another string value rather than modifying the original object.<\/p><pre class=\"wp-block-code\"><code>String message = \"Java\";\nmessage.concat(\" Interview\");\n\nSystem.out.println(message); \/\/ Java\n\nmessage = message.concat(\" Interview\");\nSystem.out.println(message); \/\/ Java Interview<\/code><\/pre><p class=\"wp-block-paragraph\">In the first operation, the result of <code>concat()<\/code> is discarded. In the second, the variable is reassigned to reference the resulting string. Neither operation changes the original string object.<\/p><p class=\"wp-block-paragraph\">Immutability provides several practical benefits:<\/p><ul class=\"wp-block-list\">\n<li><strong>Safe sharing:<\/strong> Different parts of an application can reference the same string without the risk that one changes its contents.<\/li>\n\n\n\n<li><strong>String pooling:<\/strong> Equal string literals can share interned string instances safely because their values do not change.<\/li>\n\n\n\n<li><strong>Reliable map keys:<\/strong> Stable string values support consistent <code>hashCode()<\/code> and <code>equals()<\/code> behaviour when strings are used as hash-based collection keys.<\/li>\n\n\n\n<li><strong>Predictable API behaviour:<\/strong> Strings used for identifiers, class names and other parameters cannot have their character contents modified through another reference.<\/li>\n<\/ul><p class=\"wp-block-paragraph\"><strong>Technical distinction:<\/strong> Immutability does not mean a <code>String<\/code> variable cannot be reassigned. It means the existing object cannot be modified. Oracle&rsquo;s <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/25\/docs\/api\/java.base\/java\/lang\/String.html\" target=\"_blank\" rel=\"noopener noreferrer\">String API documentation<\/a> describes this behaviour.<\/p><h3 class=\"wp-block-heading\">12. What Is the Difference Between HashMap and HashSet in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>HashMap<\/strong> stores key-value mappings, while <strong>HashSet<\/strong> stores a set of unique elements. Both use hashing, but they solve different problems.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>HashMap<\/th><th>HashSet<\/th><\/tr><\/thead><tbody><tr><td>Implements the Map interface<\/td><td>Implements the Set interface<\/td><\/tr><tr><td>Stores keys associated with values<\/td><td>Stores unique elements<\/td><\/tr><tr><td>Each key occurs at most once; values may repeat<\/td><td>Duplicate elements are not retained<\/td><\/tr><tr><td>Permits one null key and multiple null values<\/td><td>Permits a null element<\/td><\/tr><tr><td>Does not guarantee iteration order<\/td><td>Does not guarantee iteration order<\/td><\/tr><tr><td>Not synchronised by default<\/td><td>Not synchronised by default<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Correct Java example:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\n\nMap&lt;Integer, String&gt; students = new HashMap&lt;&gt;();\n\nstudents.put(1, \"Anushka\");\nstudents.put(2, \"Akansha\");\nstudents.put(1, \"Anjana\");\n\nSystem.out.println(students.get(1)); \/\/ Anjana\n\nSet&lt;String&gt; names = new HashSet&lt;&gt;();\n\nnames.add(\"Anushka\");\nnames.add(\"Akansha\");\nnames.add(\"Anushka\");\n\nSystem.out.println(names.size()); \/\/ 2<\/code><\/pre><p class=\"wp-block-paragraph\">In the <code>HashMap<\/code>, adding a value for the existing key <code>1<\/code> replaces the previous mapping. In the <code>HashSet<\/code>, adding <code>\"Anushka\"<\/code> twice does not increase the number of elements.<\/p><p class=\"wp-block-paragraph\"><strong>Interview scenario:<\/strong> Use <code>HashMap<\/code> when you need to look up a value using a unique key, such as an employee ID. Use <code>HashSet<\/code> when you need to track unique values, such as distinct email addresses, without storing an additional mapped value.<\/p><p class=\"wp-block-paragraph\">The behaviour of hash-based collections also depends on consistent equality and hashing. Custom key or element classes should implement <code>equals()<\/code> and <code>hashCode()<\/code> correctly, and fields involved in equality should not be mutated in ways that invalidate their use in a hash-based collection.<\/p><p class=\"wp-block-paragraph\">For the formal API contract, see Oracle&rsquo;s <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/25\/docs\/api\/java.base\/java\/util\/HashMap.html\" target=\"_blank\" rel=\"noopener noreferrer\">HashMap documentation<\/a>.<\/p><h3 class=\"wp-block-heading\">13. What Is the Producer-Consumer Problem in Java?<\/h3><p class=\"wp-block-paragraph\">The <strong>producer-consumer problem<\/strong> is a concurrency scenario in which one or more producer threads generate data while consumer threads process it. The threads communicate through a shared buffer or queue.<\/p><p class=\"wp-block-paragraph\">Two situations must be handled correctly: a producer should wait or apply an appropriate backpressure strategy when a bounded queue is full, and a consumer should wait when there is no item available to process.<\/p><p class=\"wp-block-paragraph\">Java provides the <code>BlockingQueue<\/code> interface for coordinating this behaviour. Its <code>put()<\/code> method waits for space when used with a full bounded blocking queue, while <code>take()<\/code> waits until an element becomes available.<\/p><p class=\"wp-block-paragraph\"><strong>Example using ArrayBlockingQueue:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\n\npublic class ProducerConsumerExample  \n            } catch (InterruptedException e)  \n        });\n\n        Thread consumer = new Thread(() -&gt;  \n            } catch (InterruptedException e)  \n        });\n\n        producer.start();\n        consumer.start();\n\n        producer.join();\n        consumer.join();\n    }\n}<\/code><\/pre><p class=\"wp-block-paragraph\">This example produces and consumes five integers. The bounded queue coordinates the threads without requiring the application to implement low-level <code>wait()<\/code> and <code>notify()<\/code> logic. A real application also needs an appropriate shutdown mechanism, error handling and a strategy for consumers to know when production has finished.<\/p><p class=\"wp-block-paragraph\"><strong>Advantages:<\/strong> Producers and consumers can operate at different speeds, their implementations remain loosely coupled, and a bounded queue can help control the amount of work waiting to be processed.<\/p><p class=\"wp-block-paragraph\"><strong>Interview consideration:<\/strong> Explain why queue capacity matters. An unbounded queue may allow pending work to accumulate, while a bounded queue can apply backpressure when consumers cannot keep up.<\/p><h3 class=\"wp-block-heading\">14. How Do You Create an Immutable Class in Java?<\/h3><p class=\"wp-block-paragraph\">An <strong>immutable class<\/strong> represents objects whose observable state cannot change after construction. The class must prevent callers from modifying its internal state, including through references to mutable objects.<\/p><p class=\"wp-block-paragraph\">Common techniques include:<\/p><ul class=\"wp-block-list\">\n<li>Prevent subclass behaviour from breaking immutability, commonly by declaring the class <code>final<\/code>.<\/li>\n\n\n\n<li>Declare instance fields <code>private<\/code> and, where appropriate, <code>final<\/code>.<\/li>\n\n\n\n<li>Initialise the object&rsquo;s state during construction and do not provide mutating methods.<\/li>\n\n\n\n<li>Make defensive copies of mutable input objects when necessary.<\/li>\n\n\n\n<li>Do not expose internal mutable objects directly through getters.<\/li>\n<\/ul><p class=\"wp-block-paragraph\"><strong>Example with a mutable List input:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.List;\n\npublic final class Employee  \n\n    public String getName()  \n\n    public List&lt;String&gt; getSkills()  \n}<\/code><\/pre><p class=\"wp-block-paragraph\"><code>List.copyOf()<\/code>, available from Java 10, creates an unmodifiable list that does not reflect later structural changes to the supplied list. Because the elements in this example are immutable strings, callers cannot change the employee&rsquo;s skills through mutable element objects.<\/p><p class=\"wp-block-paragraph\"><strong>Important:<\/strong> A <code>final<\/code> reference prevents reassignment of the field, but it does not automatically make the referenced object immutable. If a field contains mutable elements, an unmodifiable collection alone may not be sufficient; element-level defensive copying may also be required.<\/p><h3 class=\"wp-block-heading\">15. What Is the Difference Between Fail-Fast and Fail-Safe Iterators in Java?<\/h3><p class=\"wp-block-paragraph\">The terms <strong>fail-fast<\/strong> and <strong>fail-safe<\/strong> are frequently used in Java interviews, but they require careful explanation. Java&rsquo;s Collections Framework documentation uses more precise descriptions such as <strong>snapshot<\/strong> and <strong>weakly consistent<\/strong> iteration for several concurrent collections.<\/p><p class=\"wp-block-paragraph\">A fail-fast iterator may throw <code>ConcurrentModificationException<\/code> if a collection is structurally modified outside the iterator&rsquo;s permitted modification operations during traversal. This detection is generally best-effort and must not be relied upon for thread safety.<\/p><p class=\"wp-block-paragraph\">For example, iterators from ordinary <code>ArrayList<\/code> and <code>HashMap<\/code> are typically fail-fast.<\/p><p class=\"wp-block-paragraph\">Other collections provide different iteration semantics:<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>Iterator Behaviour<\/th><th>Example<\/th><th>What Happens During Modification?<\/th><\/tr><\/thead><tbody><tr><td>Fail-fast<\/td><td><code>ArrayList<\/code><\/td><td>May throw <code>ConcurrentModificationException<\/code> after an unsupported structural modification; detection is best-effort<\/td><\/tr><tr><td>Snapshot<\/td><td><code>CopyOnWriteArrayList<\/code><\/td><td>Traverses a snapshot from iterator creation and does not reflect later changes<\/td><\/tr><tr><td>Weakly consistent<\/td><td><code>ConcurrentHashMap<\/code><\/td><td>Can tolerate concurrent updates and may reflect some modifications made during traversal<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Example of snapshot iteration:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.Iterator;\nimport java.util.concurrent.CopyOnWriteArrayList;\n\nCopyOnWriteArrayList&lt;String&gt; names =\n        new CopyOnWriteArrayList&lt;&gt;();\n\nnames.add(\"A\");\nnames.add(\"B\");\n\nIterator&lt;String&gt; iterator = names.iterator();\n\nnames.add(\"C\");\n\nwhile (iterator.hasNext())  \n\n\/\/ Output:\n\/\/ A\n\/\/ B<\/code><\/pre><p class=\"wp-block-paragraph\">The iterator does not include <code>C<\/code> because the snapshot was created before that element was added.<\/p><p class=\"wp-block-paragraph\"><strong>Interview tip:<\/strong> Do not state that every iterator described as fail-safe works on a cloned collection. Snapshot and weakly consistent iterators have different contracts. Oracle&rsquo;s <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/25\/docs\/api\/java.base\/java\/util\/concurrent\/CopyOnWriteArrayList.html\" target=\"_blank\" rel=\"noopener noreferrer\">CopyOnWriteArrayList documentation<\/a> describes snapshot iteration explicitly.<\/p><div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"867\" height=\"558\" src=\"https:\/\/media.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-17.png\" alt=\"Illustration comparing fail-fast and fail-safe iteration terminology in Java collections\" class=\"wp-image-42610\" style=\"width:483px;height:auto\" srcset=\"https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-17.png 867w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-17-300x193.png 300w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-17-768x494.png 768w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-17-696x448.png 696w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-17-150x97.png 150w\" sizes=\"auto, (max-width: 867px) 100vw, 867px\"><\/figure>\n<\/div><h3 class=\"wp-block-heading\">16. What Is an Interface in Java, and What Features Does It Support?<\/h3><p class=\"wp-block-paragraph\">A <strong>Java interface<\/strong> defines a reference type that can declare abstract methods, constants and several kinds of methods with implementations. Interfaces help separate an API contract from its implementations and support polymorphism.<\/p><p class=\"wp-block-paragraph\">Important features include:<\/p><ul class=\"wp-block-list\">\n<li><strong>Abstract methods:<\/strong> Declare behaviour that an implementing concrete class normally needs to provide unless an implementation is inherited.<\/li>\n\n\n\n<li><strong>Default methods:<\/strong> Provide inherited method implementations, introduced in Java 8.<\/li>\n\n\n\n<li><strong>Static methods:<\/strong> Belong to the interface itself and can be called using the interface name.<\/li>\n\n\n\n<li><strong>Private methods:<\/strong> Supported since Java 9, allowing code reuse inside interface method implementations.<\/li>\n\n\n\n<li><strong>Constants:<\/strong> Interface fields are implicitly <code>public static final<\/code>.<\/li>\n\n\n\n<li><strong>Multiple interface implementation:<\/strong> A class can implement more than one interface, subject to the language&rsquo;s inheritance and conflict rules.<\/li>\n<\/ul><p class=\"wp-block-paragraph\">Interfaces do not have instance fields or constructors. They may also declare nested types and can extend other interfaces.<\/p><p class=\"wp-block-paragraph\"><strong>Example:<\/strong><\/p><pre class=\"wp-block-code\"><code>interface PaymentProcessor  \n}\n\nclass CardPayment implements PaymentProcessor  \n}<\/code><\/pre><p class=\"wp-block-paragraph\">Here, <code>CardPayment<\/code> implements the abstract <code>process()<\/code> method and inherits the default <code>printReceipt()<\/code> implementation.<\/p><p class=\"wp-block-paragraph\"><strong>Practical application:<\/strong> In a payment-processing system, multiple implementations can follow the same interface while using different underlying services. This allows calling code to depend on a common contract rather than on one concrete provider.<\/p><div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"956\" height=\"538\" src=\"https:\/\/media.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-20.png\" alt=\"Diagram illustrating Java interfaces, multiple interface implementation and abstract, default and static methods\" class=\"wp-image-42613\" style=\"width:549px;height:auto\" srcset=\"https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-20.png 956w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-20-300x169.png 300w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-20-768x432.png 768w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-20-696x392.png 696w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-20-150x84.png 150w\" sizes=\"auto, (max-width: 956px) 100vw, 956px\"><\/figure>\n<\/div><h3 class=\"wp-block-heading\">17. What Are the Five SOLID Principles in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>SOLID<\/strong> refers to five object-oriented design principles intended to improve maintainability, flexibility and separation of responsibilities. They are design guidelines rather than Java-specific language features or rules that must always be applied mechanically.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>Principle<\/th><th>Meaning<\/th><th>Practical Java Example<\/th><\/tr><\/thead><tbody><tr><td>Single Responsibility Principle (SRP)<\/td><td>A module or class should have one primary reason to change<\/td><td>Separate invoice calculations from invoice email delivery<\/td><\/tr><tr><td>Open\/Closed Principle (OCP)<\/td><td>Software components should support extension without unnecessary modification of existing code<\/td><td>Add another payment implementation through a common interface<\/td><\/tr><tr><td>Liskov Substitution Principle (LSP)<\/td><td>Subtypes should preserve the behavioural expectations of their base types<\/td><td>A replacement implementation must honour the interface&rsquo;s contractual behaviour<\/td><\/tr><tr><td>Interface Segregation Principle (ISP)<\/td><td>Clients should not depend on operations they do not use<\/td><td>Use focused interfaces instead of a large unrelated API<\/td><\/tr><tr><td>Dependency Inversion Principle (DIP)<\/td><td>High-level policy and implementation details should depend on suitable abstractions<\/td><td>Inject a <code>PaymentProcessor<\/code> dependency rather than constructing a specific implementation internally<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Interview scenario:<\/strong> Suppose an order service calculates totals, sends emails and writes directly to a particular database. You could explain how separating responsibilities and depending on interfaces may make the service easier to test and change.<\/p><p class=\"wp-block-paragraph\">Also explain the trade-off: introducing too many abstractions can make a small application unnecessarily complicated. Good design depends on the problem, change requirements and maintenance needs.<\/p><figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"550\" src=\"https:\/\/media.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-22-1024x550.png\" alt=\"Infographic showing the five SOLID software design principles: single responsibility, open-closed, Liskov substitution, interface segregation and dependency inversion\" class=\"wp-image-42617\" srcset=\"https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-22-1024x550.png 1024w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-22-300x161.png 300w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-22-768x413.png 768w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-22-696x374.png 696w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-22-1068x574.png 1068w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-22-150x81.png 150w, https:\/\/www.foundit.in\/career-advice\/wp-content\/uploads\/2024\/10\/image-22.png 1461w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\"><\/figure><h3 class=\"wp-block-heading\">18. What Is a Package in Java?<\/h3><p class=\"wp-block-paragraph\">A <strong>Java package<\/strong> groups related classes, interfaces and other types within a namespace. Packages help organise source code, reduce naming conflicts and support access control.<\/p><p class=\"wp-block-paragraph\">Java provides built-in packages such as <code>java.lang<\/code>, <code>java.util<\/code> and <code>java.time<\/code>. Developers also create packages for application features and components.<\/p><p class=\"wp-block-paragraph\"><strong>Example:<\/strong><\/p><pre class=\"wp-block-code\"><code>package com.example.orders;\n\npublic class OrderService  \n}<\/code><\/pre><p class=\"wp-block-paragraph\">In this example, <code>OrderService<\/code> belongs to the <code>com.example.orders<\/code> package. Other classes can import it when access rules permit.<\/p><p class=\"wp-block-paragraph\"><strong>Important distinction:<\/strong> Packages organise types, while Java modules introduced in Java 9 add mechanisms for declaring dependencies and controlling which packages are exported or opened.<\/p><h3 class=\"wp-block-heading\">19. What Is the Difference Between List and Set in Java?<\/h3><p class=\"wp-block-paragraph\">Both <code>List<\/code> and <code>Set<\/code> are interfaces in the Java Collections Framework, but they have different contracts for duplicates and element organisation.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>List<\/th><th>Set<\/th><\/tr><\/thead><tbody><tr><td>Ordered collection with positional access<\/td><td>Collection containing no duplicate elements<\/td><\/tr><tr><td>Allows duplicate elements<\/td><td>Does not allow duplicate elements under its equality rules<\/td><\/tr><tr><td>Supports positional operations such as <code>get(index)<\/code><\/td><td>Does not provide general positional access by index<\/td><\/tr><tr><td>Examples: <code>ArrayList<\/code>, <code>LinkedList<\/code><\/td><td>Examples: <code>HashSet<\/code>, <code>LinkedHashSet<\/code>, <code>TreeSet<\/code><\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\">A <code>Set<\/code> is not necessarily unordered. <code>HashSet<\/code> does not guarantee iteration order, <code>LinkedHashSet<\/code> maintains a defined encounter order, and <code>TreeSet<\/code> sorts elements according to their natural ordering or a supplied comparator.<\/p><p class=\"wp-block-paragraph\"><strong>Practical example:<\/strong> Use a <code>List<\/code> to preserve an ordered sequence of transactions where duplicates are meaningful. Use a <code>Set<\/code> to track distinct identifiers when duplicates should be excluded.<\/p><h3 class=\"wp-block-heading\">20. What Are Generics in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>Generics<\/strong> allow classes, interfaces and methods to work with type parameters. They improve compile-time type checking and make reusable APIs more expressive.<\/p><p class=\"wp-block-paragraph\">For example, <code>List&lt;String&gt;<\/code> communicates that the list is intended to hold strings, and the compiler rejects attempts to add an incompatible value through a correctly typed reference.<\/p><pre class=\"wp-block-code\"><code>import java.util.ArrayList;\nimport java.util.List;\n\nList&lt;String&gt; names = new ArrayList&lt;&gt;();\n\nnames.add(\"Anushka\");\nnames.add(\"Akansha\");\n\n\/\/ names.add(100); \/\/ Compile-time error\n\nString firstName = names.get(0);\nSystem.out.println(firstName);<\/code><\/pre><p class=\"wp-block-paragraph\">Java generics use <strong>type erasure<\/strong>: most generic type arguments are not retained as distinct runtime class identities. For example, <code>List&lt;String&gt;<\/code> and <code>List&lt;Integer&gt;<\/code> do not represent two different runtime implementations of <code>ArrayList<\/code>.<\/p><p class=\"wp-block-paragraph\"><strong>Interview consideration:<\/strong> Be prepared to explain why <code>List&lt;Integer&gt;<\/code> cannot be assigned to <code>List&lt;Number&gt;<\/code>. Java generic types are ordinarily invariant. Wildcards such as <code>? extends Number<\/code> and <code>? super Integer<\/code> can express appropriate relationships for reading and writing values.<\/p><h3 class=\"wp-block-heading\">21. What Does the synchronized Keyword Do in Java?<\/h3><p class=\"wp-block-paragraph\">The <code>synchronized<\/code> keyword provides mutual exclusion using an object&rsquo;s monitor lock. A thread must acquire the relevant monitor before entering a synchronised instance method or block protected by that monitor.<\/p><p class=\"wp-block-paragraph\">Synchronisation also establishes memory visibility and ordering guarantees through monitor release and subsequent acquisition of the same lock.<\/p><p class=\"wp-block-paragraph\"><strong>Example of a synchronised counter:<\/strong><\/p><pre class=\"wp-block-code\"><code>class Counter  \n\n    public synchronized int getCount()  \n}<\/code><\/pre><p class=\"wp-block-paragraph\">When multiple threads use the same <code>Counter<\/code> instance and access its state through these methods, the monitor protects the increment operation and establishes the required visibility.<\/p><p class=\"wp-block-paragraph\"><strong>Important distinction:<\/strong> Synchronisation only provides the intended protection when every relevant operation follows a consistent locking strategy. It does not automatically protect unrelated access to the same variable.<\/p><h3 class=\"wp-block-heading\">22. What Are Lambda Expressions in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>Lambda expressions<\/strong>, introduced in Java 8, provide a concise way to implement the single abstract method of a functional interface. They are commonly used with collection operations, streams and callback-style APIs.<\/p><p class=\"wp-block-paragraph\"><strong>Example:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.function.Predicate;\n\nPredicate&lt;String&gt; isLongName =\n        name -&gt; name.length() &gt; 5;\n\nSystem.out.println(isLongName.test(\"Anushka\")); \/\/ true\nSystem.out.println(isLongName.test(\"Ravi\"));    \/\/ false<\/code><\/pre><p class=\"wp-block-paragraph\">The lambda supplies the implementation of the <code>Predicate.test()<\/code> method. Its target type is the functional interface <code>Predicate&lt;String&gt;<\/code>.<\/p><p class=\"wp-block-paragraph\">In interviews, explain both how a lambda works and when it improves readability. A complex lambda containing extensive branching may be clearer as a named method.<\/p><h3 class=\"wp-block-heading\">23. What Is a Functional Interface in Java?<\/h3><p class=\"wp-block-paragraph\">A <strong>functional interface<\/strong> has exactly one abstract method for the purpose of functional-interface compatibility. Abstract methods corresponding to public methods of <code>Object<\/code> are not counted in the usual way.<\/p><p class=\"wp-block-paragraph\">Functional interfaces can also contain default, static and, in supported Java versions, private methods. The <code>@FunctionalInterface<\/code> annotation is optional but asks the compiler to verify that the interface meets the requirements.<\/p><pre class=\"wp-block-code\"><code>@FunctionalInterface\ninterface Calculator  \n\nCalculator addition = (a, b) -&gt; a + b;\n\nSystem.out.println(addition.calculate(4, 5)); \/\/ 9<\/code><\/pre><p class=\"wp-block-paragraph\">Common built-in functional interfaces include <code>Predicate<\/code>, <code>Function<\/code>, <code>Consumer<\/code>, <code>Supplier<\/code> and <code>Runnable<\/code>.<\/p><p class=\"wp-block-paragraph\"><strong>Practical distinction:<\/strong> A lambda expression needs a compatible target type. It is not an independent named method declaration.<\/p><h3 class=\"wp-block-heading\">24. What Is the Difference Between throw and throws in Java?<\/h3><p class=\"wp-block-paragraph\">The <code>throw<\/code> statement explicitly throws an exception object, while the <code>throws<\/code> clause declares exception types that a method or constructor can propagate.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>throw<\/th><th>throws<\/th><\/tr><\/thead><tbody><tr><td>Used within executable code<\/td><td>Appears in a method or constructor declaration<\/td><\/tr><tr><td>Throws a particular exception object<\/td><td>Lists exception types that may be propagated<\/td><\/tr><tr><td>Example: <code>throw new IllegalArgumentException();<\/code><\/td><td>Example: <code>void read() throws IOException<\/code><\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Example:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.io.IOException;\n\nclass FileService  \n}<\/code><\/pre><p class=\"wp-block-paragraph\">The method declaration includes <code>throws IOException<\/code>, while the method body contains the <code>throw<\/code> statement that creates and throws an exception.<\/p><p class=\"wp-block-paragraph\">Checked exceptions generally need to be caught or declared by callers. Unchecked exceptions, such as subclasses of <code>RuntimeException<\/code>, do not carry the same compile-time catch-or-declare requirement.<\/p><h3 class=\"wp-block-heading\">25. What Is the Map Interface in Java?<\/h3><p class=\"wp-block-paragraph\">The <code>Map<\/code> interface represents a collection of key-value mappings. Each key maps to at most one value, so adding a new value for an existing key replaces the previous mapping.<\/p><p class=\"wp-block-paragraph\">Common implementations include:<\/p><ul class=\"wp-block-list\">\n<li><strong>HashMap:<\/strong> Does not guarantee iteration order and generally provides expected constant-time basic operations with suitably distributed hashes.<\/li>\n\n\n\n<li><strong>LinkedHashMap:<\/strong> Maintains a defined encounter order, normally insertion order, with an option for access ordering.<\/li>\n\n\n\n<li><strong>TreeMap:<\/strong> Keeps keys sorted by their natural ordering or a supplied comparator.<\/li>\n\n\n\n<li><strong>ConcurrentHashMap:<\/strong> Supports concurrent retrievals and updates without requiring one global lock for ordinary operations.<\/li>\n<\/ul><p class=\"wp-block-paragraph\"><strong>Practical scenario:<\/strong> A service may use a map to associate customer IDs with account information. The appropriate implementation depends on whether ordering, concurrency or other specific behaviour is needed.<\/p><p class=\"wp-block-paragraph\"><strong>Remember:<\/strong> <code>Map<\/code> is part of the Java Collections Framework but does not extend the <code>Collection<\/code> interface.<\/p><h3 class=\"wp-block-heading\">26. What Is the Difference Between HashMap and Hashtable in Java?<\/h3><p class=\"wp-block-paragraph\"><code>HashMap<\/code> and <code>Hashtable<\/code> both store key-value mappings, but they differ in synchronisation, null handling and historical usage.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>HashMap<\/th><th>Hashtable<\/th><\/tr><\/thead><tbody><tr><td>Not synchronised by default<\/td><td>Synchronises many public methods<\/td><\/tr><tr><td>Permits one null key and null values<\/td><td>Does not permit null keys or values<\/td><\/tr><tr><td>Widely used when external synchronisation is unnecessary<\/td><td>Legacy collection class<\/td><\/tr><tr><td>Compound operations require suitable coordination when shared<\/td><td>Synchronised methods do not automatically make sequences of operations atomic<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>When is ConcurrentHashMap preferable?<\/strong> In applications with multiple threads that need frequent concurrent access, <code>ConcurrentHashMap<\/code> is often more suitable than using a legacy <code>Hashtable<\/code>, depending on the required operations.<\/p><p class=\"wp-block-paragraph\">Unlike <code>HashMap<\/code>, <code>ConcurrentHashMap<\/code> does not permit null keys or null values. Its concurrency guarantees also differ from those of ordinary collections and should be understood before use.<\/p><h3 class=\"wp-block-heading\">27. What Is a Default Method in a Java Interface?<\/h3><p class=\"wp-block-paragraph\">A <strong>default method<\/strong> is an interface instance method declared with the <code>default<\/code> keyword and supplied with an implementation. Default methods were introduced in Java 8 to allow interfaces to evolve without necessarily requiring every existing implementing class to implement a new method.<\/p><pre class=\"wp-block-code\"><code>interface Notification  \n}\n\nclass EmailNotification implements Notification  \n}<\/code><\/pre><p class=\"wp-block-paragraph\">The <code>EmailNotification<\/code> class implements the abstract <code>send()<\/code> method and inherits the default <code>log()<\/code> implementation.<\/p><p class=\"wp-block-paragraph\">If a class inherits conflicting default methods from multiple interfaces, it may need to override the method and resolve the conflict explicitly. Class methods also take precedence over conflicting interface defaults under Java&rsquo;s inheritance rules.<\/p><p class=\"wp-block-paragraph\"><strong>Interview tip:<\/strong> Be able to explain the difference between abstract, default, static and private interface methods. Also explain why adding a default method can help maintain source compatibility, while acknowledging that interface evolution still requires attention to possible method conflicts.<\/p><h3 class=\"wp-block-heading\">28. What Are the Types of Nested Classes in Java?<\/h3><p class=\"wp-block-paragraph\">A <strong>nested class<\/strong> is a class declared within another class or interface. Java supports static nested classes and several forms of inner classes. Inner classes are nested classes that are not explicitly or implicitly static.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>Type<\/th><th>Characteristics<\/th><\/tr><\/thead><tbody><tr><td>Static nested class<\/td><td>Declared with <code>static<\/code>; does not require an instance of the enclosing class<\/td><\/tr><tr><td>Member inner class<\/td><td>Non-static member class associated with an enclosing object<\/td><\/tr><tr><td>Local class<\/td><td>Declared within a block, such as a method body<\/td><\/tr><tr><td>Anonymous class<\/td><td>Declared and instantiated in an expression without an explicit class name<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Example:<\/strong><\/p><pre class=\"wp-block-code\"><code>class Outer  \n    }\n\n    class Inner  \n    }\n}<\/code><\/pre><p class=\"wp-block-paragraph\">The static nested class can be instantiated as <code>new Outer.Nested()<\/code>. The non-static inner class requires an enclosing instance, such as <code>Outer outer = new Outer();<\/code> followed by <code>outer.new Inner()<\/code>.<\/p><p class=\"wp-block-paragraph\"><strong>Interview consideration:<\/strong> Explain how a non-static inner class has access to members of its enclosing instance, whereas a static nested class does not have an implicit reference to an enclosing object.<\/p><h3 class=\"wp-block-heading\">29. What Are Method References in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>Method references<\/strong>, introduced in Java 8, provide a concise way to refer to an existing method or constructor when a compatible functional interface is expected. They can replace certain lambda expressions without changing the intended operation.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>Method Reference Type<\/th><th>Syntax<\/th><\/tr><\/thead><tbody><tr><td>Static method<\/td><td><code>ClassName::staticMethod<\/code><\/td><\/tr><tr><td>Instance method of a particular object<\/td><td><code>object::instanceMethod<\/code><\/td><\/tr><tr><td>Instance method of an arbitrary object of a particular type<\/td><td><code>ClassName::instanceMethod<\/code><\/td><\/tr><tr><td>Constructor<\/td><td><code>ClassName::new<\/code><\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Example:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\nList&lt;String&gt; names = Arrays.asList(\"Ravi\", \"Ananya\", \"Priya\");\n\nnames.forEach(System.out::println);<\/code><\/pre><p class=\"wp-block-paragraph\">Here, <code>System.out::println<\/code> is a method reference compatible with the <code>Consumer<\/code> expected by <code>forEach()<\/code>. It is equivalent in purpose to <code>name -&gt; System.out.println(name)<\/code>.<\/p><p class=\"wp-block-paragraph\">Method references are useful when the referenced operation is already expressed clearly by a named method. A lambda may be more appropriate when additional logic or argument transformation is needed.<\/p><h3 class=\"wp-block-heading\">30. What Are the Main Features Introduced in Java 8?<\/h3><p class=\"wp-block-paragraph\">Java 8 introduced language and library features that remain important in modern Java development and technical interviews.<\/p><ul class=\"wp-block-list\">\n<li><strong>Lambda expressions:<\/strong> Provide concise implementations of functional interfaces.<\/li>\n\n\n\n<li><strong>Stream API:<\/strong> Supports declarative operations such as filtering, mapping and aggregation.<\/li>\n\n\n\n<li><strong>Default interface methods:<\/strong> Allow interfaces to provide inherited method implementations.<\/li>\n\n\n\n<li><strong>Method references:<\/strong> Refer to existing methods or constructors using the <code>::<\/code> operator.<\/li>\n\n\n\n<li><strong>Optional:<\/strong> Represents a value that may be present or absent.<\/li>\n\n\n\n<li><strong>Modern Date and Time API:<\/strong> Introduced types such as <code>LocalDate<\/code>, <code>Instant<\/code> and <code>ZonedDateTime<\/code>.<\/li>\n<\/ul><p class=\"wp-block-paragraph\"><strong>Example using a stream:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\nList&lt;String&gt; names =\n        Arrays.asList(\"Ravi\", \"Ananya\", \"Priya\");\n\nList&lt;String&gt; result = names.stream()\n        .filter(name -&gt; name.length() &gt; 4)\n        .collect(Collectors.toList());\n\nSystem.out.println(result); \/\/ [Ananya, Priya]<\/code><\/pre><p class=\"wp-block-paragraph\"><strong>Interview tip:<\/strong> Be prepared to explain intermediate and terminal stream operations, the purpose of functional interfaces and situations where an ordinary loop is clearer than a stream pipeline.<\/p><h3 class=\"wp-block-heading\">31. What Is the try-with-resources Statement in Java?<\/h3><p class=\"wp-block-paragraph\">The <code>try-with-resources<\/code> statement automatically closes resources that implement <code>AutoCloseable<\/code>. Introduced in Java 7, it is commonly used with files, streams and database resources.<\/p><p class=\"wp-block-paragraph\">Resources declared in the statement are closed in reverse order of their initialisation, including when the code inside the <code>try<\/code> block throws an exception.<\/p><pre class=\"wp-block-code\"><code>import java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\n\nclass FileExample  \n    }\n}<\/code><\/pre><p class=\"wp-block-paragraph\">The reader is automatically closed when the statement completes. If both the main operation and resource closing throw exceptions, the closing exception may be recorded as a <strong>suppressed exception<\/strong> rather than replacing the primary exception.<\/p><p class=\"wp-block-paragraph\">Try-with-resources is usually preferable to manually closing resources in a <code>finally<\/code> block because it makes ownership and cleanup behaviour clearer.<\/p><h3 class=\"wp-block-heading\">32. What Is the Difference Between Comparable and Comparator in Java?<\/h3><p class=\"wp-block-paragraph\"><code>Comparable<\/code> defines a type&rsquo;s <strong>natural ordering<\/strong> through the <code>compareTo()<\/code> method. <code>Comparator<\/code> defines an external comparison strategy through <code>compare()<\/code>, allowing different ordering rules for the same type.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>Comparable<\/th><th>Comparator<\/th><\/tr><\/thead><tbody><tr><td>Implemented by the class being compared<\/td><td>Can be supplied separately from the class<\/td><\/tr><tr><td>Defines natural ordering using <code>compareTo()<\/code><\/td><td>Defines an ordering using <code>compare()<\/code><\/td><\/tr><tr><td>Typically provides one natural order<\/td><td>Supports multiple ordering strategies<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Example:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.Comparator;\nimport java.util.List;\n\nList&lt;String&gt; names =\n        Arrays.asList(\"Priya\", \"Al\", \"Ananya\");\n\nnames.sort(Comparator.comparingInt(String::length));\n\nSystem.out.println(names); \/\/ [Al, Priya, Ananya]<\/code><\/pre><p class=\"wp-block-paragraph\">The comparator sorts strings by length rather than their natural alphabetical order. In production code, consider how ties should be handled and use a secondary comparator when deterministic tie-breaking matters.<\/p><h3 class=\"wp-block-heading\">33. What Is the instanceof Operator in Java?<\/h3><p class=\"wp-block-paragraph\">The <code>instanceof<\/code> operator checks whether a reference refers to an object compatible with a specified type. It returns <code>false<\/code> for a null reference.<\/p><p class=\"wp-block-paragraph\">Java also supports <strong>pattern matching for instanceof<\/strong>, finalised in Java 16, which combines type testing with a pattern variable.<\/p><pre class=\"wp-block-code\"><code>Object value = \"Java Interview\";\n\nif (value instanceof String text)  <\/code><\/pre><p class=\"wp-block-paragraph\">Inside the applicable scope, <code>text<\/code> is treated as a <code>String<\/code> without requiring an explicit cast.<\/p><p class=\"wp-block-paragraph\"><strong>Version note:<\/strong> The pattern-matching syntax above requires Java 16 or later. For Java 8, use a conventional <code>instanceof<\/code> test followed by an explicit cast.<\/p><h3 class=\"wp-block-heading\">34. What Is the super Keyword in Java?<\/h3><p class=\"wp-block-paragraph\">The <code>super<\/code> keyword refers to the immediate superclass context from a subclass. It is commonly used to call a superclass constructor, access a hidden superclass field or invoke an overridden superclass method.<\/p><pre class=\"wp-block-code\"><code>class Employee  \n\n    void display()  \n}\n\nclass Developer extends Employee  \n\n    @Override\n    void display()  \n}<\/code><\/pre><p class=\"wp-block-paragraph\">Here, <code>super(name)<\/code> invokes the superclass constructor, while <code>super.display()<\/code> invokes the superclass implementation of <code>display()<\/code>.<\/p><p class=\"wp-block-paragraph\">In traditional Java constructor rules, an explicit superclass constructor invocation must appear at the beginning of the constructor body. Later Java versions have expanded certain constructor rules, so the exact behaviour should be considered in the context of the Java version being used.<\/p><h3 class=\"wp-block-heading\">35. What Is the finalize() Method in Java, and Should It Be Used?<\/h3><p class=\"wp-block-paragraph\">The <code>finalize()<\/code> method was historically intended to allow cleanup work before an object was reclaimed. However, Java never guaranteed that finalisation would occur promptly or even at all.<\/p><p class=\"wp-block-paragraph\"><strong>Finalisation is deprecated for removal.<\/strong> It creates reliability, performance and security concerns and should not be used as the normal mechanism for releasing files, network connections or other resources.<\/p><p class=\"wp-block-paragraph\">Prefer explicit cleanup through <code>AutoCloseable<\/code>, <code>close()<\/code> and try-with-resources. Specialised cleanup mechanisms such as <code>Cleaner<\/code> may be appropriate for particular cases, but they do not replace predictable resource ownership.<\/p><p class=\"wp-block-paragraph\">Oracle&rsquo;s <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/25\/docs\/api\/java.base\/java\/lang\/Object.html\" target=\"_blank\" rel=\"noopener noreferrer\">Object API documentation<\/a> identifies <code>finalize()<\/code> as deprecated for removal and explains the alternatives.<\/p><h3 class=\"wp-block-heading\">36. What Are the Main Interfaces in the Java Collections Framework?<\/h3><p class=\"wp-block-paragraph\">The <strong>Java Collections Framework<\/strong> provides interfaces and implementations for storing and manipulating groups of objects.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>Interface<\/th><th>Main Purpose<\/th><th>Common Implementations<\/th><\/tr><\/thead><tbody><tr><td><code>List<\/code><\/td><td>Ordered collections allowing duplicates<\/td><td><code>ArrayList<\/code>, <code>LinkedList<\/code><\/td><\/tr><tr><td><code>Set<\/code><\/td><td>Collections without duplicate elements<\/td><td><code>HashSet<\/code>, <code>TreeSet<\/code><\/td><\/tr><tr><td><code>Queue<\/code><\/td><td>Holding elements before processing<\/td><td><code>ArrayDeque<\/code>, <code>PriorityQueue<\/code><\/td><\/tr><tr><td><code>Deque<\/code><\/td><td>Insertion and removal at both ends<\/td><td><code>ArrayDeque<\/code>, <code>LinkedList<\/code><\/td><\/tr><tr><td><code>Map<\/code><\/td><td>Associating keys with values<\/td><td><code>HashMap<\/code>, <code>TreeMap<\/code><\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><code>Collection<\/code> is the root interface for types such as <code>List<\/code>, <code>Set<\/code> and <code>Queue<\/code>. Although <code>Map<\/code> belongs to the Collections Framework, it does not extend <code>Collection<\/code>.<\/p><p class=\"wp-block-paragraph\"><strong>Interview scenario:<\/strong> Choose a collection according to the required behaviour. Use a list when positional ordering matters, a set for uniqueness, a map for key-based lookup and a queue for task processing.<\/p><h3 class=\"wp-block-heading\">37. What Is a Thread in Java?<\/h3><p class=\"wp-block-paragraph\">A <strong>thread<\/strong> is an execution path within a Java application. Multiple threads can execute tasks concurrently, allowing applications to handle overlapping work such as network requests, background processing and scheduled operations.<\/p><p class=\"wp-block-paragraph\">Modern Java supports both traditional <strong>platform threads<\/strong> and <strong>virtual threads<\/strong>. Virtual threads became a permanent feature in Java 21 and are particularly useful for many concurrent tasks that spend significant time waiting for blocking I\/O.<\/p><p class=\"wp-block-paragraph\">Threads introduce coordination requirements when they share mutable state. Concurrency does not automatically improve throughput: contention, scheduling and blocking can still affect performance.<\/p><p class=\"wp-block-paragraph\"><strong>Interview tip:<\/strong> Be able to distinguish concurrency from parallelism. Concurrent tasks can make progress over overlapping periods, while parallel execution means work is executing simultaneously on multiple processing resources.<\/p><h3 class=\"wp-block-heading\">38. How Do You Create and Start a Thread in Java?<\/h3><p class=\"wp-block-paragraph\">Traditional approaches include extending <code>Thread<\/code> or implementing <code>Runnable<\/code>. In many applications, implementing <code>Runnable<\/code> or submitting tasks to an executor provides better separation between the task and its execution mechanism.<\/p><p class=\"wp-block-paragraph\"><strong>Example using Runnable:<\/strong><\/p><pre class=\"wp-block-code\"><code>public class ThreadExample  \n}<\/code><\/pre><p class=\"wp-block-paragraph\"><code>start()<\/code> arranges for a new thread to execute the task. Calling <code>run()<\/code> directly would execute the method on the calling thread rather than starting a separate thread.<\/p><p class=\"wp-block-paragraph\"><strong>Modern Java example:<\/strong> Java 21 and later support <code>Thread.startVirtualThread(task)<\/code> for starting a virtual thread. The choice between platform threads, virtual threads and executors depends on workload and lifecycle requirements.<\/p><h3 class=\"wp-block-heading\">39. What Is a Deadlock in Java?<\/h3><p class=\"wp-block-paragraph\">A <strong>deadlock<\/strong> occurs when threads are blocked in a cycle of resource dependencies and none can make progress.<\/p><p class=\"wp-block-paragraph\">For example, Thread A holds Lock 1 and waits for Lock 2, while Thread B holds Lock 2 and waits for Lock 1. Both remain blocked because neither can acquire the lock required to continue.<\/p><p class=\"wp-block-paragraph\">Common prevention and mitigation strategies include:<\/p><ul class=\"wp-block-list\">\n<li><strong>Consistent lock ordering:<\/strong> Acquire multiple locks in the same predefined order.<\/li>\n\n\n\n<li><strong>Smaller critical sections:<\/strong> Avoid holding locks longer than necessary.<\/li>\n\n\n\n<li><strong>Timed lock acquisition:<\/strong> Consider mechanisms such as <code>ReentrantLock.tryLock()<\/code> when suitable.<\/li>\n\n\n\n<li><strong>Diagnostics:<\/strong> Inspect thread dumps and lock ownership to identify blocked threads and dependency cycles.<\/li>\n<\/ul><p class=\"wp-block-paragraph\"><strong>Practical interview scenario:<\/strong> Describe a situation in which two services acquire shared locks in different orders. Explain how standardising lock acquisition order can prevent a circular wait.<\/p><h3 class=\"wp-block-heading\">40. What Is the clone() Method in Java?<\/h3><p class=\"wp-block-paragraph\">The <code>clone()<\/code> method, inherited from <code>Object<\/code>, provides a mechanism for copying objects. The conventional implementation of <code>Object.clone()<\/code> performs a <strong>shallow copy<\/strong>, meaning reference fields in the copy generally refer to the same objects as the original.<\/p><p class=\"wp-block-paragraph\">Classes using the conventional cloning mechanism normally implement <code>Cloneable<\/code>. Otherwise, calling <code>Object.clone()<\/code> typically results in <code>CloneNotSupportedException<\/code>.<\/p><p class=\"wp-block-paragraph\"><strong>Example of a shallow-copy limitation:<\/strong> If an employee object contains a mutable list, cloning the employee without copying that list can leave the original and clone referring to the same list.<\/p><p class=\"wp-block-paragraph\">Copy constructors, static factory methods or explicit copying operations are often clearer alternatives because they allow developers to specify precisely which fields and nested objects must be copied.<\/p><h3 class=\"wp-block-heading\">41. What Is a Queue in Java?<\/h3><p class=\"wp-block-paragraph\">The <code>Queue<\/code> interface represents a collection intended to hold elements before processing. Many queue implementations follow First-In-First-Out (FIFO) ordering, but not every queue uses FIFO.<\/p><p class=\"wp-block-paragraph\">For example, <code>ArrayDeque<\/code> supports FIFO operations, whereas <code>PriorityQueue<\/code> retrieves elements according to their priority ordering.<\/p><p class=\"wp-block-paragraph\"><strong>Example using ArrayDeque:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.ArrayDeque;\nimport java.util.Queue;\n\nQueue&lt;String&gt; tasks = new ArrayDeque&lt;&gt;();\n\ntasks.offer(\"Task A\");\ntasks.offer(\"Task B\");\n\nSystem.out.println(tasks.poll()); \/\/ Task A\nSystem.out.println(tasks.peek()); \/\/ Task B<\/code><\/pre><p class=\"wp-block-paragraph\">The <code>offer()<\/code> method attempts to add an element, <code>poll()<\/code> retrieves and removes the head or returns <code>null<\/code> when empty, and <code>peek()<\/code> retrieves the head without removing it.<\/p><p class=\"wp-block-paragraph\">For communication between threads, a suitable <code>BlockingQueue<\/code> implementation can provide waiting behaviour and coordination that ordinary <code>ArrayDeque<\/code> does not provide.<\/p><h3 class=\"wp-block-heading\">42. What Is Synchronisation in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>Synchronisation<\/strong> coordinates access to shared mutable data between threads. It can prevent race conditions and establish memory visibility guarantees when all relevant operations follow a correct synchronisation strategy.<\/p><p class=\"wp-block-paragraph\">Java provides several mechanisms, including:<\/p><ul class=\"wp-block-list\">\n<li><strong><code>synchronized<\/code> methods and blocks:<\/strong> Protect code using monitor locks.<\/li>\n\n\n\n<li><strong><code>ReentrantLock<\/code>:<\/strong> Provides explicit locking with features such as timed acquisition and interruptible lock waits.<\/li>\n\n\n\n<li><strong>Atomic classes:<\/strong> Support atomic operations on selected shared values.<\/li>\n\n\n\n<li><strong>Concurrent collections:<\/strong> Provide documented thread-safe operations for common data structures.<\/li>\n<\/ul><p class=\"wp-block-paragraph\"><strong>Practical distinction:<\/strong> Synchronisation is broader than simply adding the <code>synchronized<\/code> keyword. A correct concurrency design must identify shared state, define the operations that must be atomic and apply the appropriate coordination mechanism consistently.<\/p><h3 class=\"wp-block-heading\">43. What Is the Difference Between Shallow Copy and Deep Copy?<\/h3><p class=\"wp-block-paragraph\">A <strong>shallow copy<\/strong> creates a separate outer object but generally retains references to the same nested objects. Modifications to shared mutable nested objects may therefore be visible through both copies.<\/p><p class=\"wp-block-paragraph\">A <strong>deep copy<\/strong> creates independent copies of the relevant nested mutable state, so changes to one copied object graph do not affect the corresponding objects in the other.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>Shallow Copy<\/th><th>Deep Copy<\/th><\/tr><\/thead><tbody><tr><td>Creates a new outer object<\/td><td>Creates a new outer object and independently copies relevant nested state<\/td><\/tr><tr><td>Nested mutable objects may remain shared<\/td><td>Relevant nested mutable objects are not shared<\/td><\/tr><tr><td>Often simpler and less expensive<\/td><td>May require more memory and copying work<\/td><\/tr><tr><td>Appropriate when sharing referenced state is safe<\/td><td>Useful when the copy must be independent<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Interview example:<\/strong> A copied order object with a shared mutable item list is not independent. If the new order must be modified without changing the original, the list and any relevant mutable item objects also need suitable copying.<\/p><h3 class=\"wp-block-heading\">44. What Are Annotations in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>Annotations<\/strong> provide metadata associated with Java program elements such as classes, methods, fields and parameters. Compilers, frameworks and other tools can use this metadata for validation, configuration or code processing.<\/p><p class=\"wp-block-paragraph\">Examples include:<\/p><ul class=\"wp-block-list\">\n<li><strong><code>@Override<\/code>:<\/strong> Helps the compiler check that a method overrides or implements an appropriate inherited method.<\/li>\n\n\n\n<li><strong><code>@Deprecated<\/code>:<\/strong> Indicates that an API is discouraged for continued use.<\/li>\n\n\n\n<li><strong><code>@FunctionalInterface<\/code>:<\/strong> Checks that an interface satisfies functional-interface requirements.<\/li>\n\n\n\n<li><strong>Framework annotations:<\/strong> Tools such as Spring can inspect annotations for dependency injection and application configuration.<\/li>\n<\/ul><p class=\"wp-block-paragraph\">The <code>@Retention<\/code> meta-annotation controls whether an annotation is retained in source code, class files or at runtime. Not every annotation is available for reflection during execution.<\/p><h3 class=\"wp-block-heading\">45. What Is the Java Memory Model?<\/h3><p class=\"wp-block-paragraph\">The <strong>Java Memory Model (JMM)<\/strong> defines the rules governing how threads interact through shared memory, including visibility and ordering of reads and writes.<\/p><p class=\"wp-block-paragraph\">A central concept is the <strong>happens-before relationship<\/strong>, which helps determine when effects from one action must be visible to another.<\/p><p class=\"wp-block-paragraph\">Examples of happens-before relationships include:<\/p><ul class=\"wp-block-list\">\n<li>A monitor unlock happens-before a subsequent lock of the same monitor.<\/li>\n\n\n\n<li>A write to a volatile field happens-before a subsequent read of that field.<\/li>\n\n\n\n<li>Calling <code>Thread.start()<\/code> happens-before actions in the started thread.<\/li>\n\n\n\n<li>Actions in a thread happen-before another thread successfully returns from a <code>join()<\/code> waiting for its termination.<\/li>\n<\/ul><p class=\"wp-block-paragraph\"><strong>Practical scenario:<\/strong> If one thread writes a normal shared field and another reads it without suitable coordination, the second thread may not observe the update as expected. Correct synchronisation, volatile fields or appropriate concurrency utilities can establish the necessary guarantees.<\/p><h3 class=\"wp-block-heading\">46. What Is Reflection in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>Reflection<\/strong> allows Java programs to inspect classes, constructors, methods, fields and annotations at runtime using APIs including <code>java.lang.reflect<\/code>.<\/p><p class=\"wp-block-paragraph\">Frameworks use reflection for tasks such as dependency injection, object mapping, test discovery and dynamic invocation.<\/p><p class=\"wp-block-paragraph\"><strong>Example:<\/strong><\/p><pre class=\"wp-block-code\"><code>class Employee  \n}\n\nClass&lt;?&gt; type = Employee.class;\n\nfor (java.lang.reflect.Method method :\n        type.getDeclaredMethods())  <\/code><\/pre><p class=\"wp-block-paragraph\">The code lists methods declared directly by <code>Employee<\/code>. Reflection can also access constructors and fields, subject to Java&rsquo;s access-control and module-encapsulation rules.<\/p><p class=\"wp-block-paragraph\"><strong>Interview consideration:<\/strong> Discuss how reflection provides flexibility but can complicate refactoring, impose additional access restrictions and introduce overhead compared with direct method calls in some scenarios.<\/p><h3 class=\"wp-block-heading\">47. What Is the Purpose of the join() Method in Java?<\/h3><p class=\"wp-block-paragraph\">The <code>join()<\/code> method allows one thread to wait until another thread terminates. It is useful when a task must finish before the calling thread continues with dependent work.<\/p><pre class=\"wp-block-code\"><code>public class JoinExample  \n}<\/code><\/pre><p class=\"wp-block-paragraph\">The main thread waits for <code>worker<\/code> to terminate before printing the second message. The <code>join()<\/code> method can throw <code>InterruptedException<\/code> if the waiting thread is interrupted.<\/p><p class=\"wp-block-paragraph\"><strong>Practical distinction:<\/strong> <code>join()<\/code> waits for thread termination; it does not itself return a result from the task. For tasks that produce results, abstractions such as <code>Future<\/code> or <code>CompletableFuture<\/code> may be more suitable.<\/p><h3 class=\"wp-block-heading\">48. What Are the Benefits and Limitations of the Java Stream API?<\/h3><p class=\"wp-block-paragraph\">The <strong>Java Stream API<\/strong> supports declarative processing of data using operations such as filtering, mapping, sorting and aggregation. It was introduced in Java 8.<\/p><p class=\"wp-block-paragraph\"><strong>Example:<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.Arrays;\nimport java.util.List;\n\nList&lt;Integer&gt; numbers =\n        Arrays.asList(2, 5, 8, 11, 14);\n\nint sum = numbers.stream()\n        .filter(number -&gt; number % 2 == 0)\n        .mapToInt(Integer::intValue)\n        .sum();\n\nSystem.out.println(sum); \/\/ 24<\/code><\/pre><p class=\"wp-block-paragraph\">The stream selects even numbers and calculates their sum.<\/p><ul class=\"wp-block-list\">\n<li><strong>Clear data-processing pipelines:<\/strong> Operations such as <code>filter()<\/code>, <code>map()<\/code> and <code>collect()<\/code> can express transformations concisely.<\/li>\n\n\n\n<li><strong>Lazy intermediate operations:<\/strong> Intermediate operations generally execute when a terminal operation consumes the stream.<\/li>\n\n\n\n<li><strong>Parallel processing support:<\/strong> Parallel streams can distribute suitable operations across processing resources.<\/li>\n\n\n\n<li><strong>Trade-offs:<\/strong> Stream pipelines with side effects, shared mutable state or complex debugging requirements may be harder to reason about.<\/li>\n<\/ul><p class=\"wp-block-paragraph\"><strong>Interview tip:<\/strong> Explain why parallel streams do not always improve performance. Workload size, splitting overhead, contention, ordering constraints and the cost of individual operations all matter.<\/p><h3 class=\"wp-block-heading\">49. What Is the Difference Between == and equals() in Java?<\/h3><p class=\"wp-block-paragraph\">When used with object references, <code>==<\/code> checks whether both references identify the same object. The <code>equals()<\/code> method evaluates equality according to the class&rsquo;s implementation.<\/p><p class=\"wp-block-paragraph\">For primitive values, <code>==<\/code> compares the values after any applicable numeric promotion or other language conversion.<\/p><pre class=\"wp-block-code\"><code>String a = new String(\"Java\");\nString b = new String(\"Java\");\n\nSystem.out.println(a == b);      \/\/ false\nSystem.out.println(a.equals(b)); \/\/ true<\/code><\/pre><p class=\"wp-block-paragraph\">The references identify different objects, so <code>==<\/code> returns <code>false<\/code>. The strings contain the same character sequence, so <code>equals()<\/code> returns <code>true<\/code>.<\/p><p class=\"wp-block-paragraph\">Classes that override <code>equals()<\/code> should also implement <code>hashCode()<\/code> consistently. Equal objects must have equal hash codes for correct operation in hash-based collections.<\/p><p class=\"wp-block-paragraph\"><strong>Null-handling tip:<\/strong> Calling <code>a.equals(b)<\/code> throws <code>NullPointerException<\/code> when <code>a<\/code> is null. <code>Objects.equals(a, b)<\/code> supports null-safe equality comparisons.<\/p><h3 class=\"wp-block-heading\">50. What Is the Difference Between HashMap and ConcurrentHashMap in Java?<\/h3><p class=\"wp-block-paragraph\"><strong>HashMap<\/strong> is a general-purpose map implementation that is not synchronised by default. <strong>ConcurrentHashMap<\/strong> is designed to support concurrent access and updates by multiple threads.<\/p><p class=\"wp-block-paragraph\">The distinction becomes important when several threads share a map and may update it at the same time.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>HashMap<\/th><th>ConcurrentHashMap<\/th><\/tr><\/thead><tbody><tr><td>Not thread-safe for unsynchronised concurrent modification<\/td><td>Supports thread-safe concurrent retrievals and updates<\/td><\/tr><tr><td>Allows one null key and null values<\/td><td>Does not allow null keys or null values<\/td><\/tr><tr><td>Iterators are generally fail-fast on structural modification, with best-effort detection<\/td><td>Iterators are weakly consistent and can tolerate concurrent modification<\/td><\/tr><tr><td>Compound updates require appropriate external coordination<\/td><td>Provides atomic operations such as <code>compute()<\/code> and <code>merge()<\/code> for suitable updates<\/td><\/tr><tr><td>Suitable when concurrency control is unnecessary or handled elsewhere<\/td><td>Suitable for shared maps that require concurrent access<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\"><strong>Practical example: Counting events from concurrent tasks<\/strong><\/p><pre class=\"wp-block-code\"><code>import java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\nConcurrentMap&lt;String, Integer&gt; counts =\n        new ConcurrentHashMap&lt;&gt;();\n\ncounts.merge(\"login\", 1, Integer::sum);\ncounts.merge(\"login\", 1, Integer::sum);\n\nSystem.out.println(counts.get(\"login\")); \/\/ 2<\/code><\/pre><p class=\"wp-block-paragraph\"><code>merge()<\/code> performs the update atomically for the specified key. This avoids an unsafe read-modify-write sequence such as retrieving a value, incrementing it and writing it back without synchronisation.<\/p><p class=\"wp-block-paragraph\"><strong>Interview consideration:<\/strong> <code>ConcurrentHashMap<\/code> does not make an entire sequence of unrelated map operations one atomic transaction. When several updates must succeed together, additional coordination or a different design may be required.<\/p><p class=\"wp-block-paragraph\">Oracle&rsquo;s <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/25\/docs\/api\/java.base\/java\/util\/concurrent\/ConcurrentHashMap.html\" target=\"_blank\" rel=\"noopener noreferrer\">ConcurrentHashMap API documentation<\/a> describes its concurrency guarantees, restrictions on null values and atomic update methods.<\/p><h2 id=\"java-interview-key-takeaways\" class=\"wp-block-heading\">Key Takeaways for Java Interviews with 2 to 3 Years of Experience<\/h2><p class=\"wp-block-paragraph\">Java developers with <strong>2 to 3 years of experience<\/strong> should be prepared to explain how Java concepts work and where they apply in actual development. Knowing a definition is useful, but interviewers may also ask you to interpret code, compare implementation choices and describe problems you have solved.<\/p><p class=\"wp-block-paragraph\">Use the following revision checklist to identify areas that deserve additional practice.<\/p><figure class=\"wp-block-table\"><table><thead><tr><th>Topic<\/th><th>What to Practise<\/th><\/tr><\/thead><tbody><tr><td>Core Java and OOP<\/td><td>Overloading versus overriding, inheritance, interfaces, immutability and exception handling<\/td><\/tr><tr><td>Collections Framework<\/td><td>Choosing between List, Set and Map implementations; equality, hashing and iteration behaviour<\/td><\/tr><tr><td>Multithreading<\/td><td>Thread creation, synchronisation, volatile, race conditions, deadlocks and concurrent collections<\/td><\/tr><tr><td>Java 8 and later<\/td><td>Lambda expressions, streams, functional interfaces, method references and relevant newer language features<\/td><\/tr><tr><td>Practical coding<\/td><td>String and array operations, collection-based problems, debugging and explaining code output<\/td><\/tr><tr><td>Project experience<\/td><td>Explaining design decisions, exception handling, performance trade-offs, testing and production issues you have encountered<\/td><\/tr><\/tbody><\/table><\/figure><p class=\"wp-block-paragraph\">For project discussions, prepare specific examples using a simple sequence: describe the problem, explain your technical approach, identify the relevant Java features and discuss the result. Mention outcomes only when they are accurate and supported by your experience.<\/p><p class=\"wp-block-paragraph\">The questions in this guide are a revision resource rather than a prediction of a particular employer&rsquo;s interview. Backend development positions may also involve SQL, REST APIs, Spring, testing and deployment practices, depending on the vacancy.<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Preparing for Java interview questions for 2 to 3 years of experience requires more than recalling definitions. At this stage, interviewers may ask you to explain why a particular collection, design approach or concurrency mechanism was used, identify limitations and describe how you handled technical problems in your projects.This guide covers 50 Java interview questions &hellip; <a href=\"https:\/\/www.foundit.in\/career-advice\/java-interview-questions-and-answers-for-2-to-3-years-experience\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Java Interview Questions and Answers for 2 to 3 years Experienced: Top 50<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":7,"featured_media":9880,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[147],"tags":[],"class_list":["post-9456","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-interview-questions"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/posts\/9456","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/comments?post=9456"}],"version-history":[{"count":34,"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/posts\/9456\/revisions"}],"predecessor-version":[{"id":55750,"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/posts\/9456\/revisions\/55750"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/media\/9880"}],"wp:attachment":[{"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/media?parent=9456"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/categories?post=9456"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.foundit.in\/career-advice\/wp-json\/wp\/v2\/tags?post=9456"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}