<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anuj Singh on Medium]]></title>
        <description><![CDATA[Stories by Anuj Singh on Medium]]></description>
        <link>https://medium.com/@anujsinghpp123?source=rss-2346d54147f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tO9OjMJlhD696jeemXxjJA.png</url>
            <title>Stories by Anuj Singh on Medium</title>
            <link>https://medium.com/@anujsinghpp123?source=rss-2346d54147f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 03:16:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anujsinghpp123/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Java 25 Explained: New Features, Code Examples, and Why Developers Should Care]]></title>
            <link>https://medium.com/@anujsinghpp123/java-25-explained-new-features-code-examples-and-why-developers-should-care-798c2188c0f8?source=rss-2346d54147f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/798c2188c0f8</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java25]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Anuj Singh]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 16:56:14 GMT</pubDate>
            <atom:updated>2026-10-24T18:01:31.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jap_cRszSOiPk-lu65mFLw.png" /></figure><p>Java continues to evolve while maintaining its position as a major platform for enterprise applications, backend development, and cloud-native systems. With the release of <strong>Java 25 on September 16, 2025</strong>, developers get new language features, runtime improvements, and better tools for monitoring and performance optimization.</p><p>Java 25 is a <strong>Long-Term Support (LTS)</strong> release, making it an important version for developers and organizations planning their next Java upgrade.</p><p>In this article, we’ll explore the most useful Java 25 features, understand how they work with examples, and discuss why they matter in real-world development.</p><h3>1. Java 25 at a Glance</h3><p>Java 25 introduces several improvements across the language, JVM, security, and developer tooling.</p><p>Some important features include:</p><ul><li>Compact Source Files and Instance Main Methods</li><li>Module Import Declarations</li><li>Flexible Constructor Bodies</li><li>Compact Object Headers</li><li>Ahead-of-Time (AOT) improvements</li><li>Enhanced Java Flight Recorder (JFR) capabilities</li><li>Scoped Values</li><li>Primitive Types in Patterns instanceof, and switch (preview)</li></ul><p>Not every feature is entirely new in Java 25. Some were introduced in earlier releases as preview features and have now reached a stable stage, while others remain in preview or experimental status.</p><p>Let’s examine the important ones.</p><h3>2. Compact Source Files and Instance Main Methods</h3><p>One of the most beginner-friendly changes in Java 25 is the ability to write small programs without declaring a class or using the traditional public static void main(String[] args) method.</p><h4>Traditional Java approach</h4><p>In earlier Java versions, a simple program looked like this:</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello, Java!&quot;);<br>    }<br>}</pre><p>For experienced developers, this structure is familiar. However, beginners must learn about classes, static methods, and command-line arguments before writing their first program.</p><h4>Java 25 approach</h4><p>With Java 25, you can write:</p><pre>void main() {<br>    IO.println(&quot;Hello, Java 25!&quot;);<br>}</pre><p>That’s it. No explicit class declaration and no static keyword are required.</p><p>The IO class provides convenient methods for basic console input and output.</p><p>For example:</p><pre>void main() {<br>    String name = IO.readln(&quot;Enter your name: &quot;);<br>    IO.println(&quot;Welcome, &quot; + name + &quot;!&quot;);<br>}</pre><h4>Why is this useful?</h4><ul><li>Beginners can focus on programming logic first.</li><li>Small programs and learning exercises require less boilerplate.</li><li>Developers can create quick demonstrations more easily.</li></ul><p><strong>Important:</strong> This feature does not eliminate classes from Java. Traditional class-based applications remain fully supported. These compact source files are especially useful for small programs and learning, rather than replacing the structure of large applications.</p><h3>3. Module Import Declarations</h3><p>Java 25 introduces module import declarations, which allow a source file to import all the packages exported by a module without listing each package individually.</p><p>Previously, developers often wrote multiple import statements:</p><pre>import java.util.List;<br>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.Map;</pre><p>Java 25 allows a more concise approach:</p><pre>import module java.base;</pre><pre>void main() {<br>    List&lt;String&gt; names = new ArrayList&lt;&gt;();</pre><pre>    names.add(&quot;Anuj&quot;);<br>    names.add(&quot;Rahul&quot;);</pre><pre>    IO.println(names);<br>}</pre><p>The java.base module exports commonly used packages, including java.util and java.lang.</p><h4>Why does it matter?</h4><p>Module import declarations can reduce repetitive imports, particularly in examples, educational code, and small programs.</p><p>However, they do not replace ordinary imports. Explicit imports can still be preferable when you want to make dependencies clear.</p><p>Also, module import declarations are not the same as importing every class from every Java module. They import the packages exported by the specified module.</p><h3>4. Flexible Constructor Bodies</h3><p>Java 25 finalizes flexible constructor bodies, making it easier to perform certain operations before invoking a superclass constructor.</p><p>Previously, Java required an explicit super() or this() constructor invocation to appear first in a constructor body, apart from certain compiler-generated behavior.</p><p>Java 25 relaxes this restriction while preserving important initialization safety rules.</p><p>Consider this example:</p><pre>class Employee {<br>    Employee(int id) {<br>        System.out.println(&quot;Employee ID: &quot; + id);<br>    }<br>}</pre><pre>class Developer extends Employee {<br>    Developer(int id) {<br>        if (id &lt;= 0) {<br>            throw new IllegalArgumentException(<br>                &quot;Employee ID must be positive&quot;<br>            );<br>        }<br>        super(id);<br>    }<br>}</pre><p>In Java 25, the validation can appear before the explicit superclass constructor invocation.</p><h4>Why is this useful?</h4><ul><li>Constructor arguments can be validated before superclass initialization.</li><li>Invalid input can be rejected earlier.</li><li>Constructor logic can become more natural and readable.</li></ul><p>There are still restrictions on what can be done before the superclass constructor runs. This feature does not permit unrestricted access to the incompletely initialized object.</p><h3>5. Compact Object Headers</h3><p>Compact Object Headers are a JVM improvement designed to reduce the memory overhead associated with Java objects.</p><p>Every Java object requires metadata in addition to its actual fields. When an application creates a large number of objects, this overhead can become significant.</p><p>Java 25 introduces support for compact object headers, which can reduce object-header size to 64 bits on supported 64-bit architectures.</p><h4>Why does this matter?</h4><p>Consider a backend service that processes millions of records. Its workload may involve large numbers of temporary objects, collections, DTOs, and entities.</p><p>Reducing per-object overhead can potentially provide benefits such as:</p><ul><li>Lower memory consumption</li><li>Better cache utilization</li><li>Higher application density within a given memory budget</li></ul><p>However, the actual improvement depends on the application’s workload, JVM configuration, and object allocation patterns.</p><p>Compact Object Headers are not a universal performance guarantee. Before enabling a new configuration in production, benchmark the application and verify its compatibility with the target environment.</p><h3>6. Ahead-of-Time Improvements</h3><p>Java 25 continues improving Ahead-of-Time (AOT) capabilities through two important enhancements.</p><h4>AOT Command-Line Ergonomics</h4><p>AOT cache creation is made easier through simplified command-line workflows.</p><h4>AOT Method Profiling</h4><p>Java can use profiling information collected during training runs to improve the warmup behavior of subsequent application runs.</p><p>Traditionally, a JVM application may need time to gather execution profiles and optimize frequently executed code. This warmup period can be particularly relevant for applications that start and stop frequently.</p><h4>Where can these improvements help?</h4><ul><li>Microservices with frequent restarts</li><li>Serverless workloads</li><li>Command-line applications</li><li>Applications with strict startup requirements</li></ul><p>These features do not turn every Java application into a native executable. They improve specific aspects of JVM startup and optimization. Actual gains depend on how the application is built, configured, and executed.</p><h3>7. Better Monitoring with Java Flight Recorder</h3><p>Java Flight Recorder (JFR) is a built-in JVM monitoring and diagnostic technology.</p><p>Java 25 improves its capabilities with enhancements such as method timing and tracing, cooperative sampling, and experimental CPU-time profiling improvements on Linux.</p><p>For backend developers, diagnosing performance issues is often more difficult than writing the original code.</p><p>Imagine that a Spring Boot service suddenly becomes slow in production. The problem could be caused by:</p><ul><li>Expensive database queries</li><li>Excessive CPU usage</li><li>Frequent garbage collection</li><li>Slow method execution</li><li>Thread contention</li></ul><p>JFR improvements can help developers investigate method execution and application behavior more effectively.</p><p>For example, a developer can record a flight recording and inspect it using Java Mission Control.</p><h4>Why is this important?</h4><p>Better diagnostics can help developers identify bottlenecks before attempting optimization.</p><p>Instead of assuming that a particular method is slow, developers can gather profiling evidence and focus on the actual source of the problem.</p><p>For production systems, monitoring improvements can be just as valuable as language improvements.</p><h3>8. Scoped Values</h3><p>Scoped Values became a permanent feature in Java 25 after being previewed in earlier releases.</p><p>They provide a way to share immutable data across a bounded execution scope without passing the same value through every method parameter.</p><p>Consider a backend request that needs a request ID for logging:</p><pre>final class RequestContext {<br>    static final ScopedValue&lt;String&gt; REQUEST_ID =<br>        ScopedValue.newInstance();<br>}</pre><p>A request can bind a value for a particular scope:</p><pre>ScopedValue.where(RequestContext.REQUEST_ID, &quot;REQ-101&quot;)<br>    .run(() -&gt; processRequest());</pre><p>Methods called within that scope can access the value:</p><pre>static void processRequest() {<br>    String requestId = RequestContext.REQUEST_ID.get();</pre><pre>    IO.println(&quot;Processing request: &quot; + requestId);<br>}</pre><p>This example illustrates the basic concept. Real applications must ensure that the value is accessed only within its bound scope.</p><h4>Why use Scoped Values?</h4><p>They can be useful for sharing immutable contextual information such as:</p><ul><li>Request IDs</li><li>User or tenant context</li><li>Tracing information</li><li>Logging metadata</li></ul><p>Scoped Values are particularly relevant to modern concurrent Java applications. They are not a general replacement for all uses of ThreadLocal, and they should not be used as mutable global state.</p><h3>9. Primitive Types in Patterns, instanceof, and switch</h3><p>Java 25 also introduces a third preview of primitive types in patterns, instanceof, and switch.</p><p>This feature extends pattern matching so that primitive types can be used in additional pattern contexts.</p><p>For example, a preview-feature example can use a primitive value in a switch:</p><pre>static String classify(int value) {<br>    return switch (value) {<br>        case 0 -&gt; &quot;Zero&quot;;<br>        case int n when n &gt; 0 -&gt; &quot;Positive&quot;;<br>        case int n -&gt; &quot;Negative&quot;;<br>    };<br>}</pre><p>The example uses a guarded pattern with when to check whether a value is positive.</p><p>To try preview language features, you need to enable preview features when compiling and running the code. This is not required for ordinary Java 25 programs that use only permanent features.</p><h4>Why is this useful?</h4><ul><li>Pattern matching becomes more consistent across reference and primitive types.</li><li>Conditional logic can become more expressive.</li><li>Developers can write clearer code for supported pattern-matching use cases.</li></ul><p>Since this feature is still in preview in Java 25, it should not be treated as a finalized language feature for production code without considering the preview-feature implications.</p><h3>Conclusion</h3><p>Java 25 is more than a collection of new syntax features. It combines a more approachable programming experience with JVM improvements, better diagnostics, and modern concurrency-related capabilities.</p><p>The most immediately visible changes include compact source files, instance main methods, module import declarations, and flexible constructor bodies. Meanwhile, Compact Object Headers, AOT improvements, and enhanced Java Flight Recorder capabilities are particularly interesting for developers working on performance-sensitive systems.</p><p>If you are a Java backend developer, start by experimenting with the stable language features and learning how the runtime improvements affect your applications. Treat preview features separately, and measure performance before making claims about production benefits.</p><p><strong>Java keeps evolving, and understanding these changes helps you make better technical decisions — not just write newer code.</strong></p><h3>Official References</h3><ul><li><a href="https://www.oracle.com/java/technologies/javase/25-relnote-issues.html">Java 25 Release Notes — Oracle</a></li><li><a href="https://blogs.oracle.com/java/the-arrival-of-java-25">The Arrival of Java 25 — Oracle Java Blog</a></li><li><a href="https://docs.oracle.com/en/java/javase/25/migrate/index.html">Java 25 Migration Guide</a></li></ul><p><strong>Enjoyed this Java article? </strong>Follow me for more practical Java, Spring Boot, and backend development insights that make complex concepts easier to understand. Let’s learn, build, and grow together!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=798c2188c0f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Memory Management: Stack, Heap, and Garbage Collection]]></title>
            <link>https://medium.com/@anujsinghpp123/java-memory-management-stack-heap-and-garbage-collection-8ebeb111b062?source=rss-2346d54147f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ebeb111b062</guid>
            <category><![CDATA[heap-memory]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[heap-and-stack-memory]]></category>
            <dc:creator><![CDATA[Anuj Singh]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 18:12:05 GMT</pubDate>
            <atom:updated>2026-10-24T18:02:59.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jap_cRszSOiPk-lu65mFLw.png" /></figure><p>Whenever we run a Java application, the JVM needs memory to store variables, objects, method calls, and other information.</p><p>To understand how Java manages this memory, we mainly need to understand three things:</p><ul><li><strong>Stack</strong></li><li><strong>Heap</strong></li><li><strong>Garbage Collection</strong></li></ul><p>Let’s understand them step by step.</p><h3>Stack Memory</h3><p>Let’s start with the Stack.</p><p>Whenever we call a method, Java creates a <strong>stack frame</strong> for that method. This frame contains information needed while the method is executing.</p><p>For example:</p><pre>public static void main(String[] args) {<br>    int age = 25;<br>}</pre><p>Here, age is a local variable associated with the main() method&#39;s stack frame.</p><p>Each thread has its <strong>own Stack</strong>, so Stack memory is not shared between threads.</p><p>One important property of Stack is that it follows <strong>LIFO — Last In, First Out</strong>.</p><p>For example:</p><pre>main()<br>   ↓<br>method1()<br>   ↓<br>method2()</pre><p>method2() finishes first, then method1(), and finally main().</p><p>When a method finishes, its stack frame is removed automatically.</p><p>If the Stack runs out of memory, Java throws:</p><pre>StackOverflowError</pre><p>A common example is infinite recursion:</p><pre>void test() {<br>    test();<br>}</pre><p>Every call creates another stack frame until the Stack is exhausted.</p><h3>Heap Memory</h3><p>Now let’s talk about the Heap.</p><p>The Heap is where <strong>objects are stored</strong>.</p><p>Consider:</p><pre>Person person = new Person();</pre><p>There are actually two things involved here:</p><pre>Stack                  Heap<br>person  -------------&gt; Person Object</pre><p>The person variable is a reference associated with the stack frame, while the actual Person object is created in the Heap.</p><p>Unlike Stack memory, the Heap is <strong>shared between threads</strong>.</p><p>This is also where Garbage Collection becomes important.</p><h3>What Happens When an Object Is No Longer Needed?</h3><p>Let’s take this example:</p><pre>void createPerson() {<br>    Person person = new Person();<br>}</pre><p>While the method is running:</p><pre>Stack                  Heap<br>person  -------------&gt; Person Object</pre><p>Now the method finishes.</p><p>The stack frame is removed, so the person reference disappears.</p><p>But what about the Person object?</p><p>The object is still present in the Heap, but if there is no other reference pointing to it, it is no longer reachable.</p><pre>Stack                  Heap<br>Person Object           ↑<br>                     No reference</pre><p>This object is now <strong>eligible for Garbage Collection</strong>.</p><p>Notice the wording: <strong>eligible for GC</strong>, not “immediately deleted.”</p><p>The JVM decides when garbage collection actually happens.</p><h3>Garbage Collection</h3><p>Java provides automatic memory management through the <strong>Garbage Collector (GC)</strong>.</p><p>Its job is to identify objects that are no longer reachable and reclaim their memory.</p><p>So instead of manually doing something like:</p><pre>allocate memory<br>...<br>free memory</pre><p>as we might in languages with manual memory management, Java handles object memory reclamation automatically.</p><p>You can request garbage collection using:</p><pre>System.gc();</pre><p>But this is only a request.</p><p>It does <strong>not guarantee</strong> that the JVM will immediately run GC.</p><p>That’s an important interview question.</p><blockquote><strong><em>Does </em></strong><strong><em>System.gc() guarantee Garbage Collection?</em></strong></blockquote><p><strong>No.</strong> It only requests the JVM to perform GC.</p><h3>Strong, Weak and Soft References</h3><p>Now let’s understand something important: not all references behave in exactly the same way.</p><p>There are three reference types we should know:</p><ul><li>Strong Reference</li><li>Weak Reference</li><li>Soft Reference</li></ul><h4>Strong Reference</h4><p>This is the normal type of reference we use every day.</p><pre>Person person = new Person();</pre><p>As long as the object is strongly reachable through this reference, Garbage Collection won’t remove it merely because it is otherwise unused.</p><p>Think of it like:</p><pre>person ───────→ Person Object<br>   Strong Reference</pre><h4>Weak Reference</h4><p>A weak reference doesn’t keep an object strongly reachable.</p><p>For example:</p><pre>WeakReference&lt;Person&gt; person =<br>        new WeakReference&lt;&gt;(new Person());</pre><p>If there is no strong reference to that Person object, the object can be collected when GC runs.</p><p>After the object has been collected, the weak reference can return null.</p><p>So the basic idea is:</p><pre>Strong Reference<br>    ↓<br>Object is strongly reachable<br><br>Weak Reference<br>    ↓<br>Object can be collected when GC runs</pre><h4>Soft Reference</h4><p>A soft reference is useful when we want an object to remain available while memory is sufficient.</p><p>When the JVM is under memory pressure, the object may be collected.</p><p>So, at a high level:</p><pre>Strong → Normally kept alive<br>Weak   → Can be collected when GC runs<br>Soft   → Can be collected when memory is needed</pre><h3>How Is the Heap Organized?</h3><p>Now we know that objects live in the Heap.</p><p>But the Heap isn’t treated as one simple block.</p><p>We can think of it as:</p><pre>Heap<br>│<br>├── Young Generation<br>│<br>└── Old Generation</pre><p>The Young Generation is further divided into:</p><pre>Young Generation<br>│<br>├── Eden<br>├── Survivor 0<br>└── Survivor 1</pre><p>The Survivor spaces are usually referred to as S0 and S1.</p><h4>Where Does a New Object Go?</h4><p>Suppose we create:</p><pre>Person person = new Person();</pre><p>The newly created object initially goes into the <strong>Eden</strong> space.</p><p>Conceptually:</p><pre>Young Generation<br><br>Eden<br>----------------<br>Person Object<br>----------------<br>S0<br>S1</pre><p>Now imagine that Garbage Collection happens.</p><p>Some objects may no longer be reachable, while others are still being used.</p><p>The unreachable objects can be removed, while surviving objects can be moved to a Survivor Space.</p><h4>Minor GC and Survivor Spaces</h4><p>Let’s say we have:</p><pre>Eden<br>Object A → still reachable<br>Object B → unreachable<br>Object C → still reachable</pre><p>After a GC:</p><pre>Eden          Survivor Space<br>              Object A<br>              Object C</pre><p>The unreachable objects are removed, while the surviving objects move to a Survivor Space.</p><p>The surviving objects also get an <strong>age</strong>.</p><p>If they continue surviving multiple GC cycles, their age increases.</p><p>The objects can move between the two Survivor Spaces:</p><pre>Eden<br> ↓<br>S0<br> ↓<br>S1<br> ↓<br>S0<br> ↓<br>...</pre><p>This type of garbage collection in the Young Generation is commonly called <strong>Minor GC</strong>.</p><h4>Object Promotion</h4><p>Now comes an important concept: <strong>Promotion</strong>.</p><p>What happens when an object survives many Young Generation GC cycles?</p><p>Eventually, it can be moved to the <strong>Old Generation</strong>.</p><p>For example:</p><pre>Eden<br>  ↓<br>Survivor Space<br>  ↓<br>Survivor Space<br>  ↓<br>Old Generation</pre><p>This movement of a long-lived object from the Young Generation to the Old Generation is called <strong>promotion</strong>.</p><p>So you can remember the lifecycle like this:</p><pre>New Object<br>    ↓<br>  Eden<br>    ↓<br>Survivor Space<br>    ↓<br>Survivor Space<br>    ↓<br>Old Generation</pre><p>The exact promotion behavior depends on the garbage collector and JVM configuration, but the above model is important for understanding the basic concept.</p><h4>Major GC</h4><p>Once objects are in the Old Generation, garbage collection there is generally referred to as <strong>Major GC</strong> in this model.</p><p>The important difference to remember for interviews is:</p><pre>Young Generation → Minor GC<br><br>Old Generation   → Major GC</pre><p>Old Generation objects are generally longer-lived, so the collection strategy and frequency can differ from the Young Generation.</p><h3>What Is Metaspace?</h3><p>There is one more memory area we need to know about: <strong>Metaspace</strong>.</p><p>Metaspace is <strong>not part of the Heap</strong>.</p><p>It contains class-related information such as class metadata.</p><p>A simplified view is:</p><pre>JVM Memory<br><br>Heap<br>├── Young Generation<br>│   ├── Eden<br>│   ├── S0<br>│   └── S1<br>│<br>└── Old Generation<br>Non-Heap<br>└── Metaspace</pre><p>Before Java 8, Java used <strong>PermGen</strong> for this purpose.</p><p>From Java 8, Metaspace replaced PermGen.</p><p>For an interview, remember:</p><p><em>Heap → Objects</em></p><p><em>Metaspace → Class-related metadata</em></p><h3>How Does Garbage Collection Find Objects to Remove?</h3><p>One basic garbage collection technique is <strong>Mark and Sweep</strong>.</p><p>The idea is simple.</p><h4>Step 1: Mark</h4><p>The GC identifies objects that are no longer reachable.</p><pre>Object A → reachable<br>Object B → unreachable<br>Object C → reachable</pre><h4>Step 2: Sweep</h4><p>The unreachable objects are removed.</p><pre>Before: [A] [B] [C]<br>After: [A]     [C]</pre><p>The memory occupied by the removed objects can then be reused.</p><h4>Mark and Sweep with Compaction</h4><p>There is another problem.</p><p>Suppose memory looks like this:</p><pre>[A] [Free] [B] [Free] [C]</pre><p>There is free memory, but it is fragmented.</p><p>With <strong>compaction</strong>, surviving objects can be moved together:</p><pre>[A] [B] [C] [Free] [Free]</pre><p>Now we have one larger contiguous free area.</p><p>So:</p><pre>Mark<br> ↓<br>Identify unreachable objects<br> ↓<br>Sweep<br> ↓<br>Remove them<br> ↓<br>Compact<br> ↓<br>Move surviving objects together</pre><h3>Garbage Collectors</h3><p>There are different Garbage Collectors, and each uses different strategies.</p><p>The important ones to know for interviews are:</p><h4>Serial GC</h4><p>Uses a single GC thread.</p><p>It’s simple, but GC work can take longer because only one thread is performing the collection work.</p><h4>Parallel GC</h4><p>Uses multiple threads for GC work.</p><p>The goal is to complete garbage collection faster and reduce the time application threads remain paused.</p><pre>GC Thread 1 ─┐<br>GC Thread 2 ─┤<br>GC Thread 3 ─┤──→ GC<br>GC Thread 4 ─┘</pre><h4>CMS</h4><p>CMS stands for <strong>Concurrent Mark Sweep</strong>.</p><p>Its goal is to perform much of the GC work concurrently with application threads to reduce pause times.</p><p>One important characteristic is that CMS does not perform compaction.</p><h4>G1 GC</h4><p>G1 stands for <strong>Garbage-First Garbage Collector</strong>.</p><p>It is designed to provide more predictable pause behavior while also supporting compaction.</p><p>For interview purposes, remember:</p><pre>Serial → Single GC thread</pre><pre>Parallel → Multiple GC threads</pre><pre>CMS → Concurrent collection, no compaction</pre><pre>G1 → Concurrent approach + compaction</pre><h3>Final Picture</h3><p>Let’s put everything together:</p><pre>                       JVM<br>                        │<br>             ┌──────────┴──────────┐<br>             │                     │<br>          Stack                   Heap<br>             │                     │<br>      Method Frames        Young Generation<br>      Local Variables             │<br>      References            ┌──────┴──────┐<br>                            │             │<br>                          Eden       Survivor S0/S1<br>                                          │<br>                                          ↓<br>                                   Old Generation<br>                                          │<br>                                          ↓<br>                                         GC<br><br>                   Non-Heap<br>                       │<br>                   Metaspace<br>                       │<br>              Class Metadata</pre><p>If you understand this flow, you can answer most basic Java Memory Management interview questions:</p><ul><li>What is Stack memory?</li><li>What is Heap memory?</li><li>Stack vs Heap?</li><li>Where are objects stored?</li><li>What happens when an object becomes unreachable?</li><li>What is Garbage Collection?</li><li>Does System.gc() guarantee GC?</li><li>Strong vs Weak vs Soft references?</li><li>What is Eden?</li><li>What are Survivor Spaces?</li><li>What is Minor GC?</li><li>What is Major GC?</li><li>What is object promotion?</li><li>What is Metaspace?</li><li>What is Mark and Sweep?</li><li>What is compaction?</li><li>Serial vs Parallel vs CMS vs G1?</li></ul><p>💡 <strong>Preparing for Java interviews? </strong>Follow me for more interview questions and answers on Java, Spring Boot, Microservices, SQL, and backend development — explained in a simple, practical, and interview-focused way. 🚀 Let’s crack interviews and grow together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ebeb111b062" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Reflection in Java: Understanding Runtime Inspection]]></title>
            <link>https://medium.com/@anujsinghpp123/java-reflection-in-java-understanding-runtime-inspection-b4d4311cd3fc?source=rss-2346d54147f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4d4311cd3fc</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[java-reflection-api]]></category>
            <dc:creator><![CDATA[Anuj Singh]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 20:29:50 GMT</pubDate>
            <atom:updated>2026-10-24T18:06:39.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jap_cRszSOiPk-lu65mFLw.png" /></figure><p>When we write normal Java code, we usually know the class, fields, and methods at compile time.</p><p>For example:</p><pre>Calculator calculator = new Calculator();</pre><pre>calculator.add(10, 20);</pre><p>Here, we already know that:</p><ul><li>Calculator is the class.</li><li>add() is the method.</li><li>10 and 20 are the arguments.</li></ul><p>But what if we don’t know the class or method until <strong>runtime</strong>?</p><p>This is where <strong>Reflection</strong> comes into the picture.</p><p>Reflection allows Java to <strong>inspect and interact with classes, methods, fields, and constructors at runtime</strong>.</p><h3>What is Reflection?</h3><p>Reflection is a Java mechanism that allows us to examine the structure of a class at runtime.</p><p>Using Reflection, we can find things like:</p><ul><li>Class name</li><li>Methods</li><li>Fields</li><li>Constructors</li><li>Superclass</li><li>Interfaces</li><li>Modifiers</li></ul><p>We can also dynamically:</p><ul><li>Invoke methods</li><li>Read fields</li><li>Modify fields</li><li>Create objects using constructors</li></ul><p>The most important class to understand first is:</p><pre>Class</pre><h3>What is the Class Object?</h3><p>Every class loaded by the JVM has a corresponding Class object.</p><p>Think of the Class object as <strong>metadata about a class</strong>.</p><p>For example, suppose we have:</p><pre>class Calculator {<br>private String name = &quot;Calculator&quot;;<br>    public int add(int a, int b) {<br>        return a + b;<br>    }<br>}</pre><p>The JVM maintains a Class object representing Calculator.</p><p>We can use this object to inspect the class.</p><h3>How Do We Get a Class Object?</h3><p>There are three common ways.</p><h4>1. Using .class</h4><pre>Class&lt;?&gt; clazz = Calculator.class;</pre><p>This is the simplest approach when we already know the class at compile time.</p><h4>2. Using getClass()</h4><pre>Calculator calculator = new Calculator();<br>Class&lt;?&gt; clazz = calculator.getClass();</pre><p>Here, we already have an object and want to find its runtime class.</p><h4>3. Using Class.forName()</h4><pre>Class&lt;?&gt; clazz = Class.forName(&quot;Calculator&quot;);</pre><p>Here, the class name is provided as a String.</p><p>This is useful when the class needs to be loaded dynamically.</p><h3>Important Reflection Classes</h3><p>Most of the Reflection API that we need for interviews comes from:</p><pre>java.lang.reflect</pre><p>The important classes are:</p><pre>Class<br> ├── Method<br> ├── Field<br> └── Constructor</pre><p>Their purpose is simple:</p><ul><li>Class → represents a class and provides its metadata</li><li>Method → represents a method</li><li>Field → represents a field</li><li>Constructor → represents a constructor</li></ul><h4>Inspecting Methods</h4><p>Once we have the Class object, we can inspect its methods.</p><p>For example:</p><pre>Method[] methods = clazz.getDeclaredMethods();</pre><p>Then:</p><pre>for (Method method : methods) {<br>    System.out.println(method.getName());<br>}</pre><p>This allows us to discover methods without directly knowing them beforehand.</p><h4>getMethods() vs getDeclaredMethods()</h4><p>This is a common interview question.</p><h4>getMethods()</h4><pre>clazz.getMethods();</pre><p>Returns <strong>public methods</strong>, including inherited public methods.</p><h4>getDeclaredMethods()</h4><pre>clazz.getDeclaredMethods();</pre><p>Returns methods <strong>declared directly inside the class</strong>, regardless of their access modifier.</p><p>For example, it can return:</p><pre>public<br>protected<br>private<br>package-private</pre><p>methods declared in that class.</p><p>The same general distinction exists for fields and constructors:</p><pre>getFields()<br>getDeclaredFields()<br>getConstructors()<br>getDeclaredConstructors()</pre><p>A useful way to remember it is:</p><p><em>Declared means declared directly in that class.</em></p><h3>Invoking a Method Using Reflection</h3><p>Reflection is not limited to inspecting methods. We can also invoke them dynamically.</p><p>Suppose we have:</p><pre>public int add(int a, int b) {<br>    return a + b;<br>}</pre><p>Normally:</p><pre>calculator.add(10, 20);</pre><p>Using Reflection:</p><pre>Method method =<br>        Calculator.class.getMethod(<br>                &quot;add&quot;,<br>                int.class,<br>                int.class<br>        );<br>Object result =<br>        method.invoke(calculator, 10, 20);</pre><p>Here:</p><pre>getMethod()</pre><p>finds the method.</p><p>And:</p><pre>invoke()</pre><p>actually executes it.</p><p>So the flow is:</p><pre>Class<br>  ↓<br>Find Method<br>  ↓<br>Method.invoke()<br>  ↓<br>Execute method</pre><h3>Accessing Fields Using Reflection</h3><p>Reflection can also inspect fields.</p><p>Suppose:</p><pre>class Calculator {<br>private String name = &quot;Calculator&quot;;<br>}</pre><p>We can find the field using:</p><pre>Field field =<br>        Calculator.class.getDeclaredField(&quot;name&quot;);</pre><p>We can then read its value:</p><pre>field.get(calculator);</pre><p>We can also modify it:</p><pre>field.set(calculator, &quot;Scientific Calculator&quot;);</pre><p>So the two important operations are:</p><pre>field.get(object);<br>field.set(object, value);</pre><h3>What About Private Members?</h3><p>Normally, Java access modifiers prevent us from directly accessing private members.</p><p>For example:</p><pre>private String name;</pre><p>Reflection can still locate the field:</p><pre>Field field =<br>        clazz.getDeclaredField(&quot;name&quot;);</pre><p>To request access beyond the normal access checks, Reflection provides:</p><pre>field.setAccessible(true);</pre><p>After that, we can use:</p><pre>field.get(object);</pre><p>Similarly, a private method can be obtained with:</p><pre>getDeclaredMethod()</pre><p>and, where permitted, accessed using:</p><pre>method.setAccessible(true);</pre><p>This is an important interview concept because it demonstrates that Reflection can work with members that are not normally accessible from the calling code.</p><h3>Complete Runnable Example</h3><p>Now let’s put the important concepts together into one program.</p><p>Create a file:</p><pre>ReflectionDemo.java</pre><p>and add:</p><pre>import java.lang.reflect.Field;<br>import java.lang.reflect.Method;<br><br>class Calculator {<br>    private String name = &quot;Calculator&quot;;<br>    public int add(int a, int b) {<br>        return a + b;<br>    }<br>    private void message() {<br>        System.out.println(&quot;Private method called&quot;);<br>    }<br>}<br>public class ReflectionDemo {<br>    public static void main(String[] args) throws Exception {<br>        // 1. Get the Class object<br>        Class&lt;?&gt; clazz = Calculator.class;<br>        System.out.println(&quot;Class name: &quot; + clazz.getName());<br>        // 2. Get declared fields<br>        System.out.println(&quot;\nFields:&quot;);<br>        Field[] fields = clazz.getDeclaredFields();<br>        for (Field field : fields) {<br>            System.out.println(field.getName());<br>        }<br>        // 3. Get declared methods<br>        System.out.println(&quot;\nMethods:&quot;);<br>        Method[] methods = clazz.getDeclaredMethods();<br>        for (Method method : methods) {<br>            System.out.println(method.getName());<br>        }<br>        // 4. Create an object<br>        Calculator calculator = new Calculator();<br>        // 5. Find the add() method<br>        Method addMethod =<br>                clazz.getMethod(<br>                        &quot;add&quot;,<br>                        int.class,<br>                        int.class<br>                );<br>        // 6. Invoke add() dynamically<br>        Object result =<br>                addMethod.invoke(calculator, 10, 20);<br>        System.out.println(&quot;\nResult: &quot; + result);<br>        // 7. Find the private field<br>        Field nameField =<br>                clazz.getDeclaredField(&quot;name&quot;);<br>        // 8. Allow reflective access<br>        nameField.setAccessible(true);<br>        // 9. Read the private field<br>        System.out.println(<br>                &quot;Private field value: &quot;<br>                        + nameField.get(calculator)<br>        );<br>        // 10. Find the private method<br>        Method messageMethod =<br>                clazz.getDeclaredMethod(&quot;message&quot;);<br>        // 11. Allow reflective access<br>        messageMethod.setAccessible(true);<br>        // 12. Invoke the private method<br>        messageMethod.invoke(calculator);<br>    }<br>}</pre><h4>Output</h4><pre>Class name: Calculator<br>Fields:<br>name<br>Methods:<br>add<br>message<br>Result: 30<br>Private field value: Calculator<br>Private method called</pre><h3>Let’s Understand the Example</h3><p>The entire example follows a simple sequence.</p><h4>Step 1: Get the class</h4><pre>Class&lt;?&gt; clazz = Calculator.class;</pre><p>Now clazz represents the Calculator class at runtime.</p><h4>Step 2: Inspect fields</h4><pre>Field[] fields = clazz.getDeclaredFields();</pre><p>This gives us the fields declared inside Calculator.</p><p>In our example:</p><pre>private String name;</pre><h4>Step 3: Inspect methods</h4><pre>Method[] methods = clazz.getDeclaredMethods();</pre><p>This gives us:</p><pre>add()<br>message()</pre><p>without directly calling either method.</p><h4>Step 4: Find a specific method</h4><pre>Method addMethod =<br>        clazz.getMethod(<br>                &quot;add&quot;,<br>                int.class,<br>                int.class<br>        );</pre><p>We are telling Java:</p><p><em>Find the public method named </em><em>add that accepts two </em><em>int parameters.</em></p><h4>Step 5: Invoke the method</h4><pre>Object result =<br>        addMethod.invoke(calculator, 10, 20);</pre><p>This dynamically executes:</p><pre>calculator.add(10, 20);</pre><p>and gives us:</p><pre>30</pre><h4>Step 6: Access a private field</h4><pre>Field nameField =<br>        clazz.getDeclaredField(&quot;name&quot;);<br>nameField.setAccessible(true);</pre><pre>// Now we can read the value:<br>nameField.get(calculator);</pre><p>which gives:</p><pre>Calculator</pre><h4>Step 7: Invoke a private method</h4><p>We find it using:</p><pre>Method messageMethod =<br>        clazz.getDeclaredMethod(&quot;message&quot;);</pre><p>Then:</p><pre>messageMethod.setAccessible(true);</pre><p>and finally:</p><pre>messageMethod.invoke(calculator);</pre><p>This executes the private method.</p><h3>Where is Reflection Used?</h3><p>Reflection becomes useful when the application or framework needs to work with classes dynamically.</p><p>Common examples include:</p><ul><li>Dependency Injection frameworks</li><li>Testing frameworks</li><li>Serialization and deserialization</li><li>Object mapping</li><li>Framework configuration</li><li>Runtime class inspection</li></ul><p>For example, a framework may not know at compile time which class it needs to instantiate or which method it needs to invoke.</p><p>Reflection allows the framework to discover and interact with that class at runtime.</p><h3>Important Interview Questions</h3><h4>What is Reflection in Java?</h4><p>Reflection is a mechanism that allows Java programs to <strong>inspect and interact with classes, methods, fields, and constructors at runtime</strong>.</p><h4>What is an Class object?</h4><p>A Class object represents a class at runtime and provides information about its methods, fields, constructors, superclass, interfaces, and other metadata.</p><h4>How can we get a Class object?</h4><p>Three common ways:</p><pre>Calculator.class</pre><pre>calculator.getClass()</pre><pre>Class.forName(&quot;Calculator&quot;)</pre><h4>What is the difference between getMethods() and getDeclaredMethods()?</h4><p>getMethods() returns public methods, including inherited public methods.</p><p>getDeclaredMethods() returns methods declared directly in the class, regardless of their access modifier.</p><h4>Can Reflection invoke a method?</h4><p>Yes.</p><pre>method.invoke(object, arguments);</pre><h4>Can Reflection access private members?</h4><p>Reflection can locate private members using methods such as:</p><pre>getDeclaredField()<br>getDeclaredMethod()</pre><p>and can request access using:</p><pre>setAccessible(true);</pre><p>where permitted by the runtime’s access rules.</p><h3>Final Takeaway</h3><p>You don’t need to memorize every Reflection API for an interview.</p><p>Understand this flow:</p><pre>Get Class object<br>      ↓<br>Inspect class metadata<br>      ↓<br>Find Field / Method / Constructor<br>      ↓<br>Access or invoke it<br>      ↓<br>Perform the operation at runtime</pre><p>The most important APIs to remember are:</p><pre>getClass()<br>Class.forName()<br>getMethods()<br>getDeclaredMethods()<br>getFields()<br>getDeclaredFields()<br>getMethod()<br>getDeclaredMethod()<br>getField()<br>getDeclaredField()<br>Method.invoke()<br>Field.get()<br>Field.set()</pre><p>The main idea is simple:</p><p><em>Reflection allows Java code to discover and interact with the structure of a class at runtime instead of relying completely on information known at compile time.</em></p><p>That is the core concept you should be able to explain and demonstrate in a Java interview.</p><p>💡 <strong>Preparing for Java interviews? </strong>Follow me for more interview questions and answers on Java, Spring Boot, Microservices, SQL, and backend development — explained in a simple, practical, and interview-focused way. 🚀 Let’s crack interviews and grow together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4d4311cd3fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Stream API: 10 Practical Problems I Practiced]]></title>
            <link>https://medium.com/@anujsinghpp123/java-stream-api-10-practical-problems-i-practiced-ee1a1110bebf?source=rss-2346d54147f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee1a1110bebf</guid>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[java-stream-api]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[filters]]></category>
            <dc:creator><![CDATA[Anuj Singh]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 19:40:28 GMT</pubDate>
            <atom:updated>2026-10-24T18:07:23.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jap_cRszSOiPk-lu65mFLw.png" /></figure><p>While learning Java Streams, I found that understanding individual methods like filter(), map(), reduce(), and collect() is not enough.</p><p>The real understanding comes when you start solving small problems using them.</p><p>In this post, I’m sharing some Stream API problems I practiced, along with the approach and code for each one.</p><blockquote><strong><em>Note:</em></strong><em> Most of these examples work with Java 8. Where I use </em><em>.toList(), remember that </em><em>Stream.toList() was introduced in Java 16 and it return </em>unmodifiable list <em>. In Java 8, use </em><em>collect(Collectors.toList()).</em></blockquote><h3>1. Find Strings Starting With “A”</h3><h4>Problem</h4><p>Given a list of names, find names starting with the character A.</p><pre>List&lt;String&gt; names =<br>        List.of(&quot;Anuj&quot;, &quot;Amit&quot;, &quot;Rahul&quot;, &quot;Ankit&quot;, &quot;Raj&quot;);<br><br>List&lt;String&gt; result =<br>        names.stream()<br>                .filter(n -&gt; n.startsWith(&quot;A&quot;))<br>                .toList();<br>System.out.println(result);</pre><h4>Output</h4><pre>[Anuj, Amit, Ankit]</pre><p>We can also write:</p><pre>.filter(n -&gt; n.charAt(0) == &#39;A&#39;)</pre><p>Both approaches work.</p><p>However, for this particular requirement:</p><pre>startsWith(&quot;A&quot;)</pre><p>is more readable because the requirement itself is “starts with A”.</p><h3>2. Remove Duplicates and Sort in Descending Order</h3><h4>Problem</h4><p>Remove duplicate numbers and sort the result in descending order.</p><pre>List&lt;Integer&gt; numbers =<br>        List.of(10, 20, 10, 30, 20, 40, 50);<br><br>List&lt;Integer&gt; result =<br>        numbers.stream()<br>                .distinct()<br>                .sorted(Comparator.reverseOrder())<br>                .toList();<br>System.out.println(result);</pre><h4>Output</h4><pre>[50, 40, 30, 20, 10]</pre><h4>Important operations</h4><p>distinct():</p><pre>.distinct()</pre><p>removes duplicate elements.</p><p>So:</p><pre>10, 20, 10, 30, 20, 40, 50</pre><p>becomes:</p><pre>10, 20, 30, 40, 50</pre><p>Then:</p><pre>.sorted(Comparator.reverseOrder())</pre><p>sorts the elements in descending order.</p><p>You might see:</p><pre>.sorted((a, b) -&gt; b - a)</pre><p>This works for many normal integer values, but subtraction-based comparators can cause integer overflow.</p><p>For example, with extreme integer values, b - a may overflow.</p><p>A safer approach is:</p><pre>.sorted(Comparator.reverseOrder())</pre><p>or:</p><pre>.sorted((a, b) -&gt; Integer.compare(b, a))</pre><h3>3. Find the Sum of Numbers Greater Than 25</h3><h4>Problem</h4><p>Find the sum of all numbers greater than 25.</p><pre>List&lt;Integer&gt; numbers =<br>        List.of(10, 20, 30, 40, 50);<br><br>int result =<br>        numbers.stream()<br>                .filter(n -&gt; n &gt; 25)<br>                .mapToInt(Integer::intValue)<br>                .sum();<br>System.out.println(result);</pre><h4>Output</h4><pre>120</pre><p>Because:</p><pre>30 + 40 + 50 = 120</pre><h4>Another approach using reduce()</h4><p>We can also write:</p><pre>Integer result =<br>        numbers.stream()<br>                .filter(n -&gt; n &gt; 25)<br>                .reduce(0, (a, b) -&gt; a + b);</pre><p>Here:</p><pre>reduce(0, (a, b) -&gt; a + b)</pre><p>starts with 0 and repeatedly combines the values.</p><p>For a simple sum, however:</p><pre>.mapToInt(Integer::intValue)<br>.sum()</pre><p>is more readable.</p><h3>4. Find the First Number Greater Than 25</h3><h4>Problem</h4><p>Find the first number greater than 25.</p><pre>List&lt;Integer&gt; numbers =<br>        List.of(10, 20, 30, 40, 50);<br><br>Optional&lt;Integer&gt; result =<br>        numbers.stream()<br>                .filter(n -&gt; n &gt; 25)<br>                .findFirst();<br>System.out.println(result.orElse(null));</pre><h4>Output</h4><pre>30</pre><h4>Why Optional?</h4><p>findFirst() returns:</p><pre>Optional&lt;Integer&gt;</pre><p>Because there might be no matching element.</p><p>For example:</p><pre>List&lt;Integer&gt; numbers =<br>        List.of(10, 20, 15);</pre><p>There is no number greater than 25.</p><p>Instead of returning null, Java uses Optional to represent the possibility that a value may not exist.</p><p>You can also directly write:</p><pre>Integer result =<br>        numbers.stream()<br>                .filter(n -&gt; n &gt; 25)<br>                .findFirst()<br>                .orElse(null);</pre><h3>5. Check Whether Any Number Is Greater Than 18</h3><h4>Problem</h4><p>Check whether at least one number is greater than 18.</p><pre>List&lt;Integer&gt; numbers =<br>        List.of(5, 8, 12, 15, 20);<br><br>boolean result =<br>        numbers.stream()<br>                .anyMatch(n -&gt; n &gt; 18);<br>System.out.println(result);</pre><h4>Output</h4><pre>true</pre><p>anyMatch() answers:</p><p><em>Does at least one element satisfy this condition?</em></p><p>In this case:</p><pre>20 &gt; 18</pre><p>So the answer is true.</p><h3>6. Check Whether All Numbers Are Positive</h3><h4>Problem</h4><p>Check whether every number in the list is greater than zero.</p><pre>List&lt;Integer&gt; numbers =<br>        List.of(10, 20, 30, 40);<br><br>boolean result =<br>        numbers.stream()<br>                .allMatch(n -&gt; n &gt; 0);<br>System.out.println(result);</pre><h4>Output</h4><pre>true</pre><p>allMatch() answers:</p><p><em>Do all elements satisfy this condition?</em></p><p>For example:</p><pre>List&lt;Integer&gt; numbers =<br>        List.of(10, 20, -5, 40);</pre><p>Then:</p><pre>.allMatch(n -&gt; n &gt; 0)</pre><p>returns:</p><pre>false</pre><p>because -5 is not greater than zero.</p><h3>7. Find the Longest String</h3><h4>Problem</h4><p>Find the longest name from a list.</p><pre>List&lt;String&gt; names =<br>        List.of(&quot;Anuj&quot;, &quot;Amit&quot;, &quot;Rahul&quot;, &quot;Ankit&quot;, &quot;Raj&quot;);<br><br>Optional&lt;String&gt; result =<br>        names.stream()<br>                .max(Comparator.comparingInt(String::length));<br>System.out.println(result.orElse(null));</pre><h4>Output</h4><pre>Rahul</pre><p>Here:</p><pre>Comparator.comparingInt(String::length)</pre><p>compares the Strings based on their length.</p><p>So:</p><pre>Anuj   → 4<br>Amit   → 4<br>Rahul  → 5<br>Ankit  → 5<br>Raj    → 3</pre><p>The maximum length is 5.</p><h3>8. Find the Second Largest Number</h3><h4>Problem</h4><p>Find the second largest distinct number.</p><pre>List&lt;Integer&gt; numbers =<br>        List.of(10, 50, 20, 50, 30, 40);<br><br>Optional&lt;Integer&gt; result =<br>        numbers.stream()<br>                .distinct()<br>                .sorted(Comparator.reverseOrder())<br>                .skip(1)<br>                .findFirst();<br>System.out.println(result.orElse(null));</pre><h4>Output</h4><pre>40</pre><p>Let’s understand the pipeline:</p><p>Original:</p><pre>10, 50, 20, 50, 30, 40</pre><p>After distinct():</p><pre>10, 50, 20, 30, 40</pre><p>After descending sort:</p><pre>50, 40, 30, 20, 10</pre><p>After:</p><pre>.skip(1)</pre><p>we skip 50:</p><pre>40, 30, 20, 10</pre><p>Then:</p><pre>.findFirst()</pre><p>returns:</p><pre>40</pre><h3>9. Find Numbers That Occur Exactly Twice</h3><p>This is a slightly more interesting problem.</p><h4>Problem</h4><p>Given:</p><pre>List&lt;Integer&gt; numbers =<br>        List.of(10, 50, 10, 50, 30, 40, 10, 30);</pre><p>Find numbers that occur exactly twice.</p><pre>List&lt;Integer&gt; result =<br>        numbers.stream()<br>                .filter(n -&gt; Collections.frequency(numbers, n) == 2)<br>                .distinct()<br>                .toList();<br><br>System.out.println(result);</pre><h4>Output</h4><pre>[50, 30]</pre><p>Frequency:</p><pre>10 → 3<br>50 → 2<br>30 → 2<br>40 → 1</pre><p>Therefore:</p><pre>50 and 30</pre><p>occur exactly twice.</p><h4>Why distinct()?</h4><p>Without:</p><pre>.distinct()</pre><p>the stream would contain:</p><pre>50, 50, 30, 30</pre><p>We only want:</p><pre>50, 30</pre><p>so we use distinct().</p><h3>10. Find Strings Occurring At Least Twice</h3><p>We can apply the same idea to Strings.</p><pre>List&lt;String&gt; names =<br>        List.of(&quot;Anuj&quot;, &quot;Rahul&quot;, &quot;Anuj&quot;, &quot;Amit&quot;, &quot;Rahul&quot;, &quot;Anuj&quot;);<br><br>List&lt;String&gt; result =<br>        names.stream()<br>                .filter(n -&gt; Collections.frequency(names, n) &gt;= 2)<br>                .distinct()<br>                .toList();<br>System.out.println(result);</pre><p>Output:</p><pre>[Anuj, Rahul]</pre><p>The frequencies are:</p><pre>Anuj  → 3<br>Rahul → 2<br>Amit  → 1</pre><p>So only Anuj and Rahul satisfy:</p><pre>frequency &gt;= 2</pre><h3>11. Better Approach: groupingBy() + counting()</h3><p>Although Collections.frequency() works, a better approach exists for frequency problems.</p><pre>List&lt;String&gt; names =<br>        List.of(&quot;Anuj&quot;, &quot;Rahul&quot;, &quot;Anuj&quot;, &quot;Amit&quot;, &quot;Rahul&quot;, &quot;Anuj&quot;);<br><br>List&lt;String&gt; result =<br>        names.stream()<br>                .collect(Collectors.groupingBy(<br>                        Function.identity(),<br>                        Collectors.counting()<br>                ))<br>                .entrySet()<br>                .stream()<br>                .filter(e -&gt; e.getValue() &gt;= 2)<br>                .map(Map.Entry::getKey)<br>                .toList();<br>System.out.println(result);</pre><p>Output:</p><pre>[Anuj, Rahul]</pre><h3>What does groupingBy() produce?</h3><p>Conceptually:</p><pre>Anuj  → 3<br>Rahul → 2<br>Amit  → 1</pre><p>So we can think of it as:</p><pre>Map&lt;String, Long&gt;</pre><p>Then:</p><pre>.filter(e -&gt; e.getValue() &gt;= 2)</pre><p>keeps:</p><pre>Anuj  → 3<br>Rahul → 2</pre><p>And:</p><pre>.map(Map.Entry::getKey)</pre><p>extracts only the names:</p><pre>Anuj<br>Rahul</pre><p>Finally:</p><pre>.toList()</pre><p>stores them in a List&lt;String&gt;.</p><h3>Important Stream Operations I Practiced</h3><p>The problems above covered several commonly used Stream operations:</p><h4>filter()</h4><p>Used when we want to <strong>select elements</strong> based on a condition.</p><pre>.filter(n -&gt; n &gt; 20)</pre><h4>map()</h4><p>Used to <strong>transform elements</strong>.</p><pre>.map(n -&gt; n * n)</pre><p>or:</p><pre>.map(String::length)</pre><h4>distinct()</h4><p>Removes duplicate elements.</p><pre>.distinct()</pre><h4>sorted()</h4><p>Sorts elements.</p><pre>.sorted()</pre><p>Descending:</p><pre>.sorted(Comparator.reverseOrder())</pre><h4>reduce()</h4><p>Combines elements into a single result.</p><pre>.reduce(0, (a, b) -&gt; a + b)</pre><h4>findFirst()</h4><p>Returns the first matching element as an Optional.</p><pre>.findFirst()</pre><h4>anyMatch()</h4><p>Checks whether <strong>at least one</strong> element matches.</p><pre>.anyMatch(n -&gt; n &gt; 18)</pre><h4>allMatch()</h4><p>Checks whether <strong>every</strong> element matches.</p><pre>.allMatch(n -&gt; n &gt; 0)</pre><h4>max()</h4><p>Finds the maximum element according to a comparator.</p><pre>.max(Comparator.comparingInt(String::length))</pre><h4>skip()</h4><p>Skips a specified number of elements.</p><pre>.skip(1)</pre><h4>collect()</h4><p>Used to collect Stream results into a collection or another result type.</p><p>For example, in Java 8:</p><pre>.collect(Collectors.toList())</pre><p>In modern Java:</p><pre>.toList()</pre><h3>Final Takeaway</h3><p>The most important thing I learned from these exercises is that Stream API is not about memorizing methods individually.</p><p>It’s about understanding how operations can be combined into a pipeline:</p><p>Once the purpose of each operation becomes clear, solving Stream-based interview questions becomes much easier.</p><p>💡 <strong>Preparing for Java interviews? </strong>Follow me for more interview questions and answers on Java, Spring Boot, Microservices, SQL, and backend development — explained in a simple, practical, and interview-focused way. 🚀 Let’s crack interviews and grow together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee1a1110bebf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Java Introduced SequencedCollection, SequencedSet, and SequencedMap]]></title>
            <link>https://medium.com/@anujsinghpp123/why-java-introduced-sequencedcollection-sequencedset-and-sequencedmap-17bbd6aa1e71?source=rss-2346d54147f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/17bbd6aa1e71</guid>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sequencedset-sequencedmap]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[sequenced-collection]]></category>
            <dc:creator><![CDATA[Anuj Singh]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 15:34:05 GMT</pubDate>
            <atom:updated>2026-10-24T18:04:49.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jap_cRszSOiPk-lu65mFLw.png" /></figure><p>Java 21 introduced three new interfaces:</p><ul><li>SequencedCollection</li><li>SequencedSet</li><li>SequencedMap</li></ul><p>At first glance, they may look like just another addition to the Collections Framework. However, they were introduced to solve a real design problem that existed for many years.</p><h3>The Problem Before Java 21</h3><p>The Java Collections Framework has grown over the years and contains many collection types:</p><pre>ArrayList<br>LinkedList<br>ArrayDeque<br>LinkedHashSet<br>TreeSet<br>LinkedHashMap<br>TreeMap<br>...</pre><p>Many of these collections maintain an order.</p><p>For example:</p><ul><li>ArrayList stores elements in insertion order.</li><li>LinkedHashSet preserves insertion order.</li><li>TreeSet stores elements in sorted order.</li><li>LinkedHashMap preserves insertion order.</li><li>TreeMap stores keys in sorted order.</li></ul><p>Because these collections maintain order, concepts like:</p><ul><li>First element</li><li>Last element</li><li>Reverse traversal</li></ul><p>The problem was that each collection exposed these operations differently, and some collections did not expose them at all.</p><p>As a developer, you had to remember implementation-specific APIs.</p><p>For example:</p><pre>LinkedList&lt;String&gt; list = new LinkedList&lt;&gt;();</pre><pre>list.getFirst();<br>list.getLast();</pre><p>But for ArrayList:</p><pre>ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();</pre><pre>list.get(0);<br>list.get(list.size() - 1);</pre><p>Different collections, same requirement, different APIs.</p><p>This made the framework inconsistent and increased the learning burden.</p><h3>What Was Missing?</h3><p>Java already had interfaces like:</p><pre>Collection<br>List<br>Set<br>Map</pre><p>But none of them represented the idea of:</p><blockquote><em>“This collection has a defined encounter order.”</em></blockquote><p>As a result, Java had many ordered collections but no common contract describing ordered behavior.</p><p>This was the gap.</p><h3>Java’s Solution</h3><p>Java introduced:</p><pre>SequencedCollection<br>SequencedSet<br>SequencedMap</pre><p>These interfaces define common operations that make sense for ordered collections.</p><p>Instead of learning different APIs for different implementations, developers can now rely on a common set of methods.</p><h3>SequencedCollection</h3><p>Before Java 21:</p><pre>LinkedList<br>ArrayList<br>ArrayDeque</pre><p>all had ordering.</p><p>But there was no common interface saying:</p><blockquote><em>“I support first, last, and reverse operations.”</em></blockquote><p>Java introduced:</p><pre>public interface SequencedCollection&lt;E&gt;</pre><p>which provides methods such as:</p><pre><br>void addFirst()<br>void addLast()<br><br>E getFirst()<br>E getLast()<br><br>E removeFirst()<br>E removeLast()<br><br>SequencedCollection&lt;E&gt;reversed()</pre><p>Now all ordered collections can expose the same behavior through a common contract.</p><h3>Hierarchy</h3><pre>Collection<br>        │<br>        ▼<br>SequencedCollection<br>        │<br> ┌──────┴──────┐<br> ▼             ▼<br>List       Deque</pre><p>Examples:</p><pre>ArrayList<br>LinkedList<br>ArrayDeque</pre><p>inherit these capabilities through SequencedCollection.</p><h3>SequencedSet</h3><p>Another problem existed with sets.</p><p>Consider:</p><pre>LinkedHashSet<br>TreeSet</pre><p>Both maintain order.</p><p>However, the common parent interface was:</p><pre>Set</pre><p>and Set does not guarantee any ordering.</p><p>There was no way to tell the compiler:</p><blockquote><em>“I need a Set that preserves encounter order.”</em></blockquote><p>So Java introduced:</p><pre>public interface SequencedSet&lt;E&gt;</pre><p>which combines:</p><pre>Set behavior<br>+<br>SequencedCollection behavior</pre><h3>Hierarchy</h3><pre>Collection<br>     │<br>     ▼<br>SequencedCollection<br>     │<br>     ▼<br>SequencedSet<br>     │<br> ┌───┴─────────┐<br> ▼             ▼<br>LinkedHashSet  TreeSet</pre><p>Now ordered sets have a dedicated abstraction.</p><h3>SequencedMap</h3><p>Maps had a similar issue.</p><p>Consider:</p><pre>LinkedHashMap<br>TreeMap</pre><p>Both maintain ordering.</p><p>Yet the common interface:</p><pre>Map</pre><p>does not provide methods like:</p><pre>firstEntry()<br>lastEntry()<br>reversed()</pre><p>Developers often had to write iterator-based logic.</p><p>Example:</p><pre>Iterator&lt;Map.Entry&lt;K,V&gt;&gt; itr =<br>        map.entrySet().iterator();</pre><p>just to get the first entry.</p><p>This was unnecessary boilerplate.</p><p>Java introduced:</p><pre>public interface SequencedMap&lt;K,V&gt;</pre><p>to standardize ordered map operations.</p><p>It provides methods like:</p><pre>Map.Entry&lt;K,V&gt; firstEntry()<br>Map.Entry&lt;K,V&gt; lastEntry()<br><br>Map.Entry&lt;K,V&gt; pollFirstEntry()<br>Map.Entry&lt;K,V&gt; pollLastEntry()<br><br>V putFirst(K k, V v)<br>V putLast(K k, V v)<br><br>SequencedMap&lt;K,V&gt; reversed()</pre><h3>Hierarchy</h3><pre>Map<br> │<br> ▼<br>SequencedMap<br> │<br> ├───────────────┐<br> ▼               ▼<br>LinkedHashMap   TreeMap</pre><h3>Biggest Benefit</h3><p>The biggest benefit is not new functionality.</p><p>Most of these collections already had ordering.</p><p>The real benefit is:</p><h3>Before Java 21</h3><pre>public void process(LinkedHashMap&lt;String,Integer&gt; map)</pre><p>or</p><pre>public void process(TreeMap&lt;String,Integer&gt; map)</pre><p>Your code depended on a specific implementation.</p><h3>After Java 21</h3><pre>public void process(<br>        SequencedMap&lt;String,Integer&gt; map)</pre><p>Now the code only cares that:</p><ul><li>the map is ordered</li><li>first/last operations are available</li><li>reverse traversal is available</li></ul><p>It does not care whether the implementation is:</p><pre>LinkedHashMap<br>TreeMap</pre><p>This follows one of the most important OOP principles:</p><blockquote><em>Program to interfaces, not implementations.</em></blockquote><h3>Final Thoughts</h3><p>SequencedCollection, SequencedSet, and SequencedMap were introduced because Java had many ordered collections but no common abstraction for ordered behavior.</p><p>The goals were:</p><ul><li>Reduce the need to remember implementation-specific APIs.</li><li>Provide common methods like getFirst(), getLast(), and reversed().</li><li>Standardize ordered collection operations.</li><li>Allow developers to program against interfaces instead of concrete classes.</li><li>Make the Collections Framework more consistent.</li></ul><p>Java 21 did not introduce new data structures. It introduced a better way to describe and use the ordered collections that already existed in the framework.</p><p>💡 <strong>Preparing for Java interviews? </strong>Follow me for more interview questions and answers on Java, Spring Boot, Microservices, SQL, and backend development — explained in a simple, practical, and interview-focused way. 🚀 Let’s crack interviews and grow together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17bbd6aa1e71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JPA / JDBC — Interview Questions & Answers]]></title>
            <link>https://medium.com/@anujsinghpp123/jpa-jdbc-interview-questions-answers-3223658d9b1b?source=rss-2346d54147f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3223658d9b1b</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[jdbc]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Anuj Singh]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 14:41:23 GMT</pubDate>
            <atom:updated>2026-09-02T14:41:23.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jap_cRszSOiPk-lu65mFLw.png" /></figure><h3>Q1. JPA vs Hibernate</h3><p><em>JPA is the standard API/specification; Hibernate is one of the most widely used implementations of that specification.</em></p><p><strong>JPA (Java Persistence API)</strong> is a <strong>specification</strong> that defines how Java applications should interact with relational databases using ORM.</p><p><strong>Hibernate</strong> is an <strong>implementation of JPA</strong>. It provides the actual functionality behind the JPA interfaces and also offers additional Hibernate-specific features.</p><p>Think of it like:</p><pre>JPA       → Specification / Rules<br>Hibernate → Implementation</pre><p>Example:</p><pre>@Entity<br>public class Employee {<br><br>    @Id<br>    private Long id;<br><br>    private String name;<br>}</pre><p>The annotations such as @Entity, @Id, and @OneToMany are part of the JPA specification.</p><p>Spring Data JPA commonly uses Hibernate as the underlying JPA provider.</p><h3>Q2. What are @GeneratedValue Strategies?</h3><p><em>IDENTITY relies on database-generated identity values, while </em><em>SEQUENCE uses a database sequence. The best strategy depends on the database and application&#39;s requirements.</em></p><p>@GeneratedValue specifies how the primary key should be generated.</p><pre>@Id<br>@GeneratedValue(strategy = GenerationType.IDENTITY)<br>private Long id;</pre><p>JPA provides four strategies:</p><h4>IDENTITY</h4><p>The database generates the ID, usually using an identity/auto-increment column.</p><pre>@GeneratedValue(strategy = GenerationType.IDENTITY)</pre><p>The generated ID is typically obtained after the insert.</p><h4>SEQUENCE</h4><p>Uses a database sequence.</p><pre>@GeneratedValue(strategy = GenerationType.SEQUENCE)</pre><p>Commonly used with databases such as PostgreSQL and Oracle.</p><h4>TABLE</h4><p>Uses a separate database table to generate IDs.</p><pre>@GeneratedValue(strategy = GenerationType.TABLE)</pre><p>It is more database-independent but generally less efficient than native sequence/identity mechanisms.</p><h4>AUTO</h4><p>Allows the JPA provider to choose an appropriate strategy based on the database/provider.</p><pre>@GeneratedValue(strategy = GenerationType.AUTO)</pre><h3>3. Explain Entity Relationships in JPA</h3><p>JPA provides four main relationship types:</p><pre>@OneToOne<br>@OneToMany<br>@ManyToOne<br>@ManyToMany</pre><h4>One-to-One</h4><p>One entity is associated with one other entity.</p><pre>@OneToOne<br>private Address address;<br><br><br>// Example:<br><br>// Employee → Address</pre><h4>One-to-Many</h4><p>One entity is associated with multiple entities.</p><pre>@OneToMany<br>private List&lt;Order&gt; orders;</pre><p>Example:</p><pre>Customer → Order 1<br>         → Order 2<br>         → Order 3</pre><h4>Many-to-One</h4><p>Multiple entities belong to one entity.</p><pre>@ManyToOne<br>private Customer customer;</pre><p>Example:</p><pre>Order 1 ──┐<br>Order 2 ──┼──→ Customer<br>Order 3 ──┘</pre><h4>Many-to-Many</h4><p>Multiple entities are associated with multiple entities.</p><pre>@ManyToMany<br>private List&lt;Role&gt; roles;</pre><p>Usually represented using a <strong>join table</strong>.</p><pre>Student ←→ Student_Course ←→ Course</pre><h3>Q4. Lazy vs Eager Loading</h3><p><em>Lazy loading is generally safer as a default for collections because it avoids loading potentially large amounts of unnecessary data. But the correct fetch strategy depends on the use case.</em></p><p>These define <strong>when related entities are loaded from the database</strong>.</p><h4>Lazy Loading</h4><p>The related data is loaded only when it is accessed.</p><pre>@OneToMany(fetch = FetchType.LAZY)<br>private List&lt;Order&gt; orders;</pre><p>Conceptually:</p><pre>Load Customer<br>     ↓<br>Orders NOT loaded<br><br>customer.getOrders()<br>     ↓<br>Load Orders</pre><h4>Eager Loading</h4><p>The related data is loaded immediately along with the entity.</p><pre>@ManyToOne(fetch = FetchType.EAGER)<br>private Customer customer;</pre><p>Conceptually:</p><pre>Load Customer<br>     ↓<br>Load related data immediately</pre><h4>Why does it matter?</h4><p>Eager loading can retrieve unnecessary data and generate expensive queries.</p><p>Lazy loading can reduce unnecessary database work, but accessing a lazy relationship after the persistence context is closed can cause:</p><pre>LazyInitializationException</pre><h3>Q5. What is the N+1 Query Problem?</h3><p><em>Don’t blindly change everything to EAGER loading to solve N+1. The better solution is to fetch exactly the data required by the specific use case.</em></p><p>The <strong>N+1 problem</strong> occurs when the application executes:</p><ul><li>1 query to retrieve the parent records</li><li>N additional queries to retrieve related data for each parent</li></ul><p>Example:</p><pre>List&lt;Customer&gt; customers = customerRepository.findAll();<br><br>for (Customer customer : customers) {<br>    customer.getOrders().size();<br>}</pre><p>It might result in:</p><pre>1 query → Fetch all customers<br><br>N queries → Fetch orders for each customer</pre><p>If there are 100 customers:</p><pre>1 + 100 = 101 queries</pre><h4>How can we solve it?</h4><p>Common approaches include:</p><p><strong>Fetch Join</strong></p><pre>@Query(&quot;&quot;&quot;<br>    SELECT c FROM Customer c<br>    JOIN FETCH c.orders<br>&quot;&quot;&quot;)<br>List&lt;Customer&gt; findCustomersWithOrders();</pre><p>Other approaches include:</p><ul><li>Entity graphs</li><li>Batch fetching</li><li>DTO projections</li><li>Carefully designed queries</li></ul><h3>Q6. What are Transactions?</h3><p>A <strong>transaction</strong> is a group of database operations that should be treated as a single unit of work.</p><p>A transaction generally follows the <strong>ACID</strong> properties:</p><pre>Atomicity<br>Consistency<br>Isolation<br>Durability</pre><p>Example:</p><pre>@Transactional<br>public void transferMoney() {<br><br>    accountRepository.debit(from, amount);<br><br>    accountRepository.credit(to, amount);<br>}</pre><p>If the second operation fails, the transaction can be rolled back so that the first operation isn’t permanently committed.</p><h4>Transaction boundaries</h4><p>In Spring, @Transactional is commonly used to define the transaction boundary:</p><pre>@Transactional<br>public void processOrder() {<br>    // database operations<br>}</pre><h3>Q7. What is Locking in JPA?</h3><p><em>Optimistic locking is generally preferable when conflicts are uncommon; pessimistic locking can be useful when preventing concurrent modification at the database level is critical.</em></p><p>Locking is used to control how multiple transactions access the <strong>same database records concurrently</strong>.</p><p>There are two major approaches.</p><h4>Optimistic Locking</h4><p>Assumes conflicts are relatively rare.</p><p>JPA commonly uses @Version:</p><pre>@Entity<br>class Product {<br><br>    @Id<br>    private Long id;<br><br>    @Version<br>    private Long version;<br>}</pre><p>Conceptually:</p><pre>Transaction A → version 1<br>Transaction B → version 1<br><br>A updates → version 2<br>B tries update with version 1<br>       ↓<br>Conflict detected</pre><p>This prevents one transaction from silently overwriting another transaction’s changes.</p><h4>Pessimistic Locking</h4><p>Assumes conflicts are likely and obtains a database lock.</p><p>Example:</p><pre>@Lock(LockModeType.PESSIMISTIC_WRITE)<br>Optional&lt;Product&gt; findById(Long id);</pre><p>The database locks the relevant row so that conflicting operations must wait according to the database’s locking rules.</p><h4>Comparison</h4><pre>| Optimistic                   | Pessimistic                      |<br>| ---------------------------- | -------------------------------- |<br>| Assumes conflicts are rare   | Assumes conflicts may happen     |<br>| Uses version checking        | Uses database locks              |<br>| Less blocking                | More blocking                    |<br>| Good for many read scenarios | Useful for highly contested data |</pre><h3>Q8. What is Indexing and Why is it Important?</h3><p><em>Don’t create an index on every column. Design indexes based on actual query patterns, selectivity, ordering, joins, and measured execution plans.</em></p><p>A <strong>database index</strong> is a data structure that helps the database find rows faster without scanning the entire table.</p><p>Without an appropriate index:</p><pre>Query<br> ↓<br>Scan many/all rows<br> ↓<br>Find matching rows</pre><p>With an index:</p><pre>Query<br> ↓<br>Index lookup<br> ↓<br>Locate matching rows<br> ↓<br>Fetch rows</pre><p>For example:</p><pre>CREATE INDEX idx_employee_email<br>ON employee(email);</pre><p>Now a query such as:</p><pre>SELECT *<br>FROM employee<br>WHERE email = &#39;abc@example.com&#39;;</pre><p>can potentially use the index instead of scanning the entire table.</p><h4>Composite Index</h4><p>An index can contain multiple columns:</p><pre>CREATE INDEX idx_employee_status_date<br>ON employee(status, created_date);</pre><p>The <strong>column order matters</strong> because databases can use composite indexes most effectively according to their index structure and query predicates.</p><h3>Important trade-off</h3><p>Indexes are not free.</p><p>They can:</p><ul><li>Speed up reads</li><li>Consume storage</li><li>Increase INSERT, UPDATE, and DELETE overhead</li><li>Require maintenance</li></ul><h3>Quick Interview Revision</h3><pre>| Topic                | Key Point                                          |<br>| -------------------- | -------------------------------------------------- |<br>| JPA                  | Persistence specification                          |<br>| Hibernate            | JPA implementation                                 |<br>| IDENTITY             | Database identity/auto-increment                   |<br>| SEQUENCE             | Database sequence                                  |<br>| Entity Relationships | One-to-one, one-to-many, many-to-one, many-to-many |<br>| Lazy                 | Load relationship when accessed                    |<br>| Eager                | Load relationship immediately                      |<br>| N+1                  | 1 query + N additional queries                     |<br>| Transaction          | Group operations into one unit                     |<br>| Optimistic Locking   | Version-based conflict detection                   |<br>| Pessimistic Locking  | Database-level locking                             |<br>| Index                | Faster data lookup, but adds write/storage cost    |</pre><p>These are some of the most frequently asked JPA &amp; JDBC interview questions.<strong> If you found this article useful, do give it a 👏 Clap!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3223658d9b1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring / Spring Boot — Interview Questions & Answers]]></title>
            <link>https://medium.com/@anujsinghpp123/spring-spring-boot-interview-questions-answers-e02a2ec55a71?source=rss-2346d54147f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e02a2ec55a71</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[annotations]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Anuj Singh]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 21:01:21 GMT</pubDate>
            <atom:updated>2026-08-18T21:13:52.144Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jap_cRszSOiPk-lu65mFLw.png" /></figure><h3>Q1. What are IoC and DI?</h3><p><strong>IoC (Inversion of Control)</strong> means the responsibility of creating and managing objects is given to the <strong>Spring Container</strong> instead of the developer manually creating them.</p><p><strong>DI (Dependency Injection)</strong> is the mechanism Spring uses to implement IoC. Spring creates the required objects (beans) and injects them into other objects.</p><p>For example:</p><pre>@Service<br>class UserService {<br>}<br><br>@RestController<br>class UserController {<br><br>    private final UserService userService;<br><br>    UserController(UserService userService) {<br>        this.userService = userService;<br>    }<br>}</pre><p>Here, UserController doesn&#39;t create UserService using new. Spring creates UserService and injects it into the controller.</p><pre>Without DI:<br>Controller → new UserService()<br><br>With DI:<br>Spring Container → creates UserService<br>                 → injects into Controller</pre><h3>Q2. Explain the Spring Bean Lifecycle</h3><p>A <strong>Spring Bean</strong> is an object that is created and managed by the Spring IoC container.</p><p>A simplified lifecycle is:</p><pre>Bean Definition<br>      ↓<br>Bean Instantiation<br>      ↓<br>Dependency Injection<br>      ↓<br>Aware callbacks<br>      ↓<br>BeanPostProcessor (before initialization)<br>      ↓<br>@PostConstruct<br>      ↓<br>InitializingBean / init-method<br>      ↓<br>BeanPostProcessor (after initialization)<br>      ↓<br>Bean Ready<br>      ↓<br>@PreDestroy<br>      ↓<br>Bean Destroyed</pre><p>For example:</p><pre>@PostConstruct<br>public void init() {<br>    System.out.println(&quot;Bean initialized&quot;);<br>}<br><br>@PreDestroy<br>public void cleanup() {<br>    System.out.println(&quot;Bean destroyed&quot;);<br>}</pre><p>Spring first creates the bean, injects its dependencies, performs initialization callbacks, and then makes it available for use.</p><p>When the application context is closed, Spring performs the destruction callbacks for beans whose lifecycle it manages.</p><h3>Q3. What is Autowiring in Spring?</h3><p><em>Constructor injection is generally preferred because dependencies are explicit and the object can be created only when its required dependencies are available.</em></p><p><strong>Autowiring</strong> means Spring automatically finds a suitable bean and injects it as a dependency.</p><p>Example:</p><pre>@Service<br>class UserService {<br>}<br><br>@RestController<br>class UserController {<br><br>    private final UserService userService;<br><br>    @Autowired<br>    UserController(UserService userService) {<br>        this.userService = userService;<br>    }<br>}</pre><p>With a single constructor, @Autowired can be omitted:</p><pre>UserController(UserService userService) {<br>    this.userService = userService;<br>}</pre><h4>What if multiple beans have the same type?</h4><p>Spring cannot decide which bean to inject.</p><p>We can use @Qualifier:</p><pre>UserService(@Qualifier(&quot;primaryService&quot;)<br>            UserService service) {<br>    this.service = service;<br>}</pre><p>Or use @Primary to mark one bean as the default choice.</p><h3>Q4. @Controller vs @RestController</h3><p><em>Use </em><em>@Controller when returning views; use </em><em>@RestController when building REST APIs.</em></p><p>Both are used to create Spring MVC controllers, but their return-value behavior is different.</p><h4>@Controller</h4><p>Generally used for MVC applications where methods return <strong>view names</strong>.</p><pre>@Controller<br>class UserController {<br><br>    @GetMapping(&quot;/users&quot;)<br>    public String users() {<br>        return &quot;users&quot;;<br>    }<br>}</pre><p>Spring resolves &quot;users&quot; as a view.</p><h4>@RestController</h4><p>@RestController is effectively:</p><pre>@Controller<br>@ResponseBody</pre><p>It is commonly used for REST APIs.</p><pre>@RestController<br>class UserController {<br><br>    @GetMapping(&quot;/users&quot;)<br>    public List&lt;User&gt; users() {<br>        return userService.getUsers();<br>    }<br>}</pre><p>The returned object is written directly to the HTTP response body, usually as JSON.</p><h3>Q5. What is @SpringBootApplication?</h3><p><em>@SpringBootApplication reduces configuration by combining component scanning, auto-configuration, and Spring Boot configuration.</em></p><p>@SpringBootApplication is a convenience annotation that combines three important annotations:</p><pre>@SpringBootConfiguration<br>@EnableAutoConfiguration<br>@ComponentScan</pre><h4>@SpringBootConfiguration</h4><p>Indicates that the class provides Spring Boot configuration.</p><h4>@EnableAutoConfiguration</h4><p>Tells Spring Boot to automatically configure beans based on the dependencies and configuration available in the application.</p><p>For example, if Spring MVC dependencies are present, Spring Boot can automatically configure the required MVC infrastructure.</p><h4>@ComponentScan</h4><p>Tells Spring where to search for Spring components such as:</p><pre>@Component<br>@Service<br>@Repository<br>@Controller</pre><p>Example:</p><pre>@SpringBootApplication<br>public class Application {<br>    public static void main(String[] args) {<br>        SpringApplication.run(Application.class, args);<br>    }<br>}</pre><h3>Q6. Explain REST HTTP Methods</h3><p>REST APIs use HTTP methods to represent operations on resources.</p><pre>| Method | Common Purpose              |<br>| -------| --------------------------- |<br>| GET    | Retrieve data               |<br>| POST   | Create a resource           |<br>| PUT    | Replace/update a resource   |<br>| PATCH  | Partially update a resource |<br>| DELETE | Delete a resource           |</pre><p>Example:</p><pre>GET    /users/10      → Get user<br>POST   /users         → Create user<br>PUT    /users/10      → Replace user<br>PATCH  /users/10      → Partially update user<br>DELETE /users/10      → Delete user</pre><h4>Important concept: Idempotency</h4><p>An operation is <strong>idempotent</strong> if making the same request multiple times has the same intended effect as making it once.</p><p>Generally:</p><pre>GET     → Idempotent<br>PUT     → Idempotent<br>DELETE  → Idempotent<br>POST    → Not necessarily idempotent<br>PATCH   → Depends on implementation</pre><h3>Q7. What is CORS?</h3><p><em>CORS is primarily a </em><strong><em>browser-enforced cross-origin policy</em></strong><em>. It is not an authentication mechanism and does not protect your API from non-browser clients.</em></p><p><strong>CORS (Cross-Origin Resource Sharing)</strong> is a browser security mechanism that controls whether a web application from one origin can make requests to a different origin.</p><p>For example:</p><pre>Frontend:<br>http://localhost:3000<br><br>Backend:<br>http://localhost:8080</pre><p>These are different origins because their ports differ.</p><p>The browser may block the request unless the backend allows the frontend’s origin through CORS configuration.</p><p>In Spring:</p><pre>@CrossOrigin(origins = &quot;http://localhost:3000&quot;)<br>@RestController<br>class UserController {<br>}</pre><p>CORS can also be configured globally.</p><h3>Q8. How Does Spring Security JWT Authentication Work?</h3><p><em>JWT provides a way to carry authentication information, but it is not encryption by default. Sensitive information should not simply be placed in JWT claims because JWT payloads are generally readable by the client.</em></p><p>JWT (<strong>JSON Web Token</strong>) is commonly used for stateless authentication in REST APIs.</p><p>A typical flow is:</p><pre>Client<br>  ↓<br>Login credentials<br>  ↓<br>Authentication API<br>  ↓<br>Validate credentials<br>  ↓<br>Generate JWT<br>  ↓<br>Client stores token</pre><p>For subsequent requests:</p><pre>Client<br>  ↓<br>Authorization: Bearer &lt;JWT&gt;<br>  ↓<br>Spring Security Filter<br>  ↓<br>Validate JWT<br>  ↓<br>Extract user/authorities<br>  ↓<br>SecurityContext<br>  ↓<br>Controller</pre><p>A JWT typically contains claims such as user identity, expiration time, and authorities.</p><p>The server validates the token’s <strong>signature and claims</strong> before trusting its contents.</p><p>JWT-based authentication is usually <strong>stateless</strong>, meaning the server doesn’t need to maintain a traditional server-side session for each authenticated user.</p><h3>Q9. How Does Caching Work in Spring?</h3><p>Caching stores frequently accessed data so that subsequent requests can retrieve it faster instead of repeatedly performing expensive operations such as database queries.</p><p>Spring provides caching abstractions such as:</p><pre>@Cacheable<br>@CachePut<br>@CacheEvict</pre><p>Example:</p><pre>@Cacheable(&quot;users&quot;)<br>public User getUser(Long id) {<br>    return userRepository.findById(id).orElseThrow();<br>}</pre><p>First call:</p><pre>Request → Method → Database → Cache</pre><p>Next call:</p><pre>Request → Cache → Return result</pre><h3>Important annotations</h3><p><strong>@Cacheable</strong><br> If data exists in the cache, return it without executing the method.</p><p><strong>@CachePut</strong><br> Executes the method and updates the cache with the result.</p><p><strong>@CacheEvict</strong><br> Removes data from the cache.</p><p>Common cache implementations include:</p><ul><li>Caffeine</li><li>Redis</li><li>Ehcache</li></ul><h3>Q10. Explain DispatcherServlet Lifecycle</h3><p><em>DispatcherServlet doesn&#39;t contain the business logic. Its job is to </em><strong><em>coordinate request processing between Spring MVC components</em></strong><em>.</em></p><p>DispatcherServlet is the <strong>front controller of Spring MVC</strong>. It receives incoming HTTP requests and coordinates the request processing.</p><p>Simplified flow:</p><pre>Client<br>  ↓<br>DispatcherServlet<br>  ↓<br>HandlerMapping<br>  ↓<br>Controller<br>  ↓<br>Service<br>  ↓<br>Repository<br>  ↓<br>Response</pre><p>More specifically:</p><pre>HTTP Request<br>     ↓<br>DispatcherServlet<br>     ↓<br>HandlerMapping<br>     ↓<br>Find Controller/Handler<br>     ↓<br>HandlerAdapter<br>     ↓<br>Controller Method<br>     ↓<br>Return Result<br>     ↓<br>HttpMessageConverter / ViewResolver<br>     ↓<br>HTTP Response</pre><h4>Example</h4><p>For:</p><pre>GET /users/10</pre><p>DispatcherServlet receives the request and asks HandlerMapping which controller method should handle it.</p><p>The appropriate HandlerAdapter invokes that method.</p><p>For a REST controller, the returned object is generally converted into JSON using an appropriate <strong>HttpMessageConverter</strong>.</p><h3>Quick Interview Revision</h3><pre>| Topic                  | Key Point                                           |<br>| ---------------------- | --------------------------------------------------- |<br>| IoC                    | Spring controls object creation/lifecycle           |<br>| DI                     | Spring injects dependencies                         |<br>| Bean Lifecycle         | Create → Inject → Initialize → Use → Destroy        |<br>| Autowiring             | Automatic dependency injection                      |<br>| @Controller            | Usually returns views                               |<br>| @RestController        | Returns response body                               |<br>| @SpringBootApplication | Configuration + Auto-configuration + Component Scan |<br>| GET                    | Retrieve                                            |<br>| POST                   | Create                                              |<br>| PUT                    | Replace                                             |<br>| PATCH                  | Partial update                                      |<br>| DELETE                 | Delete                                              |<br>| CORS                   | Controls browser cross-origin requests              |<br>| JWT                    | Stateless token-based authentication                |<br>| Caching                | Avoid repeated expensive operations                 |<br>| DispatcherServlet      | Front controller of Spring MVC                      |</pre><p>These are some of the most frequently asked Spring &amp; Spring Boot interview questions. <strong>If you found this article useful, do give it a 👏 Clap!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e02a2ec55a71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Collections — Interview Questions & Answers]]></title>
            <link>https://medium.com/@anujsinghpp123/java-collections-interview-questions-answers-18e1d2d48ee0?source=rss-2346d54147f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/18e1d2d48ee0</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[collections-framework]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[lists]]></category>
            <dc:creator><![CDATA[Anuj Singh]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 20:43:09 GMT</pubDate>
            <atom:updated>2026-08-15T20:43:09.702Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jap_cRszSOiPk-lu65mFLw.png" /></figure><h3>Q1. What is the Internal Working of ArrayList?</h3><p>ArrayList is a <strong>resizable array implementation</strong> of the List interface.</p><p>Internally, it uses an array to store elements:</p><pre>ArrayList<br>   ↓<br>Object[]<br>[10] [20] [30] [40] [  ] [  ] ...</pre><p>When the array becomes full, ArrayList creates a <strong>larger array</strong> and copies the existing elements into it.<br>Important points:</p><ul><li>Allows duplicate elements.</li><li>Maintains insertion order.</li><li>Allows null.</li><li>Provides fast random access using index: <strong>O(1)</strong>.</li><li>Adding at the end is usually <strong>O(1) amortized</strong>.</li><li>Inserting/removing from the middle is <strong>O(n)</strong> because elements need to be shifted.</li><li>It is <strong>not thread-safe</strong>.</li></ul><p>Example:</p><pre>List&lt;Integer&gt; list = new ArrayList&lt;&gt;();<br><br>list.add(10);<br>list.add(20);<br>list.add(30);</pre><h3>Q2. What is the Internal Working of HashMap?</h3><p>HashMap stores data as <strong>key-value pairs</strong>.</p><pre>Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();<br>map.put(&quot;Java&quot;, 100);</pre><p>Internally, it uses an array of <strong>buckets</strong>. When we insert a key, its hashCode() is used to calculate a bucket location.</p><p>Conceptually:</p><pre>Key<br> ↓<br>hashCode()<br> ↓<br>Hash calculation<br> ↓<br>Bucket<br> ↓<br>Key-Value Entry</pre><p>If multiple keys map to the same bucket, a <strong>collision</strong> occurs. Java handles collisions using linked structures, and in modern Java, a heavily-collided bucket can be converted into a <strong>Red-Black Tree</strong>.</p><p>When retrieving:</p><pre>map.get(&quot;Java&quot;);</pre><p>HashMap calculates the hash again, finds the bucket, and compares keys using equals() to locate the correct entry.</p><p>Average complexity:</p><pre>put() → O(1)<br>get() → O(1)<br>remove() → O(1)</pre><p>These are average cases; collisions can affect performance.</p><p><strong>Important:</strong> HashMap allows one null key and multiple null values and is not thread-safe.</p><h3>Q3. ConcurrentHashMap vs Hashtable</h3><p>Both are thread-safe maps, but their concurrency mechanisms are different.</p><h4>Hashtable</h4><p>Hashtable is a legacy collection. Its main methods are synchronized, meaning access is heavily serialized.</p><pre>Hashtable&lt;Integer, String&gt; table = new Hashtable&lt;&gt;();</pre><h4>ConcurrentHashMap</h4><p>ConcurrentHashMap was designed for <strong>high-concurrency applications</strong></p><pre>ConcurrentHashMap&lt;Integer, String&gt; map =<br>        new ConcurrentHashMap&lt;&gt;();</pre><p>It allows multiple threads to operate on different parts of the map concurrently and uses modern synchronization/atomic mechanisms internally.</p><pre>| Hashtable                         | ConcurrentHashMap                  |<br>| --------------------------------- | ---------------------------------- |<br>| Legacy                            | Modern                             |<br>| Synchronized methods              | Fine-grained concurrency           |<br>| Lower concurrency                 | Higher concurrency                 |<br>| Does not allow `null` key/value   | Does not allow `null` key/value    |<br>| Generally slower under contention | Better for concurrent applications |</pre><h3>Q4. Vector vs ArrayList</h3><p><em>Don’t choose </em><em>Vector simply because it is synchronized. For concurrent use, choose a collection based on the actual concurrency requirements.</em></p><p>Both are <strong>dynamic arrays</strong>, but they differ mainly in thread safety.</p><h4>Vector</h4><p>Vector is a legacy collection whose major methods are synchronized.</p><h4>ArrayList</h4><p>ArrayList is not synchronized and is therefore generally faster in single-threaded scenarios.</p><pre>| Vector                                | ArrayList        |<br>| ------------------------------------- | ---------------- |<br>| Legacy                                | Modern           |<br>| Synchronized                          | Not synchronized |<br>| Thread-safe for individual operations | Not thread-safe  |<br>| Generally slower                      | Generally faster |<br>| Dynamic array                         | Dynamic array    |</pre><h3>Q5. LinkedList vs ArrayList</h3><p><em>Don’t assume </em><em>LinkedList is automatically faster for insertions. If you first need to traverse to the insertion position, that traversal itself can be O(n). In most everyday application code, </em><em>ArrayList is the better default.</em></p><p>Both implementList, but their internal structures are different.</p><h4>ArrayList</h4><p>Uses a <strong>dynamic array</strong>.</p><pre>[10] [20] [30] [40]</pre><p>Provides fast index-based access:</p><pre>list.get(2);</pre><p>Time complexity: <strong>O(1)</strong>.</p><h4>LinkedList</h4><p>Uses a <strong>doubly linked list</strong>.</p><pre>10 ↔ 20 ↔ 30 ↔ 40</pre><p>Accessing an element by index requires traversal, so:</p><pre>list.get(30);</pre><p>is <strong>O(n)</strong>.</p><pre>| ArrayList                     | LinkedList                                     |<br>| ----------------------------- | ---------------------------------------------- |<br>| Dynamic array                 | Doubly linked list                             |<br>| `get()` → O(1)                | `get()` → O(n)                                 |<br>| Better cache locality         | More pointer overhead                          |<br>| Usually better default choice | Useful for specific insertion/removal patterns |</pre><h3>Q6. TreeMap vs HashMap</h3><p><em>Use </em><em>HashMap when you primarily need fast lookup; use </em><em>TreeMap when you need keys maintained in sorted order or need navigational operations.</em></p><h4>HashMap</h4><p>Uses hashing and provides average <strong>O(1)</strong> lookup.</p><pre>Map&lt;Integer, String&gt; map = new HashMap&lt;&gt;();</pre><p>It does <strong>not maintain sorted key order</strong>.</p><h4>TreeMap</h4><p>Uses a <strong>Red-Black Tree</strong> and keeps keys sorted.</p><pre>Map&lt;Integer, String&gt; map = new TreeMap&lt;&gt;();</pre><p>Operations such as put(), get(), and remove() generally take <strong>O(log n)</strong>.</p><pre>| HashMap             | TreeMap                                               |<br>| ------------------- | ----------------------------------------------------- |<br>| Hash table          | Red-Black Tree                                        |<br>| Average O(1)        | O(log n)                                              |<br>| No sorted order     | Sorted by keys                                        |<br>| Allows one null key | Null keys generally not allowed with natural ordering |<br>| Faster lookup       | Useful when sorted order is required                  |</pre><h3>Q7. What are Immutable Classes?</h3><p>An <strong>immutable object cannot be modified after it is created</strong>.</p><p>The most common example is String.</p><pre>String name = &quot;Java&quot;;<br><br>name.concat(&quot; Programming&quot;);<br><br>System.out.println(name); // Java</pre><p>concat() does not modify the original String; it creates a new object.</p><h4>How to create an immutable class?</h4><p>Typically:</p><ol><li>Make the class final.</li><li>Make fields private and final.</li><li>Initialize fields through the constructor.</li><li>Don’t provide setters.</li><li>Don’t expose mutable internal objects directly.</li><li>Return defensive copies when necessary.</li></ol><p>Example:</p><pre>final class Employee {<br>    private final String name;<br><br>    Employee(String name) {<br>        this.name = name;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br>}</pre><h3>Q8. Shallow Copy vs Deep Copy</h3><h4>Shallow Copy</h4><p>A shallow copy creates a new outer object but <strong>references the same nested objects</strong>.</p><pre>Original ──→ Address<br>Copy     ───┘</pre><p>So modifying the nested object through one copy can affect the other.</p><h4>Deep Copy</h4><p>A deep copy creates a new outer object and <strong>copies the nested objects as well</strong>.</p><pre>Original → Address A<br>Copy     → Address B</pre><p>Changes to one object’s nested state don’t affect the other.</p><p>Example:</p><pre>Employee e1 = ...;<br>Employee e2 = shallowCopy(e1);</pre><p>Both may point to the same Address.</p><p>With deep copying:</p><pre>Employee e2 = deepCopy(e1);</pre><p>e2 gets its own Address.</p><h3>Q9. Comparator vs Comparable</h3><p><em>Use </em><em>Comparable when the class has a clear natural order; use </em><em>Comparator when sorting requirements can vary.</em></p><p>Both are used for <strong>sorting objects</strong>.</p><h4>Comparable</h4><p>Used when a class defines its <strong>natural ordering</strong>.</p><pre>class Employee implements Comparable&lt;Employee&gt; {<br><br>    private int age;<br><br>    @Override<br>    public int compareTo(Employee other) {<br>        return Integer.compare(this.age, other.age);<br>    }<br>}</pre><p>Then:</p><pre>Collections.sort(employees);</pre><h4>Comparator</h4><p>Used when we want to define sorting <strong>outside the class</strong> or need multiple sorting strategies.</p><pre>employees.sort(<br>    Comparator.comparing(Employee::getName)<br>);</pre><pre>| Comparable                   | Comparator                           |<br>| ---------------------------- | ------------------------------------ |<br>| `compareTo()`                | `compare()`                          |<br>| Defines natural ordering     | Defines custom ordering              |<br>| Implemented by the class     | Separate object/interface            |<br>| Usually one natural ordering | Multiple sorting strategies possible |</pre><h3>Q10. What is CopyOnWriteArrayList?</h3><p>CopyOnWriteArrayList is a <strong>thread-safe List implementation</strong> designed for scenarios with <strong>many reads and very few writes</strong>.</p><p>When a modification occurs, it creates a <strong>new copy of the underlying array</strong>.</p><pre>Before write:<br><br>Readers → [A B C]<br><br>Write<br><br>After write:<br><br>Readers → [A B C]<br>Writer  → [A B C D]</pre><p>Readers can continue reading without being blocked by the writer.</p><p>Advantages:</p><ul><li>Thread-safe</li><li>Excellent for read-heavy workloads</li><li>Iterators don’t throw ConcurrentModificationException due to concurrent modifications</li></ul><p>Disadvantage:</p><ul><li>Every write creates a new array, making writes expensive.</li><li>Can consume significant memory for large lists.</li></ul><p>Typical use cases include configuration data or listener lists that are read frequently but modified rarely.</p><h3>Q11. What is WeakHashMap and What are References?</h3><p><em>WeakHashMap is useful when you don&#39;t want the map itself to prevent its keys from being garbage collected.</em></p><p>WeakHashMap stores keys using <strong>weak references</strong>.</p><p>If a key is no longer strongly referenced elsewhere, the Garbage Collector can remove that key from the map.</p><pre>Map&lt;Key, Value&gt; map = new WeakHashMap&lt;&gt;();</pre><p>Conceptually:</p><pre>Strong Reference<br>      ↓<br>     Key<br>      ↓<br> WeakHashMap</pre><p>If the strong reference disappears:</p><pre>Strong Reference → removed<br>        ↓<br>       Key<br>        ↓<br>      GC can collect it<br>        ↓<br> WeakHashMap entry disappears</pre><p>This can be useful for certain caches or metadata where entries should not keep keys alive.</p><h4>Reference types</h4><p>Java provides different reference strengths:</p><ul><li><strong>Strong Reference</strong> — normal reference; object remains reachable.</li><li><strong>Soft Reference</strong> — may be collected when memory is needed.</li><li><strong>Weak Reference</strong> — can be collected when no strong references remain.</li><li><strong>Phantom Reference</strong> — used for advanced lifecycle/cleanup mechanisms.</li></ul><h3>Q12. What is ConcurrentModificationException?</h3><p>ConcurrentModificationException generally occurs when a collection is <strong>structurally modified while it is being iterated</strong>, except through the iterator&#39;s own supported modification operation.</p><p>Example:</p><pre>List&lt;Integer&gt; numbers =<br>        new ArrayList&lt;&gt;(Arrays.asList(1, 2, 3));<br><br>for (Integer n : numbers) {<br>    if (n == 2) {<br>        numbers.remove(n);<br>    }<br>}</pre><p>This can throw:</p><pre>ConcurrentModificationException</pre><p>The common reason is that the collection detects that it has been structurally modified after the iterator was created.</p><h4>Correct approach</h4><p>Use the iterator:</p><pre>Iterator&lt;Integer&gt; iterator = numbers.iterator();<br><br>while (iterator.hasNext()) {<br>    if (iterator.next() == 2) {<br>        iterator.remove();<br>    }<br>}</pre><p>Or use appropriate collection APIs:</p><pre>numbers.removeIf(n -&gt; n == 2);</pre><p><strong>Important:</strong> The name can be misleading. ConcurrentModificationException does <strong>not necessarily mean multiple threads</strong> are involved. It can happen in a single thread when a collection is modified during iteration.</p><p>Also, this behavior is generally <strong>fail-fast, not a synchronization guarantee</strong>. It is intended to detect bugs early, not to provide thread safety.</p><p>These are some of the most frequently asked Java Collections interview questions. <strong>If you liked this article, do give it a 👏 Clap!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18e1d2d48ee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Multithreading — Interview Questions & Answers]]></title>
            <link>https://medium.com/@anujsinghpp123/java-multithreading-interview-questions-answers-6277bca936fb?source=rss-2346d54147f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6277bca936fb</guid>
            <category><![CDATA[locks]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[synchronization]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Anuj Singh]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 19:57:15 GMT</pubDate>
            <atom:updated>2026-08-15T19:57:45.298Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jap_cRszSOiPk-lu65mFLw.png" /></figure><h3>Q1. Thread vs Runnable vs Callable</h3><p>These three are related to executing tasks concurrently, but they serve different purposes.</p><h4>Thread</h4><p>Thread represents an actual thread of execution.</p><pre>class MyThread extends Thread {<br>    @Override<br>    public void run() {<br>        System.out.println(&quot;Task running&quot;);<br>    }<br>}<br><br>new MyThread().start();</pre><h4>Runnable</h4><p>Runnable represents a <strong>task that can be executed by a thread</strong>. It does not return a result.</p><pre>Runnable task = () -&gt; System.out.println(&quot;Task running&quot;);<br><br>new Thread(task).start();</pre><h4>Callable</h4><p>Callable is similar toRunnable, but it <strong>returns a result and can throw checked exceptions</strong>.</p><pre>Callable&lt;Integer&gt; task = () -&gt; 10 + 20;</pre><p>It is commonly used with ExecutorService and Future.</p><pre>|                   | Thread                 | Runnable       | Callable               |<br>| ----------------- | ---------------------- | -------------- | ---------------------- |<br>| Represents        | Thread                 | Task           | Task                   |<br>| Return value      | No                     | No             | Yes                    |<br>| Checked exception | No                     | No             | Yes                    |<br>| Common use        | Direct thread creation | Task execution | Async task with result |</pre><h3>Q2. What is the synchronized Keyword?</h3><p>synchronized is used to control access to shared resources by allowing <strong>only one thread at a time</strong> to execute a synchronized section for the same monitor.</p><p>Example:</p><pre>public synchronized void increment() {<br>    count++;<br>}</pre><p>When a thread enters the synchronized method, it acquires the object’s <strong>monitor lock</strong>. Other threads trying to enter synchronized code protected by the same monitor must wait until the lock is released.</p><p>synchronized provides:</p><ul><li><strong>Mutual exclusion</strong> — only one thread executes the critical section at a time.</li><li><strong>Visibility</strong> — changes made before releasing the monitor become visible to a thread that subsequently acquires the same monitor.</li></ul><p>It is mainly used to protect <strong>shared mutable state</strong> from race conditions.</p><h3>Q3. Method vs Block Synchronization</h3><p><em>The important difference is </em><strong><em>lock scope and lock object</em></strong><em>, not that one is inherently thread-safe and the other isn’t.</em></p><p>Both use the synchronized mechanism, but the scope of locking is different.</p><h4>Synchronized Method</h4><pre>public synchronized void update() {<br>    // entire method is synchronized<br>}</pre><p>For an instance method, the lock is acquired on this.</p><h4>Synchronized Block</h4><pre>public void update() {<br><br>    // non-critical work<br><br>    synchronized (this) {<br>        // only this section is synchronized<br>    }<br>}</pre><p>A synchronized block allows us to lock only the <strong>critical section</strong> and even choose a specific lock object.</p><pre>synchronized (lockObject) {<br>    // critical section<br>}</pre><h4>Which is better?</h4><p>A synchronized block is often preferable when only a small portion of the method needs protection because it can reduce the scope of locking.</p><h3>Q4. Locks vs synchronized</h3><p><em>Use </em><em>synchronized when simple mutual exclusion is enough. Use </em><em>Lock when you actually need its additional capabilities.</em></p><p>Both provide synchronization, but explicit locks from java.util.concurrent.locks provide more control.</p><h4>synchronized</h4><pre>synchronized (lock) {<br>    // critical section<br>}</pre><p>The JVM automatically acquires and releases the monitor.</p><h4>Lock</h4><pre>Lock lock = new ReentrantLock();<br><br>lock.lock();<br>try {<br>    // critical section<br>} finally {<br>    lock.unlock();<br>}</pre><p>Lock provides features that synchronized does not directly provide, such as:</p><ul><li>tryLock()</li><li>Interruptible lock acquisition</li><li>Optional fairness</li><li>Multiple Condition objects</li></ul><pre>| `synchronized`   | `Lock`                 |<br>| ---------------- | ---------------------- |<br>| Simple           | More flexible          |<br>| Automatic unlock | Must explicitly unlock |<br>| No `tryLock()`   | Supports `tryLock()`   |<br>| Less control     | More control           |</pre><h3>Q5. What is ReentrantLock?</h3><p><em>ReentrantLock is useful when you need features beyond what </em><em>synchronized provides.</em></p><p>ReentrantLock is an explicit lock implementation from java.util.concurrent.locks.</p><p>It is called <strong>reentrant</strong> because the same thread can acquire the lock multiple times without deadlocking itself.</p><pre>Lock lock = new ReentrantLock();<br><br>lock.lock();<br>try {<br>    // critical section<br>} finally {<br>    lock.unlock();<br>}</pre><p>If the same thread calls another method that acquires the same lock, it can acquire it again.</p><pre>Thread<br>  ↓<br>acquire lock<br>  ↓<br>method A<br>  ↓<br>method B<br>  ↓<br>acquire same lock again</pre><p>The thread must release the lock the same number of times it acquired it.</p><p>Useful features include:</p><pre>lock.tryLock();<br>lock.lockInterruptibly();</pre><p>It can also optionally provide <strong>fairness</strong>, allowing waiting threads to acquire the lock in a more ordered manner.</p><h3>Q6. wait() vs sleep()</h3><p><em>sleep() is generally for timing; </em><em>wait() is for coordination between threads.</em></p><p>Both cause a thread to stop executing temporarily, but their behavior is fundamentally different.</p><h4>sleep()</h4><pre>Thread.sleep(1000);</pre><ul><li>Belongs to Thread.</li><li>Pauses the current thread for a specified time.</li><li><strong>Does not release locks</strong> held by the thread.</li></ul><h4>wait()</h4><pre>synchronized (lock) {<br>    lock.wait();<br>}</pre><ul><li>Belongs to Object.</li><li>Used for thread coordination.</li><li>The thread must own the object’s monitor.</li><li><strong>Releases that object’s monitor while waiting.</strong></li><li>Continues after another thread calls notify()/notifyAll() and the waiting thread reacquires the monitor.</li></ul><pre>| `sleep()`                    | `wait()`                            |<br>| ---------------------------- | ----------------------------------- |<br>| `Thread` method              | `Object` method                     |<br>| Used for timed pause         | Used for coordination               |<br>| Does not release monitor     | Releases monitor                    |<br>| Doesn&#39;t require synchronized | Must be called while owning monitor |</pre><h3>Q7. What is ThreadLocal?</h3><p><em>ThreadLocal doesn&#39;t make shared data thread-safe; it avoids sharing the data by giving each thread its own value.</em></p><p>ThreadLocal provides a way to store data that is <strong>isolated per thread</strong>.</p><pre>ThreadLocal&lt;Integer&gt; userId = new ThreadLocal&lt;&gt;();<br><br>userId.set(101);<br><br>System.out.println(userId.get());</pre><p>If multiple threads use the sameThreadLocal, each thread gets its <strong>own independent value</strong>.</p><pre>Thread 1 → ThreadLocal → 101<br>Thread 2 → ThreadLocal → 202<br>Thread 3 → ThreadLocal → 303</pre><p>This means threads don’t need to synchronize access to that particular state because the value isn’t shared between threads.</p><p>A common use case is storing <strong>thread-specific context</strong>, such as request-related information.</p><h4>Important caution</h4><p>ThreadLocal can cause problems with thread pools if values are not removed because pool threads are reused.</p><pre>try {<br>    threadLocal.set(value);<br>    // use value<br>} finally {<br>    threadLocal.remove();<br>}</pre><h3>Q8. What is ExecutorService?</h3><p>ExecutorService provides a framework for <strong>managing and executing tasks using a pool of threads</strong>.</p><p>Instead of creating a new thread for every task:</p><pre>new Thread(task).start();</pre><p>we can create a thread pool:</p><pre>ExecutorService executor =<br>        Executors.newFixedThreadPool(5);<br><br>executor.submit(() -&gt; {<br>    System.out.println(&quot;Task running&quot;);<br>});<br><br>executor.shutdown();</pre><p>The executor manages:</p><ul><li>Thread creation</li><li>Task submission</li><li>Thread reuse</li><li>Task scheduling</li><li>Shutdown</li></ul><p>It can execute both Runnable and Callable tasks.</p><pre>Future&lt;Integer&gt; future =<br>        executor.submit(() -&gt; 10 + 20);<br><br>Integer result = future.get();</pre><h4>Why use thread pools?</h4><p>Creating too many threads can cause memory consumption and context-switching overhead. A thread pool allows us to <strong>control concurrency and reuse threads</strong>.</p><h3>Q9. Race Condition vs Visibility Problem</h3><p>These are different multithreading problems.</p><p>Race Condition</p><p>A race condition occurs when the result depends on the <strong>timing/interleaving of multiple threads accessing shared state</strong>.</p><p>Example:</p><pre>count++;</pre><p>This looks like one operation, but it is effectively:</p><pre>Read<br> ↓<br>Modify<br> ↓<br>Write</pre><p>Two threads can read the same value and overwrite each other’s updates.</p><h4>Visibility Problem</h4><p>A visibility problem occurs when one thread updates a variable but another thread <strong>doesn’t see the latest value</strong> because there is no proper memory-visibility guarantee.</p><p>Example:</p><pre>boolean running = true;</pre><p>One thread changes it to false, but another thread may continue seeing the old value.</p><p>Using:</p><pre>volatile boolean running = true;</pre><p>provides the required visibility guarantee.</p><h4>Difference</h4><pre>Race Condition → Correctness problem caused by concurrent access/order<br>Visibility      → One thread may not see another thread&#39;s latest update</pre><p><strong>Important:</strong> volatile can solve certain visibility problems, but it does <strong>not</strong> make count++ atomic.</p><h3>Q10. CountDownLatch vs CyclicBarrier</h3><p>Both are synchronization utilities, but they solve different problems.</p><h4>CountDownLatch</h4><p>A CountDownLatch allows one or more threads to <strong>wait until a counter reaches zero</strong>.</p><pre>CountDownLatch latch = new CountDownLatch(3);</pre><p>Worker threads:</p><pre>latch.countDown();</pre><p>Waiting thread:</p><pre>latch.await();</pre><p>Example:</p><pre>Task 1 ──┐<br>Task 2 ──┼──→ count reaches 0 → Main continues<br>Task 3 ──┘</pre><p>Once the count reaches zero, the latch <strong>cannot be reset</strong>.</p><h4>CyclicBarrier</h4><p>A CyclicBarrier makes a group of threads <strong>wait for each other at a common barrier point</strong>.</p><pre>CyclicBarrier barrier = new CyclicBarrier(3);</pre><p>Each thread calls:</p><pre>barrier.await();</pre><p>When all three arrive, they can continue.</p><pre>Thread 1 ──→<br>Thread 2 ──→ Barrier ──→ Continue<br>Thread 3 ──→</pre><p>The barrier can be <strong>reused</strong> for another round.</p><h4>Difference</h4><pre>| CountDownLatch                 | CyclicBarrier                       |<br>| ------------------------------ | ----------------------------------- |<br>| Wait for a count to reach zero | Threads wait for each other         |<br>| Cannot be reset                | Reusable                            |<br>| One group can signal another   | Threads synchronize with each other |<br>| `countDown()` + `await()`      | `await()`                           |</pre><p>Easy way to remember:</p><pre>CountDownLatch → &quot;Wait until these tasks finish.&quot;<br>CyclicBarrier  → &quot;Everyone wait until we all arrive.&quot;</pre><h3>Quick Interview Revision</h3><pre>| Topic              | Key Point                                    |<br>| -------------------| -------------------------------------------- |<br>| Thread             | Represents execution thread                  |<br>| Runnable           | Task without result                          |<br>| Callable           | Task with result + checked exception         |<br>| synchronized       | Mutual exclusion + visibility                |<br>| Synchronized block | Smaller locking scope                        |<br>| Lock               | More control than synchronized               |<br>| ReentrantLock      | Explicit, reentrant lock                     |<br>| sleep()            | Pauses thread; doesn&#39;t release monitor       |<br>| wait()             | Waits for coordination; releases monitor     |<br>| ThreadLocal        | Thread-specific state                        |<br>| ExecutorService    | Manages thread pools and task execution      |<br>| Race Condition     | Result depends on concurrent execution order |<br>| Visibility         | Changes may not be visible across threads    |<br>| CountDownLatch     | Wait for tasks/countdown                     |<br>| CyclicBarrier      | Threads wait for each other                  |</pre><p>These are some of the most frequently asked Java Multithreading interview questions. <strong>If you found this article useful, do give it a 👏 Clap!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6277bca936fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java String — Interview Questions & Answers]]></title>
            <link>https://medium.com/@anujsinghpp123/java-string-interview-questions-answers-a8c07380954b?source=rss-2346d54147f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8c07380954b</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[string-vs-stringbuilder]]></category>
            <category><![CDATA[stringbuffer]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Anuj Singh]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 20:30:03 GMT</pubDate>
            <atom:updated>2026-08-14T20:30:03.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jap_cRszSOiPk-lu65mFLw.png" /></figure><h3>Q1. Why is String Immutable?</h3><p><em>String immutability improves performance, security, and thread safety.</em></p><p>A <strong>String is immutable</strong>, which means its value cannot be changed after creation.</p><p>Example:</p><pre>String str = &quot;Java&quot;;<br><br>str.concat(&quot; 8&quot;);<br><br>System.out.println(str);</pre><p>Output:</p><pre>Java</pre><p>A new String object is created, but str still points to the original object.</p><h4>Why was String made immutable?</h4><ul><li>Enables String Pool optimization.</li><li>Improves security (URLs, database connections, file paths cannot be modified).</li><li>Makes Strings naturally thread-safe.</li><li>Allows reliable caching of hash codes.</li></ul><h3>Q2. What is String Interning?</h3><p><em>String interning reduces memory usage by reusing identical String literals.</em></p><p><strong>String Interning</strong> is a mechanism where Java stores String literals in a special memory area called the <strong>String Pool</strong>.</p><p>Example:</p><pre>String s1 = &quot;Java&quot;;<br>String s2 = &quot;Java&quot;;</pre><p>Internally:</p><pre>String Pool<br>    │<br>  &quot;Java&quot;<br>   /  \<br> s1   s2</pre><p>Both variables point to the same object.</p><p>Verification:</p><pre>System.out.println(s1 == s2);</pre><p>Output:</p><pre>true</pre><h4>intern()</h4><p>The intern() method adds a String to the String Pool (if not already present) and returns the pooled reference.</p><pre>String s1 = new String(&quot;Java&quot;);<br>String s2 = s1.intern();</pre><h3>Q3. String vs StringBuffer vs StringBuilder</h3><p><em>For frequent String modifications, prefer </em><em>StringBuilder. Use </em><em>StringBuffer only when thread safety is required.</em></p><p>All three are used to work with character sequences, but they differ in mutability and thread safety.</p><h4>String:</h4><pre>String s = &quot;Java&quot;;<br>s += &quot; 8&quot;;</pre><p>Every modification creates a new object.</p><h4>StringBuffer</h4><pre>StringBuffer sb = new StringBuffer(&quot;Java&quot;);<br>sb.append(&quot; 8&quot;);</pre><ul><li>Mutable</li><li>Thread-safe (synchronized)</li></ul><h4>StringBuilder</h4><pre>StringBuilder sb = new StringBuilder(&quot;Java&quot;);<br>sb.append(&quot; 8&quot;);</pre><ul><li>Mutable</li><li>Not thread-safe</li><li>Faster than StringBuffer in single-threaded code</li></ul><h4>Comparison:</h4><pre>| Feature     | String                 | StringBuffer                 | StringBuilder                 |<br>| ----------- | ---------------------- | ---------------------------- | ----------------------------- |<br>| Mutable     | ❌                      | ✅                            | ✅                             |<br>| Thread Safe | ✅ (immutable)          | ✅                            | ❌                             |<br>| Performance | Slow for modifications | Moderate                     | Fastest                       |<br>| Use Case    | Read-only text         | Multi-threaded modifications | Single-threaded modifications |</pre><h3>Q4. How Many Objects Are Created in String?</h3><p><em>new String() always creates a new heap object, even if the same value already exists in the String Pool.</em></p><h4>Case 1</h4><pre>String s = &quot;Java&quot;;</pre><p>If &quot;Java&quot; does not exist in the String Pool:</p><pre>1 Object</pre><p>If it already exists:</p><pre>0 New Objects</pre><p>The existing pooled object is reused.</p><h4>Case 2</h4><pre>String s = new String(&quot;Java&quot;);</pre><p>Typically:</p><pre>String Pool  → &quot;Java&quot;<br>Heap         → new String(&quot;Java&quot;)</pre><p>Objects created:</p><pre>2 Objects</pre><ul><li>One in String Pool (if not already present)</li><li>One in Heap</li></ul><h4>Case 3</h4><pre>String s = new String(&quot;Java&quot;).intern();</pre><p>Internally:</p><ul><li>Heap object created</li><li>Pool object reused/created</li><li>Reference returned from pool</li></ul><h3>Q5. What is the Use of toString()?</h3><p><em>Whenever an object is printed using </em><em>System.out.println(obj), Java automatically calls </em><em>obj.toString().</em></p><p>toString() is a method of the Object class used to provide a meaningful String representation of an object.</p><p>Default implementation:</p><pre>Object obj = new Object();<br><br>System.out.println(obj);</pre><p>Output:</p><pre>java.lang.Object@1a2b3c</pre><p>This is usually not useful.</p><h4>Overriding toString()</h4><pre>class Employee {<br><br>    private String name;<br><br>    Employee(String name) {<br>        this.name = name;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Employee{name=&#39;&quot; + name + &quot;&#39;}&quot;;<br>    }<br>}</pre><p>Usage:</p><pre>Employee emp = new Employee(&quot;Anuj&quot;);<br><br>System.out.println(emp);</pre><p>Output:</p><pre>Employee{name=&#39;Anuj&#39;}</pre><h4>Why use it?</h4><ul><li>Better logging</li><li>Easier debugging</li><li>Meaningful object representation</li><li>Frequently used by frameworks and logging libraries</li></ul><h3>Quick Interview Revision</h3><pre>| Topic               | Key Point                               |<br>| ------------------- | --------------------------------------- |<br>| String Immutability | Cannot be modified after creation       |<br>| String Pool         | Reuses String literals                  |<br>| Interning           | Stores/retrieves String from pool       |<br>| String              | Immutable                               |<br>| StringBuffer        | Mutable + Thread-safe                   |<br>| StringBuilder       | Mutable + Fastest                       |<br>| new String()        | Creates new heap object                 |<br>| toString()          | Returns String representation of object |</pre><p>These are some of the most frequently asked Java String interview questions. <strong>If you found this article helpful, do give it a 👏 Clap!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8c07380954b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>