<?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 Puja Kumari on Medium]]></title>
        <description><![CDATA[Stories by Puja Kumari on Medium]]></description>
        <link>https://medium.com/@pjkri33?source=rss-d0e5a7ec930d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IEPmEx0E-exhfnTclvhVgQ.jpeg</url>
            <title>Stories by Puja Kumari on Medium</title>
            <link>https://medium.com/@pjkri33?source=rss-d0e5a7ec930d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 17:09:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pjkri33/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[Apache Kafka vs RabbitMQ: Understanding the Differences, Architecture, and Use Cases]]></title>
            <link>https://medium.com/@pjkri33/apache-kafka-vs-rabbitmq-understanding-the-differences-architecture-and-use-cases-6ea30299b3da?source=rss-d0e5a7ec930d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ea30299b3da</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Puja Kumari]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 17:57:16 GMT</pubDate>
            <atom:updated>2026-11-18T17:57:16.987Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical comparison of two popular messaging technologies, with examples, advantages, and guidance on when to use each.</h4><h3>Introduction</h3><p>In modern software development, applications often need to communicate with each other. For example, when a user places an order in an e-commerce application, multiple services may need to perform different tasks:</p><ul><li>Order Service creates the order.</li><li>Payment Service processes the payment.</li><li>Inventory Service updates stock.</li><li>Notification Service sends an email or SMS.</li></ul><p>If every service communicates directly with other services, the system becomes tightly coupled and difficult to maintain.</p><p>This is where <strong>message brokers and event streaming platforms</strong> like Apache Kafka and RabbitMQ become useful.</p><p>Both technologies enable asynchronous communication between services, but they work differently and solve different problems.</p><h3><strong>1. What is RabbitMQ?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rdvz9R4tyaSHatNn" /></figure><p><strong>RabbitMQ</strong> is an open-source message broker that enables applications to communicate through messages.</p><p>It follows a traditional messaging model where producers send messages to exchanges, and exchanges route messages to queues. Consumers receive messages from those queues and process them.</p><p><strong>How RabbitMQ works:</strong></p><ol><li>Producer sends a message.</li><li>Exchange receives the message.</li><li>Exchange routes it to the appropriate queue using routing rules.</li><li>Consumer receives the message.</li><li>After successful processing, the consumer acknowledges the message.</li></ol><p><strong>Example:</strong></p><p>Imagine an online shopping application.</p><p>When a customer places an order:</p><ul><li>Order Service publishes an order message.</li><li>RabbitMQ routes the message to the payment queue.</li><li>Payment Service processes the payment.</li><li>Once processing succeeds, the consumer acknowledges the message.</li></ul><h3>Key features of RabbitMQ</h3><ul><li>Message acknowledgment.</li><li>Flexible message routing.</li><li>Exchanges and queues.</li><li>Dead Letter Exchanges (DLX).</li><li>Message durability.</li><li>Retry mechanisms and publisher confirms.</li></ul><h3><strong>2. What is Apache Kafka?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*tvJHGQe4ipRQyh9V" /></figure><p><strong>Apache Kafka</strong> is a distributed event streaming platform designed to handle large volumes of events with high throughput and scalability.</p><p>Unlike traditional message brokers, Kafka stores messages in topics for a configurable retention period. Consumers can read those messages independently and can replay them when required.</p><p><strong>How Kafka works:</strong></p><ol><li>Producer publishes an event to a topic.</li><li>Kafka stores the event in a partition.</li><li>Consumers subscribe to the topic.</li><li>Consumers read events using offsets.</li><li>Events remain available according to the retention policy.</li></ol><p><strong>Example:</strong></p><p>Imagine a banking application.</p><p>Whenever a customer performs a transaction:</p><ul><li>Transaction Service publishes an event to Kafka.</li><li>Fraud Detection Service checks the transaction.</li><li>Analytics Service processes transaction data.</li><li>Notification Service sends an alert.</li></ul><p>Multiple consumer groups can independently process the same event.</p><h3>Key features of Kafka</h3><ul><li>High-throughput event processing.</li><li>Distributed architecture.</li><li>Topics and partitions.</li><li>Consumer groups.</li><li>Message retention and replay.</li><li>Replication and fault tolerance.</li></ul><h3>3. Apache Kafka vs RabbitMQ: Key Differences</h3><p>Although both technologies support asynchronous communication, they differ in their architecture, message handling, and use cases.</p><h4>1. Architecture</h4><ul><li><strong>RabbitMQ:</strong> Traditional message broker.</li><li><strong>Apache Kafka:</strong> Distributed event streaming platform.</li></ul><h4>2. Data Storage</h4><ul><li><strong>RabbitMQ:</strong> Stores messages in queues until they are consumed and acknowledged.</li><li><strong>Apache Kafka:</strong> Stores messages in topics divided into partitions.</li></ul><h4>3. Message Consumption</h4><ul><li><strong>RabbitMQ:</strong> Primarily uses push-based message delivery.</li><li><strong>Apache Kafka:</strong> Consumers pull messages from topics.</li></ul><h4>4. Message Deletion</h4><ul><li><strong>RabbitMQ:</strong> Messages are typically removed from queues after successful acknowledgment.</li><li><strong>Apache Kafka:</strong> Messages remain available according to the configured retention policy.</li></ul><h4>5. Message Replay</h4><ul><li><strong>RabbitMQ:</strong> Traditional queues do not provide built-in event replay in the same way as Kafka.</li><li><strong>Apache Kafka:</strong> Consumers can replay messages by resetting their offsets.</li></ul><h4>6. Message Routing</h4><ul><li><strong>RabbitMQ:</strong> Uses exchanges, routing keys, and bindings to route messages to queues.</li><li><strong>Apache Kafka:</strong> Producers publish messages to topics and can use partitioning strategies to determine where messages are stored.</li></ul><h4>7. Scalability</h4><ul><li><strong>RabbitMQ:</strong> Supports clustering and horizontal scaling.</li><li><strong>Apache Kafka:</strong> Uses distributed brokers and partitions to support large-scale event processing.</li></ul><h4>8. Message Ordering</h4><ul><li><strong>RabbitMQ:</strong> Message ordering depends on queue configuration, priorities, and consumer behavior.</li><li><strong>Apache Kafka:</strong> Guarantees message ordering within an individual partition.</li></ul><h4>9. Consumer Management</h4><ul><li><strong>RabbitMQ:</strong> Uses message acknowledgments to track successful processing.</li><li><strong>Apache Kafka:</strong> Uses consumer groups and offsets to manage message consumption.</li></ul><h4>10. Best Use Cases</h4><ul><li><strong>RabbitMQ:</strong> Background jobs, task queues, message routing, and asynchronous communication.</li><li><strong>Apache Kafka:</strong> Event streaming, real-time analytics, event-driven systems, and large-scale data processing.</li></ul><blockquote><strong>Note:</strong> Both technologies support durable messaging and different delivery guarantees. Actual performance depends on configuration, workload, and system architecture.</blockquote><h3>4. When Should You Use RabbitMQ?</h3><p>Choose RabbitMQ when your application requires:</p><ul><li>Background job processing.</li><li>Asynchronous communication between microservices.</li><li>Message routing based on specific conditions.</li><li>Retry mechanisms and dead-letter queues.</li><li>Task distribution among multiple workers.</li><li>Request-response messaging.</li></ul><blockquote><strong>Real-world example:</strong> In a telecom application, when a customer requests a phone number port, the system can publish a message to RabbitMQ. A background worker processes the porting request and communicates with the external vendor.</blockquote><p>This helps services process tasks asynchronously without blocking the main application.</p><h3>5. When Should You Use Apache Kafka?</h3><p>Choose Kafka when your application requires:</p><ul><li>High-volume event processing.</li><li>Real-time data streaming.</li><li>Event-driven architecture.</li><li>Multiple independent consumers.</li><li>Event replay and historical data processing.</li><li>Log aggregation and analytics.</li></ul><blockquote><strong>Real-world example:</strong> In a banking application, every financial transaction can be published to Kafka. Multiple services can independently consume the event for fraud detection, transaction analytics, auditing, and notifications.</blockquote><p>This allows multiple systems to process the same event without depending on each other.</p><h3>6. Can We Use Kafka and RabbitMQ Together?</h3><p>Yes! Both technologies can be used in the same microservices architecture.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*1U3q42shXa_9SmaP" /></figure><p>Consider an e-commerce application:</p><ul><li>Kafka captures order-created events.</li><li>Analytics Service consumes Kafka events.</li><li>RabbitMQ distributes payment-processing tasks.</li><li>Notification Service consumes messages from RabbitMQ.</li></ul><p>Kafka handles event streaming, while RabbitMQ handles background task distribution.</p><p>However, using both technologies increases infrastructure and maintenance complexity. Choose them based on actual requirements.</p><h3>7. Which One Should You Learn as a Java Developer?</h3><p>If you are a Java backend developer working with Spring Boot and microservices, understanding both technologies is valuable.</p><p>My recommended learning order:</p><ol><li><strong>RabbitMQ:</strong> Understand producers, consumers, exchanges, queues, acknowledgments, and dead-letter queues.</li><li><strong>Kafka:</strong> Understand producers, consumers, topics, partitions, offsets, and consumer groups.</li><li><strong>Spring Boot Integration:</strong> Learn Spring AMQP and Spring for Apache Kafka.</li><li><strong>Advanced Concepts:</strong> Learn retries, idempotency, message ordering, delivery guarantees, and error handling.</li></ol><h3>Conclusion</h3><p>Apache Kafka and RabbitMQ solve similar communication problems but are designed around different messaging models.</p><ul><li>RabbitMQ is a strong choice for message routing, background processing, and task queues.</li><li>Kafka is a strong choice for distributed event streaming, event replay, and large-scale data processing.</li></ul><p>There is no universal winner. The right choice depends on your application’s architecture, scalability requirements, and business needs.</p><blockquote><strong>Remember:</strong> RabbitMQ is primarily about distributing messages and tasks, while Kafka is primarily about storing and distributing event streams.</blockquote><h3>References and further reading</h3><ol><li><a href="https://kafka.apache.org/24/documentation.html?utm_source=chatgpt.com">Apache Kafka — Official Documentation</a>.</li><li><a href="https://www.rabbitmq.com/docs/compare/kafka?utm_source=chatgpt.com">RabbitMQ — Kafka Comparison</a>.</li><li><a href="https://aws.amazon.com/compare/the-difference-between-rabbitmq-and-kafka/?trk=faq_card&amp;utm_source=chatgpt.com">AWS — Difference Between RabbitMQ and Kafka</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ea30299b3da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Developer Interview Questions— Part 1]]></title>
            <link>https://medium.com/@pjkri33/java-developer-interview-questions-for-2-years-of-experience-part-1-dbcc208cd920?source=rss-d0e5a7ec930d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbcc208cd920</guid>
            <dc:creator><![CDATA[Puja Kumari]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 18:14:20 GMT</pubDate>
            <atom:updated>2026-09-28T18:15:13.194Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are preparing for a <strong>Java Developer interview with around 2 years of experience</strong>, you will often be asked questions that test both your <strong>Java fundamentals</strong> and your ability to apply them in real-world projects.</p><p>Interviewers may ask about collections, functional interfaces, SQL, Java versions, microservices, design patterns, and your own project experience.</p><p>In this article, I have covered some questions that can come up in Java Developer interviews, along with <strong>simple explanations, examples, and interview-friendly answers</strong>.</p><h3>1. Can a Functional Interface Extend Another Functional Interface?</h3><p>Yes, a functional interface can extend another functional interface, as long as the child interface still has <strong>only one abstract method</strong>.</p><h4>Real-World Example</h4><p>Imagine we are building a payment system.</p><p>We define a functional interface for processing payments:</p><pre>@FunctionalInterface<br>interface PaymentProcessor {<br>    void processPayment();<br>}</pre><p>Now, suppose we want a more specific interface for online payments. We can extend the existing functional interface:</p><pre>@FunctionalInterface<br>interface OnlinePaymentProcessor extends PaymentProcessor {<br>}</pre><p>This is valid because OnlinePaymentProcessor inherits the processPayment() method and still has only <strong>one abstract method</strong>.</p><p>We can use it with a lambda expression:</p><pre>OnlinePaymentProcessor processor = () -&gt; {<br>    System.out.println(&quot;Processing online payment&quot;);<br>};<br>processor.processPayment();</pre><p>Output:</p><pre>Processing online payment</pre><h4>What If We Add Another Abstract Method?</h4><p>Suppose we add another method to the child interface:</p><pre>interface OnlinePaymentProcessor extends PaymentProcessor {<br>    void validatePayment();<br>}</pre><p>Now the interface has two abstract methods:</p><pre>processPayment()<br>validatePayment()</pre><p>Therefore, it can no longer be a functional interface.</p><h3>Interview Answer</h3><blockquote>Yes, a functional interface can extend another functional interface, as long as the child interface still has only one abstract method. If we add another abstract method, it will no longer be a functional interface.</blockquote><h4>Key Takeaway</h4><p><em>A functional interface can extend another functional interface, but the </em><strong><em>one abstract method rule must be maintained</em></strong><em>.</em></p><h3>2. <strong>What is the difference between ArrayList and LinkedList?</strong></h3><p>ArrayList and LinkedList both implement the List interface in Java, but they use different data structures internally.</p><ul><li><em>ArrayList uses a </em><strong><em>dynamic array</em></strong><em>.</em></li><li><em>LinkedList uses a </em><strong><em>doubly linked list</em></strong><em>.</em></li></ul><p>The main difference becomes important when we consider how frequently we <strong>access, insert, or delete elements</strong>.</p><h4>ArrayList</h4><p>ArrayList stores elements in an array-like structure.</p><p>For example:</p><pre>List&lt;String&gt; users = new ArrayList&lt;&gt;();<br>users.add(&quot;Puja&quot;);<br>users.add(&quot;Riya&quot;);<br>users.add(&quot;Amit&quot;);<br>System.out.println(users.get(1));</pre><p>Here:</p><pre>users.get(1);</pre><p>can directly access the element at index 1.</p><p>Therefore, accessing an element by index in an ArrayList takes <strong>O(1)</strong> time.</p><h4>LinkedList</h4><p>LinkedList stores elements as nodes.</p><p>Each node contains the data and references to the previous and next nodes.</p><pre>List&lt;String&gt; users = new LinkedList&lt;&gt;();<br>users.add(&quot;Puja&quot;);<br>users.add(&quot;Rahul&quot;);<br>users.add(&quot;Amit&quot;);<br>System.out.println(users.get(1));</pre><p>When we access an element by index, Java may need to traverse the nodes to reach that position.</p><p>Therefore, accessing an element by index takes <strong>O(n)</strong> time.</p><h4>Real-World Example</h4><p>Imagine we are building an application that stores a list of customer records:</p><pre>Customer 1<br>Customer 2<br>Customer 3<br>Customer 4<br>...<br>Customer 1000</pre><p>Suppose the application frequently needs to access a customer using an index:</p><pre>customers.get(500);</pre><p>In this situation, ArrayList is generally a better choice because it provides fast random access.</p><p>Now imagine a different use case where we frequently add or remove elements from the beginning or end of a list.</p><p>For example, consider a queue-like operation:</p><pre>Customer A → Customer B → Customer C</pre><p>If we frequently add or remove elements from the ends, LinkedList can be considered because it supports efficient insertion and removal at its ends.</p><p>However, the actual choice should depend on the application’s access pattern.</p><h4>What About Insertion and Deletion?</h4><p>For an ArrayList, inserting or deleting an element in the middle can require shifting other elements.</p><p>For example:</p><pre>Before:<br>A  B  C  D<br>Insert X at index 1<br>A  X  B  C  D</pre><p>Elements B, C, and D may need to be shifted.</p><p>Therefore, insertion or deletion in the middle is generally <strong>O(n)</strong>.</p><p>With a LinkedList, once we reach the required node, insertion or deletion only requires changing the links between nodes.</p><p>So the link modification itself is <strong>O(1)</strong>, but finding the required position can take <strong>O(n)</strong>.</p><p>That’s why saying:</p><blockquote>LinkedList insertion is always O(1)</blockquote><p>is not completely correct.</p><h4>Interview Answer</h4><blockquote>Both ArrayList and LinkedList implement the List interface, but ArrayList uses a dynamic array, while LinkedList uses a doubly linked list. ArrayList provides fast random access, so getting an element by index takes O(1). In LinkedList, accessing an element by index takes O(n) because we may need to traverse the nodes. For insertion or deletion in the middle, ArrayList may need to shift elements, while LinkedList can change the node links once the required position is reached. So, I would generally use ArrayList when I need frequent random access and consider LinkedList when the application’s operations benefit from linked-list insertion or deletion.</blockquote><h3>Key Takeaway</h3><blockquote>ArrayList → fast random access</blockquote><blockquote>LinkedList → node-based structure</blockquote><p>The right choice depends on what operations your application performs most frequently.</p><h3>3. <strong>What is a wildcard in Java Generics?</strong></h3><p>A wildcard is represented by:</p><pre>?</pre><p>It is used when we don’t know the exact generic type.</p><p>For example:</p><pre>List&lt;?&gt; list;</pre><p>This means the list can contain elements of an unknown type.</p><p>There are three commonly used forms:</p><pre>?<br>? extends Type<br>? super Type</pre><h4>?</h4><pre>List&lt;?&gt; list;</pre><p>This represents a list of an unknown type.</p><h4>? extends</h4><pre>List&lt;? extends Number&gt;</pre><p>This means the list can contain Number or a subclass of Number, such as:</p><pre>List&lt;Integer&gt;<br>List&lt;Double&gt;<br>List&lt;Float&gt;</pre><p><em>This is commonly used when we mainly want to </em><strong><em>read</em></strong><em> values.</em></p><h4>? super</h4><pre>List&lt;? super Integer&gt;</pre><p>This means the list can be a list of Integer, Number, or Object.</p><p>It is useful when we want to <strong>add</strong> Integer values.</p><p>A useful rule to remember is:</p><blockquote><strong>PECS — Producer Extends, Consumer Super</strong></blockquote><ul><li>Producer → extends</li><li>Consumer → super</li></ul><h4>Real-World Example</h4><p>Let’s understand each one with a real-world example.</p><h4>? — Unknown Type</h4><p>Suppose we have a reporting system where we only need to print the data from a list. We don’t care what type of data the list contains.</p><pre>public void printData(List&lt;?&gt; data) {<br>    for (Object value : data) {<br>        System.out.println(value);<br>    }<br>}</pre><p>Now we can pass different types of lists:</p><pre>List&lt;String&gt; names = List.of(&quot;Puja&quot;, &quot;Rahul&quot;, &quot;Amit&quot;);<br>printData(names);</pre><pre>List&lt;Integer&gt; numbers = List.of(10, 20, 30);<br>printData(numbers);</pre><pre>List&lt;Double&gt; salaries = List.of(10.5, 20.5, 30.5);<br>printData(salaries);</pre><p>Here, ? means <strong>we don&#39;t know the exact type</strong>.</p><h4>? extends Type — Type or Its Subclasses</h4><p>Suppose our reporting system only needs to print numbers.</p><p>Instead of creating separate methods for:</p><pre>List&lt;Integer&gt;<br>List&lt;Double&gt;<br>List&lt;Float&gt;</pre><p>we can use:</p><pre>public void printNumbers(List&lt;? extends Number&gt; numbers) {<br>    for (Number number : numbers) {<br>        System.out.println(number);<br>    }<br>}</pre><p>Now the same method can accept:</p><pre>List&lt;Integer&gt; integers = List.of(10, 20, 30);<br>printNumbers(integers);</pre><pre>List&lt;Double&gt; doubles = List.of(10.5, 20.5, 30.5);<br>printNumbers(doubles);</pre><pre>List&lt;Float&gt; floats = List.of(10.5f, 20.5f, 30.5f);<br>printNumbers(floats);</pre><pre>List&lt;Long&gt; values = List.of(100L, 200L, 300L);<br>printNumbers(values);</pre><p>This works because Integer, Double, Float, and Long are subclasses of Number.</p><p>So:</p><pre>List&lt;? extends Number&gt;</pre><p>means:</p><blockquote>A list containing some unknown type that extends Number.</blockquote><p>With extends, we generally <strong>read values from the collection</strong> rather than add specific values to it.</p><h4>? super Type — Type or Its Parent Classes</h4><p>Now suppose our reporting system needs to add Integer values to a list.</p><p>We can use:</p><pre>public void addNumbers(List&lt;? super Integer&gt; numbers) {<br>    numbers.add(10);<br>    numbers.add(20);<br>    numbers.add(30);<br>}</pre><p>This method can accept:</p><pre>List&lt;Integer&gt; integers = new ArrayList&lt;&gt;();<br>addNumbers(integers);</pre><pre>List&lt;Number&gt; numbers = new ArrayList&lt;&gt;();<br>addNumbers(numbers);</pre><pre>List&lt;Object&gt; values = new ArrayList&lt;&gt;();<br>addNumbers(values);</pre><p>Why do all three work?</p><p>Because Integer can be assigned to:</p><pre>Integer<br>   ↓<br>Number<br>   ↓<br>Object</pre><p>Therefore:</p><pre>List&lt;? super Integer&gt;</pre><p>means:</p><blockquote>A list whose type is Integer or one of its parent types.</blockquote><p>With super, we can safely <strong>add </strong><strong>Integer values</strong> to the collection.</p><h3>Interview Answer</h3><blockquote>A wildcard represents an unknown generic type. extends is generally used when we read or produce values, while super is used when we consume or add values.</blockquote><h3>4. <strong>Write a program to find the second duplicate character in a string.</strong></h3><p>This is a common Java interview question.</p><p>Suppose we have:</p><pre>String str = &quot;programming&quot;;</pre><p>The characters that appear more than once are:</p><pre>r → 2 times<br>g → 2 times<br>m → 2 times</pre><p>So, the <strong>second duplicate character is </strong><strong>g</strong>.</p><p>There are two ways we can solve this in Java 8.</p><h4>Approach 1: Using LinkedHashMap</h4><p>This is a simple and traditional approach. It is <strong>Java 8 compatible</strong> and uses the Java 8 getOrDefault() method.</p><pre>String str = &quot;programming&quot;;<br>Map&lt;Character, Integer&gt; map = new LinkedHashMap&lt;&gt;();<br>for (char ch : str.toCharArray()) {<br>    map.put(ch, map.getOrDefault(ch, 0) + 1);<br>}<br>int duplicateCount = 0;<br>for (Map.Entry&lt;Character, Integer&gt; entry : map.entrySet()) {<br>    if (entry.getValue() &gt; 1) {<br>        duplicateCount++;<br>        if (duplicateCount == 2) {<br>            System.out.println(&quot;Second duplicate character: &quot;<br>                    + entry.getKey());<br>            break;<br>        }<br>    }<br>}</pre><h4>Approach 2: Using Java 8 Streams</h4><p>If the interviewer specifically asks:</p><blockquote>Can you solve it using Java 8 features?</blockquote><p>we can demonstrate the <strong>Stream API, lambda expressions, method references, and Collectors</strong>.</p><pre>String str = &quot;programming&quot;;<br>Character result = str.chars()<br>        .mapToObj(c -&gt; (char) c)<br>        .collect(Collectors.groupingBy(<br>                Function.identity(),<br>                LinkedHashMap::new,<br>                Collectors.counting()<br>        ))<br>        .entrySet()<br>        .stream()<br>        .filter(entry -&gt; entry.getValue() &gt; 1)<br>        .skip(1)<br>        .map(Map.Entry::getKey)<br>        .findFirst()<br>        .orElse(null);<br>System.out.println(&quot;Second duplicate character: &quot; + result);</pre><h4>How does the Java 8 version work?</h4><p>First:</p><pre>str.chars()</pre><p><em>converts the string into an </em><em>IntStream.</em></p><p>Then:</p><pre>.mapToObj(c -&gt; (char) c)</pre><p><em>converts each value into a </em><em>Character.</em></p><p>Next, we group the characters and count their occurrences:</p><pre>.collect(Collectors.groupingBy(<br>        Function.identity(),<br>        LinkedHashMap::new,<br>        Collectors.counting()<br>))</pre><p>The result is effectively:</p><pre>p → 1<br>r → 2<br>o → 1<br>g → 2<br>a → 1<br>m → 2<br>i → 1<br>n → 1</pre><p>Then:</p><pre>.filter(entry -&gt; entry.getValue() &gt; 1)</pre><p>keeps only duplicate characters:</p><pre>r → 2<br>g → 2<br>m → 2</pre><p>Next:</p><pre>.skip(1)</pre><p>skips the first duplicate, r.</p><p>Finally:</p><pre>.map(Map.Entry::getKey)<br>.findFirst()</pre><p><em>gets the next duplicate character, which is </em><em>g.</em></p><h4>Java 8 Features Used in Approach 2</h4><p>This solution demonstrates several Java 8 features:</p><ul><li><em>Stream API</em></li><li><em>Lambda expression → </em><em>c -&gt; (char) c</em></li><li><em>Method reference → </em><em>Map.Entry::getKey</em></li><li><em>Functional interface → </em><em>Function.identity()</em></li><li><em>Collectors</em></li><li><em>Optional → </em><em>findFirst().orElse(null)</em></li></ul><h3>Interview Answer</h3><p>If the interviewer asks you to solve it normally:</p><blockquote>I would use a LinkedHashMap to count the frequency of each character while maintaining insertion order. Then I would iterate through the map and find characters whose frequency is greater than one. When the duplicate counter reaches two, I return that character.</blockquote><p>If the interviewer specifically asks for Java 8:</p><blockquote>I can solve it using the Java 8 Stream API. I would convert the string into a character stream, group the characters using Collectors.groupingBy(), maintain their order using LinkedHashMap, filter the duplicate characters, skip the first duplicate, and get the second one using findFirst().</blockquote><h3>Key Takeaway</h3><p>Both solutions are valid Java 8 solutions, but there is an important difference:</p><pre>Traditional approach<br>        ↓<br>Java 8 compatible<br>        ↓<br>Uses getOrDefault()<br><br><br>Stream approach<br>        ↓<br>Demonstrates Java 8 features<br>        ↓<br>Streams + Lambda + Collectors + Method References</pre><p><em>So, if an interviewer specifically wants to </em><strong><em>see your Java 8 knowledge</em></strong><em>, the </em><strong><em>Stream API solution</em></strong><em> is the better version to demonstrate.</em></p><h3>5. <strong>How do you find the 10th minimum salary from an employee table?</strong></h3><p>Suppose we have:</p><pre>Employee<br>----------------<br>id<br>name<br>salary</pre><p>For MySQL, one simple approach is:</p><pre>SELECT salary<br>FROM Employee<br>ORDER BY salary ASC<br>LIMIT 1 OFFSET 9;</pre><p>Why OFFSET 9?</p><p>Because indexing starts from zero:</p><pre>OFFSET 0 → 1st<br>OFFSET 1 → 2nd<br>OFFSET 2 → 3rd<br>...<br>OFFSET 9 → 10th</pre><h4>What if Duplicate Salaries Exist?</h4><p>If we want the <strong>10th distinct salary</strong>, we can use:</p><pre>SELECT DISTINCT salary<br>FROM Employee<br>ORDER BY salary ASC<br>LIMIT 1 OFFSET 9;</pre><p>Another approach is using DENSE_RANK():</p><pre>SELECT salary<br>FROM (<br>    SELECT salary,<br>           DENSE_RANK() OVER (ORDER BY salary) AS rnk<br>    FROM Employee<br>) e<br>WHERE rnk = 10;</pre><h3>Interview Tip</h3><p>Before answering, clarify:</p><blockquote>Should duplicate salaries be counted separately, or are you asking for the 10th distinct minimum salary?</blockquote><p>This small clarification can change the SQL query.</p><h3>6. Explain a Story You Worked On and How You Resolved It</h3><p>The interviewer wants to understand how you approach a <strong>real development problem</strong>.</p><p>A simple structure is:</p><pre>Problem<br>   ↓<br>Investigation<br>   ↓<br>Root Cause<br>   ↓<br>Solution<br>   ↓<br>Testing<br>   ↓<br>Result</pre><h3>Example Answer</h3><blockquote>In one of my projects, we had an issue where a callback from an external system was not always being processed correctly. I first checked the application logs and traced the request flow to identify where the issue was occurring. During the investigation, I found that the callback validation was not handling one of the expected states correctly. I updated the validation logic to check the callback state and the required capability before processing the callback. I then added unit test cases using JUnit and Mockito to cover the different scenarios. After testing the change in the QA environment, we verified the callback flow again and monitored the application logs. This resolved the inconsistency and made the callback processing more reliable.</blockquote><h3>Why This Type of Answer Works</h3><p>It shows that you can:</p><ul><li>Debug an issue</li><li>Read application logs</li><li>Find the root cause</li><li>Modify existing code</li><li>Write unit tests</li><li>Validate your fix</li><li>Understand the impact of your change</li></ul><blockquote>Instead of saying: I fixed a bug. Explain <strong>how you found and fixed it</strong>.</blockquote><h3>7. Java 21 vs Java 25</h3><p>Java 21 and Java 25 are both <strong>Long-Term Support (LTS)</strong> releases.</p><p>Java 21 introduced several important features, including:</p><ul><li>Virtual Threads</li><li>Record Patterns</li><li>Pattern Matching for switch</li><li>Sequenced Collections</li><li>Generational ZGC</li></ul><p><em>Java 25 is a newer LTS release that builds on the improvements introduced in the Java releases after Java 21. It includes further enhancements to the </em><strong><em>language, JVM, libraries, garbage collection, and performance</em></strong><em>.</em></p><h4>What If a Project Uses Java 21?</h4><p>If a project currently runs on Java 21 and we want to upgrade to Java 25, I would not just change:</p><pre>&lt;java.version&gt;21&lt;/java.version&gt;</pre><p>to:</p><pre>&lt;java.version&gt;25&lt;/java.version&gt;</pre><p>I would first verify:</p><ul><li><em>Spring Boot compatibility</em></li><li><em>Third-party dependencies</em></li><li><em>Maven or Gradle compatibility</em></li><li><em>Docker images</em></li><li><em>CI/CD pipelines</em></li><li><em>Testing frameworks</em></li><li><em>Production environment compatibility</em></li></ul><p>Then I would run unit, integration, and regression tests before deploying.</p><blockquote>Java 21 and Java 25 are both LTS releases. Java 21 introduced features such as Virtual Threads, Record Patterns, Pattern Matching for switch, Sequenced Collections, and Generational ZGC. Java 25 builds on the improvements delivered after Java 21 with further language, JVM, library, and performance enhancements. If upgrading a project from Java 21 to Java 25, I would also verify framework and dependency compatibility and run the complete test suite.</blockquote><h4>Key Point</h4><p>A Java upgrade is not just changing the version number. In a real application, you need to validate the <strong>complete application ecosystem</strong> before moving to a newer Java version.</p><h3>8. Which Design Patterns Are Commonly Used in Microservices?</h3><p>This is a common question in Java and Spring Boot microservices interviews.</p><p>When working with multiple independent services, we need patterns to handle <strong>communication, failures, distributed transactions, and service decoupling</strong>.</p><p>Some commonly discussed microservice patterns are <strong>API Gateway, Circuit Breaker, Retry, Saga, and Event-Driven Architecture</strong>.</p><h4>1. API Gateway</h4><p>Instead of allowing clients to communicate directly with multiple services, we can place an <strong>API Gateway</strong> in front of them.</p><pre>Client<br>   |<br>   v<br>API Gateway<br>   |<br>   +----&gt; User Service<br>   |<br>   +----&gt; Order Service<br>   |<br>   +----&gt; Payment Service</pre><p>The API Gateway can handle common concerns such as:</p><ul><li>Request routing</li><li>Authentication</li><li>Authorization</li><li>Rate limiting</li><li>Request filtering</li></ul><blockquote>API Gateway provides a single entry point for clients and can handle cross-cutting concerns such as routing, authentication, and rate limiting.</blockquote><h4>2. Circuit Breaker</h4><p>A Circuit Breaker helps prevent continuous calls to a service that is currently failing or unavailable.</p><pre>Order Service<br>      |<br>      v<br>Payment Service<br>      X<br>    Failure</pre><p>If the Payment Service repeatedly fails, the circuit can <strong>open</strong> and temporarily stop further requests.</p><p>Once the service becomes healthy again, the circuit can allow requests to flow normally.</p><blockquote>Circuit Breaker prevents repeated calls to an unhealthy service and helps prevent cascading failures.</blockquote><h4>3. Retry Pattern</h4><p>Sometimes a request fails because of a temporary problem, such as a network timeout.</p><p>In such cases, we can retry the request.</p><pre>Service A<br>   |<br>   X<br>   |<br> Retry<br>   |<br>   v<br>Service B</pre><p>However, retries should be configured carefully.</p><p>For example, retrying a payment request without considering <strong>idempotency</strong> could potentially result in duplicate processing.</p><blockquote>Retry is useful for temporary failures, but it should be configured carefully with limits and appropriate backoff, especially for operations that can have duplicate side effects.</blockquote><h4>4. Saga Pattern</h4><p>A Saga is used when a business operation involves multiple microservices and we need to maintain consistency across those services.</p><p>For example:</p><pre>Order<br>  ↓<br>Payment<br>  ↓<br>Inventory<br>  ↓<br>Shipping</pre><p>There is no single database transaction covering all these services.</p><p>If a later operation fails, the Saga can trigger <strong>compensating actions</strong> for previously completed operations.</p><p>For example:</p><pre>Create Order<br>     ↓<br>Payment Successful<br>     ↓<br>Inventory Failed<br>     ↓<br>Refund Payment<br>     ↓<br>Cancel Order</pre><blockquote>Saga is used to manage distributed business transactions across multiple services by using a sequence of local transactions and compensating actions when something fails.</blockquote><h4>5. Event-Driven Architecture</h4><p>In an event-driven architecture, services communicate by publishing and consuming events through a messaging system such as <strong>RabbitMQ or Kafka</strong>.</p><p>For example:</p><pre>Order Service<br>      |<br>      v<br>Order Created Event<br>      |<br>      v<br>   RabbitMQ<br>    /    \<br>   /      \<br>Payment  Inventory</pre><p>The Order Service doesn’t necessarily need to directly call both Payment and Inventory services.</p><p>This can reduce <strong>tight coupling</strong> between services and support asynchronous processing.</p><blockquote>In event-driven architecture, services communicate through events using a messaging system such as RabbitMQ or Kafka. This helps reduce direct coupling and supports asynchronous communication.</blockquote><h4>You can answer:</h4><blockquote>Some commonly used microservice patterns are API Gateway, Circuit Breaker, Retry, Saga, and Event-Driven Architecture. API Gateway provides a single entry point for clients, Circuit Breaker helps handle service failures, Retry handles temporary failures, Saga manages distributed business transactions, and Event-Driven Architecture enables loosely coupled asynchronous communication using systems like RabbitMQ or Kafka. The pattern depends on the specific problem we are trying to solve.</blockquote><h3>9. Which Design Patterns Have You Used?</h3><p>This is a common follow-up after discussing microservices and design patterns.</p><p>The important thing is <strong>not to list every design pattern you know</strong>. Instead, mention patterns or concepts that you have actually worked with and can explain with a practical example.</p><h4>1. Dependency Injection</h4><p>In my Spring Boot project, <strong>Dependency Injection</strong> is something I use regularly.</p><p>Instead of a class creating its own dependencies, Spring manages and injects them.</p><p>For example:</p><pre>@Service<br>public class OrderService {<br>    private final PaymentService paymentService;<br>    public OrderService(PaymentService paymentService) {<br>        this.paymentService = paymentService;<br>    }<br>}</pre><p>Here, OrderService does not create PaymentService using new. Spring provides the required dependency.</p><p><strong>Why is it useful?</strong></p><ul><li>Reduces tight coupling</li><li>Makes components easier to test</li><li>Improves maintainability</li></ul><h4>2. Strategy Pattern</h4><p>The Strategy Pattern is useful when we have <strong>multiple implementations of the same behavior</strong> and want to select one based on the situation.</p><p>For example, suppose an application supports different payment methods:</p><pre>interface PaymentStrategy {<br>    void pay();<br>}</pre><p>Then we can have different implementations:</p><pre>class CardPayment implements PaymentStrategy {<br>    public void pay() {<br>        System.out.println(&quot;Card payment&quot;);<br>    }<br>}</pre><pre>class UpiPayment implements PaymentStrategy {<br>    public void pay() {<br>        System.out.println(&quot;UPI payment&quot;);<br>    }<br>}</pre><p>The application can select the appropriate implementation based on the payment method.</p><pre>Payment Service<br>      |<br>      v<br>PaymentStrategy<br>   /       \<br>Card       UPI</pre><p>The main benefit is that we can add another payment strategy without putting all the logic into one large if-else block.</p><h4>3. Factory Pattern</h4><p>A Factory can be useful when object creation depends on some input.</p><p>For example:</p><pre>Payment Type<br>     |<br>     v<br> PaymentFactory<br>   /       \<br>Card       UPI</pre><p>Instead of the client directly deciding which implementation to instantiate, the Factory can handle that decision.</p><p>The main purpose is to <strong>centralize object creation</strong> and keep the calling code cleaner.</p><h4>4. Event-Driven Communication</h4><p>In my microservices experience, I have also worked with <strong>event-driven communication using RabbitMQ</strong>.</p><p>For example:</p><pre>Order Service<br>      |<br>      v<br>Order Created Event<br>      |<br>      v<br>   RabbitMQ<br>    /    \<br>   /      \<br>Service A  Service B</pre><p>Instead of one service making synchronous calls to multiple services, an event can be published to RabbitMQ and consumed by the required services.</p><p>This helps with <strong>asynchronous processing and reducing direct coupling</strong> between services.</p><blockquote>In my Spring Boot projects, Dependency Injection is something I use regularly because Spring manages the dependencies between components. I am also familiar with patterns such as Strategy and Factory. Strategy is useful when we have multiple implementations of the same behavior and need to select one dynamically, while Factory is useful for centralizing object creation. In my microservices project, I have also worked with event-driven communication using RabbitMQ for asynchronous processing. I prefer explaining the pattern based on the problem it solves rather than simply listing pattern names.</blockquote><h3>10. What Is a Stored Procedure?</h3><p>A stored procedure is a group of SQL statements that is stored and executed inside the database.</p><p>For example:</p><pre>CREATE PROCEDURE GetEmployeeById(IN empId INT)<br>BEGIN<br>    SELECT *<br>    FROM Employee<br>    WHERE id = empId;<br>END;</pre><p>We can execute it using:</p><pre>CALL GetEmployeeById(101);</pre><h4>Why use Stored Procedures?</h4><ul><li>Reuse SQL logic</li><li>Reduce repeated queries</li><li>Perform multiple database operations together</li><li>Accept input parameters</li><li>Can improve security by controlling direct table access</li></ul><blockquote>A stored procedure is a precompiled or stored set of SQL statements maintained in the database. It can accept parameters and perform operations such as fetching, inserting, updating, or deleting data. It is useful when we want to reuse database logic or execute multiple SQL operations together.</blockquote><h3>Final Thoughts</h3><p>For a Java Developer with around <strong>2 years of experience</strong>, interview preparation shouldn’t be limited to memorizing definitions.</p><p>Try to connect every concept with a practical situation.</p><p>For example:</p><pre>Java Concept<br>     ↓<br>Why is it needed?<br>     ↓<br>Where have I seen it?<br>     ↓<br>What problem does it solve?<br>     ↓<br>Can I explain it with an example?</pre><p>If you can explain a concept in <strong>simple words + code + a real-world example</strong>, you are much better prepared for follow-up questions.</p><p>The most important thing is to be honest about your experience. If you have only worked with a concept at a basic level, say that clearly and explain what you understand instead of pretending to have designed the entire system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbcc208cd920" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorting in Java: Understanding the Basics and Built-in Sorting]]></title>
            <link>https://medium.com/@pjkri33/sorting-in-java-understanding-the-basics-and-built-in-sorting-490984e4b2b3?source=rss-d0e5a7ec930d------2</link>
            <guid isPermaLink="false">https://medium.com/p/490984e4b2b3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Puja Kumari]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 17:27:13 GMT</pubDate>
            <atom:updated>2026-09-23T17:27:13.291Z</atom:updated>
            <content:encoded><![CDATA[<p>Sorting is one of the most common operations in programming.</p><p>Whether we are working with numbers, strings, employees, products, transactions, or database results, we often need to arrange data in a particular order.</p><p>For example:</p><pre>Before sorting:<br>[5, 2, 8, 1, 3]<br><br>After sorting:<br>[1, 2, 3, 5, 8]</pre><p>At first, sorting looks simple. But understanding <strong>how sorting works</strong>, <strong>which algorithm to use</strong>, and <strong>how Java performs sorting internally</strong> becomes important as the amount of data grows.</p><p>In this article, let’s understand sorting step by step, starting with basic sorting algorithms and then looking at Java’s built-in sorting capabilities.</p><h3>What Is Sorting?</h3><p>Sorting means arranging a collection of elements according to a specific order.</p><p>The order can be:</p><ul><li>Ascending</li><li>Descending</li><li>Alphabetical</li><li>Based on a particular object property</li></ul><p>For example:</p><pre>Ascending:<br>1 2 3 4 5<br><br>Descending:<br>5 4 3 2 1</pre><p>For objects, we can sort based on properties such as:</p><pre>Employee → salary<br>Student  → marks<br>Product  → price<br>Order    → orderDate</pre><h3>1. Bubble Sort</h3><p>Bubble Sort repeatedly compares adjacent elements and swaps them when they are in the wrong order.</p><p>Consider:</p><pre>[5, 2, 8, 1]</pre><p>First comparison:</p><pre>5 &gt; 2</pre><p>Swap them:</p><pre>[2, 5, 8, 1]</pre><p>Next:</p><pre>5 &lt; 8</pre><p>No swap.</p><p>Then:</p><pre>8 &gt; 1</pre><p>Swap:</p><pre>[2, 5, 1, 8]</pre><p>After multiple passes, the array becomes sorted.</p><h3>Java Implementation</h3><pre>public static void bubbleSort(int[] numbers) {<br>    for (int i = 0; i &lt; numbers.length - 1; i++) {<br>        for (int j = 0; j &lt; numbers.length - i - 1; j++) {<br>            if (numbers[j] &gt; numbers[j + 1]) {<br>                int temp = numbers[j];<br>                numbers[j] = numbers[j + 1];<br>                numbers[j + 1] = temp;<br>            }<br>        }<br>    }<br>}</pre><h3>Complexity</h3><pre>Best Case:    O(n)<br>Average Case: O(n²)<br>Worst Case:   O(n²)<br>Space:        O(1)</pre><p>Bubble Sort is easy to understand, but it is generally not suitable for large datasets.</p><h3>2. Selection Sort</h3><p>Selection Sort works by repeatedly finding the smallest element from the unsorted portion and placing it at the correct position.</p><p>For example:</p><pre>[5, 2, 8, 1, 3]</pre><p>The smallest element is:</p><pre>1</pre><p>Move it to the beginning:</p><pre>[1, 2, 8, 5, 3]</pre><p>Then find the smallest element from the remaining portion and continue.</p><h3>Java Implementation</h3><pre>public static void selectionSort(int[] numbers) {<br>    for (int i = 0; i &lt; numbers.length - 1; i++) {<br>        int minIndex = i;<br>        for (int j = i + 1; j &lt; numbers.length; j++) {<br>            if (numbers[j] &lt; numbers[minIndex]) {<br>                minIndex = j;<br>            }<br>        }<br>        <br>        if(i != minIndex) {<br>            int temp = numbers[i];<br>            numbers[i] = numbers[minIndex];<br>            numbers[minIndex] = temp;<br>        }<br>    }<br>}</pre><h3>Complexity</h3><pre>Best Case:    O(n²)<br>Average Case: O(n²)<br>Worst Case:   O(n²)<br>Space:        O(1)</pre><h3>3. Insertion Sort</h3><p>Insertion Sort works similarly to how we might arrange playing cards in our hand.</p><p>Suppose we have:</p><pre>[5, 2, 8, 1]</pre><p>We consider 5 sorted initially.</p><p>Then we take 2 and place it before 5:</p><pre>[2, 5, 8, 1]</pre><p>Next, 8 is already in the correct position:</p><pre>[2, 5, 8, 1]</pre><p>Finally, 1 is inserted at the beginning:</p><pre>[1, 2, 5, 8]</pre><h3>Java Implementation</h3><pre>public static void insertionSort(int[] numbers) {<br>    for (int i = 1; i &lt; numbers.length; i++) {<br>        int current = numbers[i];<br>        int j = i - 1;<br>        while (j &gt;= 0 &amp;&amp; numbers[j] &gt; current) {<br>            numbers[j + 1] = numbers[j];<br>            j--;<br>        }<br>        numbers[j + 1] = current;<br>    }<br>}</pre><h3>Complexity</h3><pre>Best Case:    O(n)<br>Average Case: O(n²)<br>Worst Case:   O(n²)<br>Space:        O(1)</pre><p>Insertion Sort can perform well when the data is already nearly sorted.</p><h3>4. Merge Sort</h3><p>Merge Sort uses the <strong>divide-and-conquer</strong> approach.</p><p>Instead of sorting the entire array at once, it divides the array into smaller parts.</p><p>For example:</p><pre> [8, 3, 5, 1]<br>       ↓<br>[8, 3]    [5, 1]<br>   ↓          ↓<br>[8] [3]    [5] [1]</pre><p>Then the smaller arrays are merged in sorted order:</p><pre>[3, 8]    [1, 5]<br>        ↓<br>   [1, 3, 5, 8]</pre><h3>Java Implementation</h3><pre>public static void insertionSort(int[] numbers) {<br>    for (int i = 1; i &lt; numbers.length; i++) {<br>        int current = numbers[i];<br>        int j = i - 1;<br>        while (j &gt;= 0 &amp;&amp; numbers[j] &gt; current) {<br>            numbers[j + 1] = numbers[j];<br>            j--;<br>        }<br>        numbers[j + 1] = current;<br>    }<br>}<br><br><br><br>public static void mergeSort(int[] nums) {<br>    if(nums.length == 1) return;<br>    int[] left = new int[nums.length / 2];<br>    int[] right = new int[nums.length - left.length];<br>    for(int i = 0; i &lt; left.length; i++) left[i] = nums[i];<br>    for(int i = 0; i &lt; right.length; i++) right[i] = nums[left.length + i];<br>    <br>    mergeSort(left);<br>    mergeSort(right);<br>    merge(nums, left, right);<br>}<br>public static void merge(int[] nums, int[] arr1, int[] arr2) {<br>    int i = 0;<br>    int j = 0;<br>    int k = 0;<br>    while(i &lt; arr1.length &amp;&amp; j &lt; arr2.length) {<br>        if(arr1[i] &lt; arr2[j]) {<br>            nums[k++] = arr1[i++];<br>        } else {<br>            nums[k++] = arr2[j++];<br>        }<br>    }<br>    while(i &lt; arr1.length) {<br>        nums[k++] = arr1[i++];<br>    }<br>    while(j &lt; arr2.length) {<br>        nums[k++] = arr2[j++];<br>    }<br>}</pre><p>Its time complexity is:</p><pre>O(n log n)</pre><p>which makes it much more efficient than quadratic sorting algorithms for large datasets.</p><h3>5. Quick Sort</h3><p>Quick Sort is another divide-and-conquer algorithm.</p><p>It selects an element as a <strong>pivot</strong> and rearranges the array so that:</p><pre>Elements smaller than pivot<br>        ↓<br>      Pivot<br>        ↓<br>Elements greater than pivot</pre><p>The same process is then applied recursively to the smaller portions.</p><h3>Java Implementation</h3><pre>public static void quickSort(int[] nums) {<br>    quickSort(nums, 0, nums.length - 1);<br>}<br><br>public int[] quickSort(int[] nums, int start, int end) {<br><br>    if (start &gt;= end) {<br>        return;<br>    }<br><br>    int i = start;<br>    int j = end;<br><br>    int pivot = nums[(start + end) / 2];<br><br>    while (i &lt;= j) {<br><br>        while (nums[i] &lt; pivot) {<br>            i++;<br>        }<br><br>        while (nums[j] &gt; pivot) {<br>            j--;<br>        }<br><br>        if (i &lt;= j) {<br>            int temp = nums[i];<br>            nums[i] = nums[j];<br>            nums[j] = temp;<br><br>            i++;<br>            j--;<br>        }<br>     }<br><br>     quickSort(nums, start, j);<br>     quickSort(nums, i, end);<br><br>}</pre><p>Its average time complexity is:</p><pre>O(n log n)</pre><p>However, depending on pivot selection and input distribution, its worst-case complexity can become:</p><pre>O(n²)</pre><h3>Sorting in Real Java Applications</h3><p>In real-world Java applications, we usually don’t implement Bubble Sort or Selection Sort ourselves.</p><p>Java provides built-in sorting functionality.</p><p>For arrays:</p><pre>int[] numbers = {5, 2, 8, 1, 3};<br>Arrays.sort(numbers);<br>System.out.println(Arrays.toString(numbers));</pre><p>Output:</p><pre>[1, 2, 3, 5, 8]</pre><p>For collections:</p><pre>List&lt;Integer&gt; numbers = Arrays.asList(5, 2, 8, 1, 3);<br>Collections.sort(numbers);</pre><p>Modern Java code can also use:</p><pre>numbers.sort(Comparator.naturalOrder());</pre><h3>Sorting Objects in Java</h3><p>Sorting becomes more interesting when we work with objects.</p><p>Suppose we have:</p><pre>class Employee {<br>    private String name;<br>    private int salary;<br>    // constructor, getters and setters<br>}</pre><p>If we want to sort employees by salary, we can use a Comparator.</p><pre>employees.sort(<br>    Comparator.comparing(Employee::getSalary)<br>);</pre><p>For descending order:</p><pre>employees.sort(<br>    Comparator.comparing(Employee::getSalary).reversed()<br>);</pre><p>This is something we commonly encounter in Java backend applications.</p><p>For example, we might need to sort:</p><pre>Employees by salary<br>Products by price<br>Orders by date<br>Users by registration date<br>Transactions by amount</pre><h3>Comparable vs Comparator</h3><p>One of the common Java interview questions is:</p><p><strong>What is the difference between Comparable and Comparator?</strong></p><h3>Comparable</h3><p>Comparable is used when a class has a <strong>natural ordering</strong>.</p><pre>class Employee implements Comparable&lt;Employee&gt; {<br>    private int salary;<br>    @Override<br>    public int compareTo(Employee other) {<br>        return Integer.compare(this.salary, other.salary);<br>    }<br>}</pre><p>Now employees have a default sorting order based on salary.</p><h3>Comparator</h3><p>Comparator is useful when we want to define <strong>custom sorting logic</strong>.</p><pre>employees.sort(<br>    Comparator.comparing(Employee::getSalary)<br>);</pre><p>We can create different comparators for different requirements without changing the Employee class.</p><h3>What Should You Use in Java?</h3><p>The answer depends on the situation.</p><p>For learning DSA, understanding algorithms such as:</p><pre>Bubble Sort<br>Selection Sort<br>Insertion Sort<br>Merge Sort<br>Quick Sort</pre><p>is useful.</p><p>But in production Java applications, we generally use Java’s built-in sorting APIs rather than manually implementing a sorting algorithm.</p><p>For example:</p><pre>Arrays.sort(numbers);</pre><p>or:</p><pre>employees.sort(<br>    Comparator.comparing(Employee::getSalary)<br>);</pre><p>The important part is not just knowing how to sort.</p><p>A good Java developer should also understand <strong>what is being sorted, what ordering is required, and the complexity involved</strong>.</p><h3>Final Thoughts</h3><p>Sorting is a simple concept, but it appears everywhere in software development.</p><p>From basic DSA problems to real-world backend applications, we frequently need to arrange data efficiently.</p><p>The main concepts to remember are:</p><ul><li><em>Bubble, Selection, and Insertion Sort are simple but generally have </em><em>O(n²) average/worst-case complexity.</em></li><li><em>Merge Sort uses divide and conquer and provides </em><em>O(n log n) time complexity.</em></li><li><em>Quick Sort has </em><em>O(n log n) average-case complexity but can have </em><em>O(n²) worst-case complexity.</em></li><li><em>Java provides built-in sorting APIs.</em></li><li><em>Comparable defines natural ordering.</em></li><li><em>Comparator allows custom ordering.</em></li></ul><p>Once these concepts are clear, sorting objects and collections in Java becomes much easier to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=490984e4b2b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HashMap in Java Explained Simply]]></title>
            <link>https://medium.com/@pjkri33/hashmap-in-java-explained-simply-6581aacee7d9?source=rss-d0e5a7ec930d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6581aacee7d9</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[hashmap]]></category>
            <dc:creator><![CDATA[Puja Kumari]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 18:21:04 GMT</pubDate>
            <atom:updated>2026-09-22T18:21:04.366Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding HashMap is one of the most common topics in Java.</p><p>It is one of the most commonly used classes when we need to store data in <strong>key-value pairs</strong>.</p><p>For example:</p><pre>Map&lt;String, Integer&gt; marks = new HashMap&lt;&gt;();<br>marks.put(&quot;Java&quot;, 90);<br>marks.put(&quot;Spring Boot&quot;, 85);<br>marks.put(&quot;SQL&quot;, 80);</pre><p>Using a HashMap is easy.</p><p>But what actually happens internally when we write:</p><pre>marks.put(&quot;Java&quot;, 90);</pre><p>How does Java decide where to store &quot;Java&quot;?</p><p>And when we write:</p><pre>marks.get(&quot;Java&quot;);</pre><p>How does Java find the value so quickly?</p><p>What happens when two different keys end up in the same location?</p><p>To answer these questions, let’s understand how HashMap works internally.</p><h3>What Is a HashMap?</h3><p>HashMap is a class in Java that stores data in the form of <strong>key-value pairs</strong>.</p><pre>HashMap&lt;Key, Value&gt;</pre><p>For example:</p><pre>HashMap&lt;Integer, String&gt; employees = new HashMap&lt;&gt;();<br>employees.put(101, &quot;Riya&quot;);<br>employees.put(102, &quot;Priya&quot;);<br>employees.put(103, &quot;Amit&quot;);</pre><p>Here:</p><pre>101 → Riya<br>102 → Priya<br>103 → Amit</pre><p>Each key is associated with one value.</p><p>A HashMap allows:</p><ul><li>One null key</li><li>Multiple null values</li><li>Duplicate values</li><li>Unique keys</li></ul><p>If we insert the same key again:</p><pre>employees.put(101, &quot;Neha&quot;);</pre><p>The previous value &quot;Riya&quot; is replaced.</p><p>Now:</p><pre>101 → Neha<br>102 → Priya<br>103 → Amit</pre><h3>What Does HashMap Use Internally?</h3><p>At a high level, HashMap uses an <strong>array of buckets</strong>.</p><p>Each bucket can contain one or more entries.</p><p>A simplified view looks like this:</p><pre>HashMap<br>   |<br>   ↓<br>Internal Array<br>   |<br>   +---- Bucket 0<br>   |<br>   +---- Bucket 1<br>   |<br>   +---- Bucket 2<br>   |<br>   +---- Bucket 3<br>   |<br>   +---- Bucket 4<br>   |<br>   +---- ...</pre><p>When we add a key-value pair, Java calculates a hash for the key.</p><p>That hash is then used to determine which bucket should contain the entry.</p><p>So the basic idea is:</p><pre>Key<br> ↓<br>hashCode()<br> ↓<br>Hash<br> ↓<br>Bucket Index<br> ↓<br>Store Entry</pre><p>Let’s understand each step.</p><h3>What Happens When We Call put()?</h3><p>Consider:</p><pre>Map&lt;String, Integer&gt; marks = new HashMap&lt;&gt;();<br>marks.put(&quot;Java&quot;, 90);</pre><p>When put() is called, Java roughly performs the following steps:</p><pre>&quot;Java&quot;<br>   ↓<br>hashCode()<br>   ↓<br>Hash calculation<br>   ↓<br>Bucket index calculation<br>   ↓<br>Check bucket<br>   ↓<br>Store key-value pair</pre><p>Let’s break this down.</p><h3>Step 1: Java Calculates the Hash</h3><p>Every Java object has a hashCode() method inherited from Object.</p><p>For example:</p><pre>String key = &quot;Java&quot;;<br>int hash = key.hashCode();</pre><p>The returned integer is used by HashMap as part of the process of finding the bucket.</p><p>Conceptually:</p><pre>&quot;Java&quot;<br>   ↓<br>hashCode()<br>   ↓<br>some integer hash</pre><p>The important thing to understand is that the hash helps HashMap quickly determine where the entry should be stored.</p><h3>Step 2: HashMap Finds the Bucket</h3><p>The hash itself is not used directly as an array index.</p><p>HashMap calculates an index from the hash and the current table size.</p><p>Conceptually:</p><pre>hash<br> ↓<br>bucket index<br> ↓<br>internal array[index]</pre><p>In modern Java implementations, the calculation is optimized around the fact that the table size is a power of two.</p><p>You may see code similar to:</p><pre>index = (n - 1) &amp; hash;</pre><p>where n represents the table length.</p><p>You don’t need to memorize the formula to understand the main idea.</p><p>The important point is:</p><blockquote>The hash is used to determine which bucket should be checked.</blockquote><h3>What Is a Bucket?</h3><p>A bucket is simply a position in the internal array where a HashMap entry can be stored.</p><p>For example:</p><pre>Index<br><br>0<br>1<br>2  → [Java, 90]<br>3<br>4<br>5</pre><p>If the calculated bucket index for &quot;Java&quot; is 2, the entry is stored at bucket 2.</p><p>Internally, the entry contains information such as:</p><pre>hash<br>key<br>value<br>next</pre><p>A simplified representation is:</p><pre>+----------------+<br>| hash           |<br>| key            |<br>| value          |<br>| next           |<br>+----------------+</pre><p>In Java’s implementation, this is represented by internal node structures.</p><h3>But What If Two Keys Get the Same Bucket?</h3><p>This is where things become interesting.</p><p>Suppose we have two different keys:</p><pre>Key A<br>Key B</pre><p>After hashing and bucket calculation, both happen to point to the same bucket.</p><p>This is called a <strong>hash collision</strong>.</p><p>For example:</p><pre>Bucket 5<br>       ↓<br>[Key A, Value A]<br>       |<br>       ↓<br>[Key B, Value B]</pre><p>Different keys can have the same bucket.</p><p>This is completely normal.</p><p>So how does HashMap handle it?</p><h3>How Does HashMap Handle Collisions?</h3><p>Historically, collisions are handled using a linked structure.</p><p>A simplified representation looks like this:</p><pre>Bucket 5<br>   |<br>   ↓<br>[Key A | Value A | next]<br>                    |<br>                    ↓<br>             [Key B | Value B | next]<br>                                  |<br>                                  ↓<br>                           [Key C | Value C]</pre><p>When multiple entries belong to the same bucket, they can be connected together.</p><p>This allows the HashMap to search through the entries in that bucket.</p><p>But there is a problem.</p><p>What if a bucket contains a very large number of entries?</p><p>Searching through a long linked list can become slower.</p><p>This is where Java’s treeification feature becomes important.</p><h3>HashMap and Red-Black Trees</h3><p>In Java 8 and later, when a bucket becomes sufficiently large, the linked structure can be converted into a <strong>Red-Black Tree</strong>.</p><p>Instead of:</p><pre>Entry<br>  ↓<br>Entry<br>  ↓<br>Entry<br>  ↓<br>Entry</pre><p>it can become a tree-like structure:</p><pre>             Entry<br>            /     \<br>        Entry     Entry<br>        /           \<br>     Entry          Entry</pre><p>This can improve lookup performance when many entries collide into the same bucket.</p><p>However, treeification does not happen immediately after a few collisions.</p><p>Java uses specific thresholds and conditions before converting a bucket into a tree.</p><p>The commonly referenced constants in modern OpenJDK implementations include:</p><pre>TREEIFY_THRESHOLD = 8<br>UNTREEIFY_THRESHOLD = 6<br>MIN_TREEIFY_CAPACITY = 64</pre><p>These are implementation details and can vary across Java versions, so the important concept is:</p><blockquote>A heavily populated bucket can be converted from a linked structure into a tree to improve lookup performance.</blockquote><h3>What Happens When We Call get()?</h3><p>Now let’s look at the other common operation:</p><pre>marks.get(&quot;Java&quot;);</pre><p>How does Java find 90?</p><p>The process is roughly:</p><pre>&quot;Java&quot;<br>   ↓<br>hashCode()<br>   ↓<br>Hash calculation<br>   ↓<br>Find bucket index<br>   ↓<br>Go to bucket<br>   ↓<br>Compare entries<br>   ↓<br>Find &quot;Java&quot;<br>   ↓<br>Return 90</pre><p>Suppose the bucket contains:</p><pre>Bucket 3<br><br>[Python, 70]<br>      ↓<br>[Java, 90]<br>      ↓<br>[SQL, 80]</pre><p>When we call:</p><pre>marks.get(&quot;Java&quot;);</pre><p>Java finds the appropriate bucket and checks the entries.</p><p>It doesn’t simply compare hash codes.</p><p>It also needs to check the actual key.</p><p>This is why both <strong>hashCode() and </strong><strong>equals()</strong> are important.</p><h3>Why Are hashCode() and equals() Important?</h3><p>This is one of the most important concepts to understand when working with HashMap.</p><p>Suppose we create our own class:</p><pre>class Employee {<br>    private int id;<br>    private String name;<br>    public Employee(int id, String name) {<br>        this.id = id;<br>        this.name = name;<br>    }<br>}</pre><p>Now imagine using it as a key:</p><pre>Map&lt;Employee, String&gt; employees = new HashMap&lt;&gt;();</pre><p>For custom objects, we need to properly implement equals() and hashCode() when logical equality is intended.</p><p>For example:</p><pre>@Override<br>public int hashCode() {<br>    return id;<br>}<br>@Override<br>public boolean equals(Object obj) {<br>    if (this == obj) {<br>        return true;<br>    }<br>    if (!(obj instanceof Employee)) {<br>        return false;<br>    }<br>    Employee other = (Employee) obj;<br>    return this.id == other.id;<br>}</pre><p>The important contract is:</p><blockquote>If two objects are equal according to equals(), they must return the same hashCode().</blockquote><p>The reverse is not required.</p><p>Two different objects can have the same hash code.</p><p>That’s one reason collisions are possible.</p><h3>A Simple Example of hashCode() and equals()</h3><p>Consider:</p><pre>Employee e1 = new Employee(101, &quot;Puja&quot;);<br>Employee e2 = new Employee(101, &quot;Puja&quot;);</pre><p>If equals() considers these two employees equal, then:</p><pre>e1.equals(e2)</pre><p>should return:</p><pre>true</pre><p>And:</p><pre>e1.hashCode() == e2.hashCode()</pre><p>should also be:</p><pre>true</pre><p>This allows HashMap to correctly locate logically equivalent keys.</p><h3>What Is the Default Capacity?</h3><p>A commonly discussed default initial capacity for HashMap is:</p><pre>16</pre><p>This means the internal table can have 16 buckets once initialized.</p><p>Conceptually:</p><pre>0<br>1<br>2<br>3<br>...<br>15</pre><p>However, there is an important detail:</p><p>HashMap uses lazy initialization, so creating:</p><pre>HashMap&lt;String, Integer&gt; map = new HashMap&lt;&gt;();</pre><p>doesn’t necessarily mean the internal array is immediately allocated with 16 elements.</p><p>The table is initialized when it is first needed.</p><h3>What Is Load Factor?</h3><p>Another important concept is the <strong>load factor</strong>.</p><p>The commonly used default load factor is:</p><pre>0.75</pre><p><em>The load factor determines </em><strong><em>when the </em></strong><strong><em>HashMap should resize its internal table</em></strong><em>.</em></p><blockquote><strong>Important:</strong> The load factor does not determine how much the capacity increases. It only determines when resizing should happen.</blockquote><p>For example:</p><pre>Capacity = 16<br>Load Factor = 0.75</pre><p>The resize threshold is calculated as:</p><pre>Threshold = Capacity × Load Factor<br>          = 16 × 0.75<br>          = 12</pre><p>So:</p><pre>Capacity  = 16<br>Threshold = 12</pre><p><em>Here, </em><em>16 represents the number of buckets, while </em><em>12 represents the point at which the </em><em>HashMap reaches its resize threshold.</em></p><p>It does <strong>not</strong> mean that the capacity becomes:</p><pre>16 + (16 × 0.75) = 28</pre><p>The load factor is only used to calculate the <strong>threshold</strong>.</p><h3>What Happens During Resizing?</h3><p>Suppose the internal capacity is:</p><pre>16</pre><p>and the number of entries grows beyond the resize threshold:</p><pre>Capacity = 16<br>Load Factor = 0.75<br>Threshold = 12</pre><p>When the threshold is exceeded, the HashMap needs to resize its internal table.</p><p>For the usual growth pattern, the capacity is <strong>doubled</strong>:</p><pre>16 → 32</pre><p>So the new capacity becomes:</p><pre>32</pre><p>The new threshold is then calculated using the same load factor:</p><pre>New Threshold = 32 × 0.75<br>              = 24</pre><p>So the progression looks like:</p><pre>Capacity = 16<br>Threshold = 12<br>        ↓ resize<br>Capacity = 32<br>Threshold = 24<br>        ↓ resize<br>Capacity = 64<br>Threshold = 48</pre><p>A simple way to remember this is:</p><pre>Load Factor → Determines WHEN to resize<br>Capacity Growth → Determines HOW MUCH the table grows</pre><p>The entries then need to be redistributed according to the new table size.</p><p>Conceptually:</p><pre>Before Resize<br>Capacity = 16<br>[0] [1] [2] [3] ... [15]<br>             ↓ resize<br>After Resize<br>Capacity = 32<br>[0] [1] [2] [3] ... [31]</pre><p><em>During resizing, existing entries are redistributed into the new table. Because </em><em>HashMap uses power-of-two capacities, an entry can often either </em><strong><em>stay at its current index or move to an index offset by the old capacity</em></strong><em>.</em></p><p>For example, with an old capacity of 16, an entry at index 5 can remain at:</p><pre>5</pre><p>or move to:</p><pre>5 + 16 = 21</pre><p>depending on its hash.</p><p>Resizing can be an expensive operation because the table needs to be expanded and existing entries need to be redistributed.</p><p><em>This is one reason choosing a reasonable initial capacity can sometimes be useful when you already know approximately how many entries the </em><em>HashMap will contain.</em></p><h3>Why Does HashMap Use a Load Factor of 0.75?</h3><p>There is a trade-off.</p><p>If the map resizes too frequently:</p><pre>More resizing<br>→ More work</pre><p>If the map allows too many entries in the same table:</p><pre>More collisions<br>→ Potentially slower lookup</pre><p>The load factor provides a balance between memory usage and performance.</p><p>The default of 0.75 is a commonly used practical choice in Java&#39;s implementation.</p><h3>Is HashMap Really O(1)?</h3><p>You will often hear:</p><blockquote>HashMap provides O(1) average-time for finding a value.</blockquote><p>That’s broadly correct for a well-distributed hash table.</p><p>For example:</p><pre>map.put(&quot;Java&quot;, 90);<br>map.get(&quot;Java&quot;);</pre><p>The average expected complexity is:</p><pre>put() → O(1)<br>get() → O(1)<br>remove() → O(1)</pre><p>However, this doesn’t mean every operation always takes exactly constant time.</p><p>Performance depends on factors such as:</p><ul><li>Hash distribution</li><li>Number of collisions</li><li>Table resizing</li><li>Equality checks</li><li>Whether a bucket contains a linked structure or tree</li></ul><p><em>With heavy collisions, finding a value can take longer than the ideal average case.</em></p><h3>Is HashMap Thread-Safe?</h3><p>No.</p><p>HashMap is <strong>not thread-safe</strong>.</p><p>If multiple threads modify the same HashMap concurrently without proper synchronization, you can encounter inconsistent behavior.</p><p>For concurrent access, Java provides alternatives such as:</p><pre>ConcurrentHashMap</pre><p>For example:</p><pre>Map&lt;String, Integer&gt; map = new ConcurrentHashMap&lt;&gt;();</pre><p>The right collection depends on the application’s concurrency requirements.</p><h3>Can HashMap Have a Null Key?</h3><p>Yes.</p><p>A HashMap allows:</p><pre>Map&lt;String, Integer&gt; map = new HashMap&lt;&gt;();<br>map.put(null, 100);</pre><p>It can also contain multiple null values:</p><pre>map.put(&quot;Java&quot;, null);<br>map.put(&quot;Spring&quot;, null);</pre><p>So:</p><pre>Null keys   → One<br>Null values → Multiple</pre><h3>HashMap Internals at a Glance</h3><p>Let’s put everything together.</p><pre>                 put(key, value)<br>                         |<br>                         ↓<br>                  key.hashCode()<br>                         |<br>                         ↓<br>                    Hash value<br>                         |<br>                         ↓<br>                  Bucket index<br>                         |<br>                         ↓<br>                  Internal array<br>                         |<br>              ┌──────────┴──────────┐ <br>              ↓                     ↓ <br>           Empty bucket         Existing entry <br>              ↓                     ↓ <br>            Store            hash + equals() <br>                                    | <br>                           ┌────────┴────────┐ <br>                           ↓                 ↓ <br>                        Same key         Different key <br>                           ↓                 ↓ <br>                       Update value       Collision <br>                                             | <br>                                   ┌─────────┴─────────┐ <br>                                   ↓                   ↓ <br>                              Linked structure    Red-Black Tree <br>                                                    (Java 8+)</pre><p><em>This is the basic idea behind how </em><em>HashMap works.</em></p><h3>What If Two Keys Are the Same?</h3><p>An important point is that a collision does <strong>not</strong> necessarily mean the keys are the same.</p><p>Suppose we have:</p><pre>map.put(&quot;Java&quot;, 90);<br>map.put(&quot;Java&quot;, 95);</pre><p>Here, &quot;Java&quot; is the <strong>same key</strong>.</p><p>When the second put() happens, HashMap finds the existing key and uses equals() to confirm that the keys are equal.</p><p>Instead of creating another entry, HashMap <strong>updates the existing value</strong>:</p><pre>Before:<br>&quot;Java&quot; → 90<br><br>After:<br>&quot;Java&quot; → 95</pre><p>So:</p><pre>map.get(&quot;Java&quot;);</pre><p>returns:</p><pre>95</pre><p>This means a HashMap cannot contain two separate entries with equal keys.</p><p>However, two <strong>different keys</strong> can still end up in the same bucket. That is a collision.</p><p>For example:</p><pre>Different keys<br>     ↓<br>Same bucket<br>     ↓<br>Collision<br>     ↓<br>Linked Structure / Red-Black Tree</pre><p>So remember the difference:</p><blockquote>Same key → Existing value is replaced</blockquote><blockquote>Different keys, same bucket → Collision occurs</blockquote><blockquote>Different keys, different buckets → Both are stored separately</blockquote><p>This distinction is important when understanding how HashMap handles keys internally.</p><h3>What Is a Red-Black Tree in HashMap?</h3><p>We have already seen that collisions can occur when multiple keys end up in the same bucket.</p><p>Before Java 8, a bucket mainly used a <strong>linked list</strong> to store entries when collisions occurred.</p><p>From <strong>Java 8</strong>, HashMap introduced an optimization for buckets that contain many entries: the linked structure can be converted into a <strong>Red-Black Tree</strong>.</p><p>A Red-Black Tree is a type of <strong>self-balancing Binary Search Tree</strong>.</p><p>Each node is assigned one of two colors:</p><ul><li>Red</li><li>Black</li></ul><p>The tree follows certain rules to keep itself balanced. Because of this balancing, searching, inserting, and deleting elements in the tree can generally be performed in:</p><pre>O(log n)</pre><p>This is useful when many keys end up in the same bucket.</p><p>Conceptually:</p><pre>Few collisions<br>Bucket<br>  ↓<br>Entry → Entry → Entry → Entry<br>        Linked Structure<br><br>Many collisions<br>     Bucket<br>       ↓<br>     Entry<br>     /   \<br> Entry   Entry<br> /  \      \<br>...  ...   ...<br> Red-Black Tree</pre><p>HashMap does <strong>not</strong> immediately create a Red-Black Tree whenever a collision happens.</p><p>In Java 8+, when a bucket becomes heavily populated, HashMap can convert that bucket into a tree. Treeification also depends on the table capacity. If the table is still small, HashMap may resize the table instead of immediately creating a tree.</p><p>The commonly known thresholds in the Java implementation are:</p><pre>TREEIFY_THRESHOLD      = 8<br>UNTREEIFY_THRESHOLD    = 6<br>MIN_TREEIFY_CAPACITY   = 64</pre><ul><li><strong>TREEIFY_THRESHOLD = 8</strong><br><em>When a bucket becomes heavily populated, around 8 entries, HashMap may convert the linked list into a Red-Black Tree.</em></li><li><strong>UNTREEIFY_THRESHOLD = 6</strong><br><em>If a tree bucket becomes smaller, around 6 entries, HashMap can convert it back into a linked list.</em></li><li><strong>MIN_TREEIFY_CAPACITY = 64</strong><br><em>HashMap generally treeifies a bucket only when the table has at least 64 buckets. If the table is smaller, it prefers to resize first.</em></li></ul><h4>Easy to Remember</h4><p><em>8 → Tree<br>6 → Linked List<br>64 → Minimum table capacity for treeification</em></p><p>So, it is better to remember this as:</p><blockquote><strong>Java 8 introduced Red-Black Trees in heavily collided HashMap buckets to improve performance when many entries accumulate in the same bucket.</strong></blockquote><h3>Final Takeaway</h3><p>HashMap may look simple from the outside:</p><pre>map.put(&quot;Java&quot;, 90);<br>map.get(&quot;Java&quot;);</pre><p>But internally, several things happen.</p><p>The overall flow is:</p><pre>Key<br> ↓<br>hashCode()<br> ↓<br>Hash calculation<br> ↓<br>Bucket index<br> ↓<br>Check existing entries<br> ↓<br>No collision → Store entry<br>        OR<br>Collision → Compare hash + equals()<br>        ↓<br>  Linked Structure / Red-Black Tree</pre><p>The most important points to remember are:</p><ul><li><em>HashMap stores data as </em><strong><em>key-value pairs</em></strong><em>.</em></li><li><em>It uses an internal </em><strong><em>array of buckets</em></strong><em>.</em></li><li><em>hashCode() helps determine where a key should be stored.</em></li><li><em>Different keys can produce the same bucket index, causing a </em><strong><em>collision</em></strong><em>.</em></li><li><em>equals() is used to determine whether two keys are actually equal.</em></li><li><em>Since </em><strong><em>Java 8</em></strong><em>, heavily populated buckets can be converted into </em><strong><em>Red-Black Trees</em></strong><em>.</em></li><li><em>The default load factor is </em><strong><em>0.75</em></strong><em>.</em></li><li><em>Load factor determines </em><strong><em>when resizing happens</em></strong><em>, not how much the capacity increases.</em></li><li><em>HashMap normally grows its capacity by </em><strong><em>doubling it</em></strong><em>, such as </em><em>16 → 32 → 64.</em></li><li><em>put(), </em><em>get(), and </em><em>remove() have </em><strong><em>O(1) average expected time</em></strong><em>, assuming a good distribution of hashes.</em></li><li><em>HashMap is </em><strong><em>not thread-safe</em></strong><em> for concurrent modifications.</em></li></ul><p>Once you understand <strong>hashing → buckets → collisions → treeification → resizing</strong>, the internal working of HashMap becomes much easier to understand.</p><h3>Final Interview Question</h3><p>If an interviewer asks:</p><blockquote><strong>“How does HashMap work internally?”</strong></blockquote><p>A simple answer is:</p><blockquote>HashMap stores key-value pairs in an array of buckets. When we insert a key, HashMap uses its hashCode() to calculate a bucket location. If the bucket is empty, the entry is stored there. If another entry already exists, HashMap handles the collision by comparing the hash and using equals(). Since Java 8, heavily populated buckets can be converted into Red-Black Trees to improve performance. HashMap also resizes when the number of entries crosses the threshold determined by the load factor.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6581aacee7d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding @Transactional in Spring Boot: Commit, Rollback, Propagation & Real-World Examples]]></title>
            <link>https://medium.com/@pjkri33/understanding-transactional-in-spring-boot-commit-rollback-propagation-real-world-examples-1b20a41f8c72?source=rss-d0e5a7ec930d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b20a41f8c72</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Puja Kumari]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 17:28:08 GMT</pubDate>
            <atom:updated>2026-09-15T17:32:16.662Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A practical guide to transaction management in Spring Boot, including commit, rollback, and propagation.</blockquote><p>If you have worked with Spring Boot, you have probably seen this annotation:</p><pre>@Transactional</pre><p>At first, it looks like a very simple annotation.</p><p>But when I started looking deeper into Spring Boot transactions, I came across questions like:</p><ul><li>What exactly does @Transactional do?</li><li>What happens if one database operation succeeds and another fails?</li><li>Does Spring automatically roll everything back?</li><li>What is the difference between REQUIRED and REQUIRES_NEW?</li><li>What does readOnly = true actually mean?</li></ul><p>Understanding these concepts is important because transactions are not just about database operations. They are about keeping our application’s data <strong>consistent and reliable</strong>.</p><p>Let’s understand @Transactional step by step with simple examples.</p><h3>What Is a Transaction?</h3><p>A <strong>transaction</strong> is a group of database operations that should be treated as a <strong>single logical unit of work</strong>.</p><p>A simple real-world example is transferring money from one bank account to another.</p><p>Suppose we want to transfer <strong>₹1,000 from Account A to Account B</strong>.</p><p>Two operations are required:</p><pre>Account A<br>   ↓<br>Debit ₹1,000<br>   ↓<br>Account B<br>   ↓<br>Credit ₹1,000</pre><p>We don’t want only one operation to succeed.</p><p>Imagine this:</p><pre>Debit Account A       ✅<br>Credit Account B      ❌</pre><p>Now ₹1,000 has been deducted from Account A but has not been credited to Account B.</p><p>That leaves the system in an <strong>inconsistent state</strong>.</p><p>Ideally, we want:</p><pre>Transfer ₹1,000<br>                    │<br>             ┌──────┴──────┐<br>             ↓             ↓<br>          Debit A       Credit B<br>             │             │<br>             └──────┬──────┘<br>                    ↓<br>                Success?<br>                /       \<br>              Yes        No<br>               ↓          ↓<br>            COMMIT     ROLLBACK</pre><blockquote>The idea is simple: <strong>either everything succeeds, or the transaction rolls back the changes when something goes wrong.</strong></blockquote><p>This is the basic idea behind database transactions.</p><h3>ACID Properties of a Transaction</h3><p>Before understanding @Transactional, it helps to understand one important concept: <strong>ACID properties</strong>.</p><p>ACID is a set of properties that helps ensure database transactions are processed <strong>reliably and safely</strong>.</p><p>Think about a simple money transfer:</p><p><strong><em>Transfer ₹1,000 from Account A to Account B.</em></strong></p><p>Two things need to happen:</p><p>₹1,000 should be deducted from Account A.</p><p>₹1,000 should be added to Account B.</p><p>We don’t want the first operation to succeed while the second one fails. This is where ACID properties become important.</p><p>Transactions are commonly explained using four important properties known as <strong>ACID</strong>:</p><ul><li><strong>A — Atomicity</strong></li><li><strong>C — Consistency</strong></li><li><strong>I — Isolation</strong></li><li><strong>D — Durability</strong></li></ul><p>Let’s understand each one with a simple example.</p><h3>1. Atomicity — All or Nothing</h3><p>Atomicity means that a transaction is treated as <strong>one unit of work</strong>.</p><p>Let’s continue with our money-transfer example:</p><pre>Debit Account A       ✅<br>Credit Account B      ❌<br>        ↓<br>     ROLLBACK<br>        ↓<br>Debit is also undone</pre><p>If one of the required operations fails, the transaction can roll back the changes made by the transaction.</p><p>For example:</p><pre>Before:<br>Account A = ₹5,000<br>Account B = ₹2,000<br><br>Transfer = ₹1,000<br>If transfer succeeds:<br>Account A = ₹4,000<br>Account B = ₹3,000<br>If credit operation fails:<br>Account A = ₹5,000<br>Account B = ₹2,000</pre><p>The goal is to avoid leaving behind a <strong>partial transaction result</strong>.</p><p><strong>Simple idea:</strong></p><blockquote><strong>Either everything succeeds, or nothing does.</strong></blockquote><h3>2. Consistency — Data Remains Valid</h3><p>Consistency means that a transaction should take the database from <strong>one valid state to another valid state</strong>.</p><p>For example, suppose our application has a rule:</p><blockquote>Account balance cannot be negative.</blockquote><p>Before the transaction:</p><pre>Account A = ₹5,000<br>Account B = ₹2,000</pre><p>After transferring ₹1,000:</p><pre>Account A = ₹4,000<br>Account B = ₹3,000</pre><p>The database still follows its rules and constraints.</p><p>If a transaction would violate an important database constraint, the transaction should not leave the database in that invalid state.</p><p><strong>Simple idea:</strong></p><blockquote><strong>A transaction should preserve the rules and integrity of the database.</strong></blockquote><h3>3. Isolation — Transactions Should Not Interfere Incorrectly</h3><p>Isolation becomes important when <strong>multiple transactions run at the same time</strong>.</p><p>Imagine Account A has ₹5,000.</p><p>Two transactions start almost simultaneously:</p><pre>Transaction 1 → Withdraw ₹3,000<br>Transaction 2 → Withdraw ₹3,000</pre><p>If both transactions read the same initial balance without proper control, they might both think there is enough money.</p><pre>Account Balance = ₹5,000<br><br>Transaction 1 → Reads ₹5,000<br>Transaction 2 → Reads ₹5,000<br><br>Both try to withdraw ₹3,000</pre><p>This can lead to incorrect results.</p><p>Database <strong>isolation levels</strong> help control how concurrent transactions interact.</p><p>Common isolation levels include:</p><pre>READ_UNCOMMITTED<br>READ_COMMITTED<br>REPEATABLE_READ<br>SERIALIZABLE</pre><p>The exact behavior depends on the database and transaction configuration.</p><p><strong>Simple idea:</strong></p><blockquote><strong>Concurrent transactions should interact in a controlled and predictable way.</strong></blockquote><h3>4. Durability — Committed Data Stays Saved</h3><p>Durability means that once a transaction has been successfully <strong>committed</strong>, its changes should persist.</p><p>For example:</p><pre>Transfer ₹1,000<br>      ↓<br>Transaction succeeds<br>      ↓<br>COMMIT<br>      ↓<br>Data is saved<br>      ↓<br>Application crashes<br>      ↓<br>Data remains persisted</pre><p>If the transfer was successfully committed, restarting the application should not simply undo that transaction.</p><p>For example:</p><pre>Before:<br>Account A = ₹5,000<br>Account B = ₹2,000<br><br>After COMMIT:<br>Account A = ₹4,000<br>Account B = ₹3,000<br><br>Application crashes ❌<br><br>After restart:<br>Account A = ₹4,000<br>Account B = ₹3,000</pre><p><strong>Simple idea:</strong></p><blockquote><strong>Once a transaction is committed, its changes should persist.</strong></blockquote><p>These properties are especially important in systems such as <strong>banking, payments, e-commerce, inventory management, and order processing</strong>.</p><p>And this is where @Transactional becomes useful in Spring applications.</p><p>Instead of manually managing transaction boundaries, Spring can manage the transaction around a business operation:</p><pre>@Transactional<br>public void transferMoney() {<br>    debitAccount();<br>    creditAccount();<br>}</pre><p>If the operation completes successfully, the transaction can be committed. If an appropriate failure occurs, Spring can roll it back according to the transaction’s rollback rules.</p><h3>What Is @Transactional?</h3><p>@Transactional is a Spring annotation used to define <strong>transactional behavior around a method or class</strong>.</p><p>For example:</p><pre>@Service<br>public class OrderService {<br>    <br>    @Transactional<br>    public void placeOrder(Order order) {<br>        orderRepository.save(order);<br>        paymentRepository.save(order.getPayment());<br>        inventoryRepository.updateStock(order.getProductId());<br>    }<br>}</pre><p>Here, multiple database operations are part of the same business operation.</p><p>Conceptually:</p><pre>@Transactional<br>      │<br>      ▼<br>Start Transaction<br>      │<br>      ├── Save Order<br>      │<br>      ├── Save Payment<br>      │<br>      └── Update Inventory<br>      │<br>      ▼<br>   Everything OK?<br>      /       \<br>    Yes        No<br>     ↓          ↓<br>  COMMIT     ROLLBACK</pre><p>If everything succeeds, the transaction is committed.</p><p>If a rollback-triggering exception occurs, Spring can roll back the transaction.</p><h3>Why Do We Need @Transactional?</h3><p>Let’s take a simple order-processing example.</p><p>Suppose we need to perform three operations:</p><pre>1. Create Order<br>2. Update Inventory<br>3. Save Payment</pre><p>Without a transaction boundary around the complete business operation, we could potentially end up with:</p><pre>Create Order       ✅<br>Update Inventory   ✅<br>Save Payment       ❌</pre><p>Now we have an order and inventory update, but payment information was not saved.</p><p>That’s not what we want.</p><p>With:</p><pre>@Transactional<br>public void placeOrder(Order order) {<br>    orderRepository.save(order);<br>    inventoryRepository.reduceStock(order.getProductId());<br>    paymentRepository.save(order.getPayment());<br>}</pre><p>the database operations can participate in the same transaction.</p><p>If the transaction is rolled back:</p><pre>Create Order<br>     ↓<br>Update Inventory<br>     ↓<br>Save Payment<br>     ↓<br>Payment fails<br>     ↓<br>ROLLBACK<br>     ↓<br>Changes made in the transaction are undone</pre><p>This is why transaction boundaries matter.</p><h3>With @Transactional vs Without @Transactional</h3><p>This is one of the easiest ways to understand the concept.</p><p>Consider a money transfer.</p><h3>Without @Transactional</h3><pre>public void transferMoney(Long senderId, Long receiverId, double amount) {<br>  accountRepository.debit(senderId, amount);<br>  accountRepository.credit(receiverId, amount);<br>}</pre><p>Suppose:</p><pre>Debit Sender        ✅<br>Credit Receiver     ❌</pre><p>If these operations are not otherwise enclosed in a single transaction, the application can potentially end up with a partially completed business operation.</p><pre>Sender Account<br>      ↓<br>₹1,000 deducted ✅<br><br>Receiver Account<br>      ↓<br>Credit failed ❌<br>-------------------------<br>Potential inconsistency<br>-------------------------</pre><p>The exact behavior depends on how your repositories, database, and transaction configuration are set up.</p><p>The important point is that there is <strong>no single transaction boundary around the complete business operation at this method level</strong>.</p><h3>With @Transactional</h3><p>Now let’s add @Transactional:</p><pre>@Transactional<br>public void transferMoney(Long senderId, Long receiverId, double amount) {<br>  accountRepository.debit(senderId, amount);<br>  accountRepository.credit(receiverId, amount);<br>}</pre><p>Now both operations can participate in the same transaction.</p><pre>Start Transaction<br>       │<br>       ▼<br>Debit Sender<br>       │<br>       ▼<br>Credit Receiver<br>       │<br>       ▼<br>    Success?<br>    /     \<br>  Yes      No<br>   ↓        ↓<br>COMMIT   ROLLBACK</pre><p>If the credit operation fails with an exception that triggers rollback:</p><pre>Debit ₹1,000<br>      ↓<br>Credit fails<br>      ↓<br>Rollback<br>      ↓<br>Debit is also undone</pre><p>This helps maintain consistency.</p><blockquote><strong>Note: </strong>@Transactional is not simply &quot;rollback everything.&quot; It defines how a transaction should be managed around a business operation.</blockquote><h3>A Real-World Example: E-Commerce Order</h3><p>Let’s say we are developing an e-commerce application.</p><p>When a customer places an order, we need to:</p><ol><li>Create the order</li><li>Save order items</li><li>Reduce inventory</li><li>Save payment information</li></ol><p>We could have:</p><pre>@Service<br>public class OrderService {<br>    <br>    @Transactional<br>    public void placeOrder(OrderRequest request) {<br>        Order order = orderRepository.save(<br>                new Order(request.getCustomerId()));<br><br>        orderItemRepository.saveAll(request.getItems());<br>        <br>        inventoryRepository.reduceStock(<br>                request.getProductId(),<br>                request.getQuantity()<br>        );<br><br>        paymentRepository.save(<br>                createPayment(order, request)<br>        );<br>    }<br>}</pre><p>Now the transaction boundary represents the business operation:</p><pre>                    placeOrder()<br>                         │<br>                 Start Transaction<br>                         │<br>          ┌──────────────┼──────────────┐<br>          ↓              ↓              ↓<br>       Order          Inventory       Payment<br>          │              │              │<br>          └──────────────┼──────────────┘<br>                         ↓<br>                     Success?<br>                    /         \<br>                  Yes          No<br>                   ↓            ↓<br>                COMMIT       ROLLBACK</pre><p>This is a practical example of why transaction boundaries are important.</p><h3>Where Should @Transactional Be Used?</h3><p>In a typical Spring Boot application, @Transactional is commonly placed at the <strong>service layer</strong>.</p><p>For example:</p><pre>@Service<br>public class OrderService {<br>    @Transactional<br>    public void placeOrder(OrderRequest request) {<br>        // business logic<br>    }<br>}</pre><p>A typical application structure looks like:</p><pre>Controller<br>    ↓<br>Service<br>    ↓<br>Repository<br>    ↓<br>Database</pre><p>The controller handles the HTTP request.</p><p>The service handles the business logic.</p><p>The repository communicates with the database.</p><p>Because a service method often represents a complete business operation, it is usually a natural place for the transaction boundary.</p><h3>Rollback Behavior</h3><p>Now comes one of the most important parts of @Transactional.</p><p><strong>Does every exception cause a rollback?</strong></p><p>No.</p><p>By default, Spring rolls back for <strong>unchecked exceptions</strong>, such as RuntimeException, and for Error.</p><p>For example:</p><pre>@Transactional<br>public void createOrder(Order order) {<br>    orderRepository.save(order);<br>    throw new RuntimeException(&quot;Something went wrong&quot;);<br>}</pre><p>The transaction is normally marked for rollback.</p><p>Conceptually:</p><pre>Save Order<br>    ↓<br>RuntimeException<br>    ↓<br>ROLLBACK</pre><h3>What About Checked Exceptions?</h3><p>Consider:</p><pre>@Transactional<br>public void createOrder(Order order) throws Exception {<br>    orderRepository.save(order);<br>    throw new Exception(&quot;Something went wrong&quot;);<br>}</pre><p>If you specifically want the transaction to roll back for checked exceptions, you can configure it:</p><pre>@Transactional(rollbackFor = Exception.class)<br>public void createOrder(Order order) throws Exception {<br>    orderRepository.save(order);<br>    throw new Exception(&quot;Something went wrong&quot;);<br>}</pre><p>So don’t simply remember:</p><blockquote>Exception = rollback</blockquote><blockquote>Instead, remember:</blockquote><blockquote><strong>Rollback depends on the transaction’s rollback rules.</strong></blockquote><h3>Propagation</h3><p>Now let’s look at another important concept: <strong>transaction propagation</strong>.</p><p>Propagation defines what should happen when one transactional method calls another transactional method.</p><p>The default propagation is:</p><pre>Propagation.REQUIRED</pre><p>For example:</p><pre>@Transactional(propagation = Propagation.REQUIRED)<br>public void placeOrder() {<br>    // business logic<br>}</pre><p>REQUIRED means:</p><blockquote>If a transaction already exists, join it. Otherwise, create a new transaction.</blockquote><p>Conceptually:</p><pre>Transaction A<br>      │<br>      ├── Method A<br>      │<br>      └── Method B<br>             │<br>             └── Joins Transaction A</pre><p>This is the most commonly used propagation behavior.</p><h3>REQUIRED vs REQUIRES_NEW</h3><p>Another important propagation option is:</p><pre>Propagation.REQUIRES_NEW</pre><p>REQUIRES_NEW means that the existing transaction is suspended and a <strong>new transaction</strong> is started.</p><p>For example:</p><pre>@Transactional<br>public void placeOrder() {<br>    saveOrder();<br>    auditService.saveAudit();<br>}</pre><p>And:</p><pre>@Transactional(propagation = Propagation.REQUIRES_NEW)<br>public void saveAudit() {<br>    auditRepository.save(...);<br>}</pre><p>Conceptually:</p><pre>Transaction A<br>      │<br>      ├── Save Order<br>      │<br>      └── Save Audit<br>              │<br>              ▼<br>        Suspend Transaction A<br>              │<br>              ▼<br>        Start Transaction B<br>              │<br>              ▼<br>           Commit B<br>              │<br>              ▼<br>        Resume Transaction A</pre><blockquote>REQUIRES_NEW can be useful when an operation needs to be committed independently, but it should be used carefully because it changes the transaction semantics of the overall operation.</blockquote><h3>What Does readOnly = true Mean?</h3><p>For read-oriented operations, you may see:</p><pre>@Transactional(readOnly = true)<br>public List&lt;Order&gt; getOrders() {<br>    return orderRepository.findAll();<br>}</pre><p>This tells the transaction infrastructure that the transaction is intended to be read-only.</p><h3>@Transactional at Class Level</h3><p>You can also put @Transactional on a class.</p><pre>@Service<br>@Transactional<br>public class OrderService {<br>    public void createOrder() {<br>        // transactional<br>    }<br>    public void updateOrder() {<br>        // transactional<br>    }<br>}</pre><p>You can override the behavior for a particular method.</p><p>For example:</p><pre>@Service<br>@Transactional<br>public class OrderService {<br>    public void createOrder() {<br>        // transactional<br>    }<br>    @Transactional(readOnly = true)<br>    public List&lt;Order&gt; getOrders() {<br>        return orderRepository.findAll();<br>    }<br>}</pre><p>This allows class-level configuration to act as a default while individual methods can customize the behavior.</p><h3>Thanks for Reading!</h3><p>If you’re learning Java and Spring Boot, follow for more practical articles about:</p><ul><li>Java</li><li>Spring Boot</li><li>REST APIs</li><li>Microservices</li><li>Backend Development</li><li>SQL</li><li>System Design</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b20a41f8c72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 21 Features You Should Know]]></title>
            <link>https://medium.com/@pjkri33/java-21-features-you-should-know-69475c3cdd26?source=rss-d0e5a7ec930d------2</link>
            <guid isPermaLink="false">https://medium.com/p/69475c3cdd26</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java21]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Puja Kumari]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 12:40:35 GMT</pubDate>
            <atom:updated>2026-09-04T12:40:35.898Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*sl79bxroaXDjJr6A" /></figure><blockquote>Working with Java backend technologies such as <strong>Spring Boot, REST APIs, and Microservices</strong>, I’ve found that keeping up with newer Java versions is important — not just for interviews, but also for understanding how modern Java applications are being built.</blockquote><h3>1. Virtual Threads</h3><p>Before virtual threads, Java applications mainly used platform threads to handle multiple tasks. Creating and managing a large number of platform threads can become expensive because threads consume system resources.</p><p>Virtual threads are lightweight threads managed by the JVM. It makes easier to handle a large number of concurrent tasks, especially when the application spends a lot of time waiting for I/O operations.</p><pre>public class VirtualThreadDemo {<br>  public static void main(String[] args) throws InterruptedException {<br>        Thread thread = Thread.startVirtualThread(() -&gt; {<br>            System.out.println(&quot;Running in a virtual thread&quot;);<br>        });<br>        thread.join();<br>    }<br>}</pre><p>You can also create multiple virtual threads:</p><pre>public class VirtualThreadDemo {<br>  public static void main(String[] args) throws InterruptedException {<br>        for (int i = 0; i &lt; 5; i++) {<br>            Thread.startVirtualThread(() -&gt; {<br>                System.out.println(<br>                    &quot;Task running: &quot; + Thread.currentThread()<br>                );<br>            });<br>        }<br>        Thread.sleep(1000);<br>    }<br>}</pre><h3>Why is this useful?</h3><p>Think about a backend service that receives thousands of requests.</p><p>Many of those requests spend most of their time waiting for things such as:</p><ul><li>Database responses</li><li>HTTP calls</li><li>Network operations</li><li>Other microservices</li></ul><p>Virtual threads are particularly useful for these <strong>I/O-heavy applications</strong>.</p><p>The real advantage of virtual threads is that they make handling a large number of concurrent tasks much more scalable without requiring a completely different programming model.</p><p>For someone working with Spring Boot and microservices, this is definitely a feature worth exploring.</p><h3>2. Pattern Matching for Switch</h3><p>Another feature I really like in Java 21 is <strong>pattern matching for switch</strong>.</p><p>Traditionally, if we wanted to perform different operations based on an object’s type, we might write several instanceof checks.</p><p>Java 21 makes this much cleaner.</p><pre>static String getValue(Object value) {<br>  return switch (value) {<br>        case Integer i -&gt; &quot;Integer: &quot; + i;<br>        case String s -&gt; &quot;String: &quot; + s;<br>        case Double d -&gt; &quot;Double: &quot; + d;<br>        case null -&gt; &quot;Null value&quot;;<br>        default -&gt; &quot;Unknown type&quot;;<br>    };<br>}</pre><p>This is easier to read than writing multiple if-else blocks.</p><p>It also becomes useful when working with different types of data in backend applications.</p><h3>3. Record Patterns</h3><p>Records were introduced earlier, but Java 21 takes them further with <strong>Record Patterns, </strong>making it easier to extract values directly from a record.</p><p>Suppose we have an Employee record:</p><pre>record Employee(String name, int age) {}</pre><p>We can extract its values directly using a pattern:</p><pre>if(employee instanceof Employee(String name, int age)) {<br>  System.out.println(&quot;Name: &quot; + name);<br>  System.out.println(&quot;Age: &quot; + age);<br>}</pre><p>Instead of first getting the record and then separately calling:</p><pre>employee.name();<br>employee.age();</pre><p>the pattern allows us to extract the components directly.</p><p>This becomes particularly interesting when combined with pattern matching.</p><p>For example:</p><pre>static void printEmployee(Object obj) {<br>  if (obj instanceof Employee(String name, int age)) {<br>        System.out.println(<br>            name + &quot; is &quot; + age + &quot; years old.&quot;<br>        );<br>    }<br>}</pre><p>It’s a small feature, but it can make code cleaner when working with data-oriented classes.</p><h3>4. Sequenced Collections</h3><p>Java collections have always been an important part of Java development.</p><p>Java 21 introduced new interfaces such as:</p><ul><li>SequencedCollection</li><li>SequencedSet</li><li>SequencedMap</li></ul><p>The main idea is to provide a consistent way of working with collections where <strong>encounter order matters</strong>.</p><p>For example:</p><pre>SequencedCollection&lt;String&gt; names =<br>        new ArrayList&lt;&gt;(List.of(&quot;Riya&quot;, &quot;Sakshi&quot;, &quot;Amit&quot;));<br>System.out.println(names.getFirst());<br>System.out.println(names.getLast());</pre><p>We can also use:</p><pre>names.addFirst(&quot;Neha&quot;);<br>names.addLast(&quot;Ritu&quot;);</pre><p>And:</p><pre>names.removeFirst();<br>names.removeLast();</pre><p>There is also:</p><pre>names.reversed();</pre><p>Before this API, working with the beginning and end of different collection implementations could require different approaches.</p><h3>5. Generational ZGC</h3><p>Java 21 also introduced <strong>Generational ZGC</strong>.</p><p>If you’ve worked with Java memory management, you’ve probably heard about the garbage collector.</p><p>The JVM automatically identifies objects that are no longer being used and frees the memory occupied by them.</p><p><strong>ZGC</strong> is designed for applications that need very low pause times, even when working with large heaps. It performs most of its work concurrently, so the application can continue running while garbage collection is happening.</p><p>Generational ZGC improves this approach by taking advantage of a simple observation: <strong>most objects created by an application are short-lived.</strong></p><p>For example, imagine a backend application processing an order:</p><pre>public OrderResponse createOrder(OrderRequest request) {<br>Order order = new Order(<br>        request.getProductId(),<br>        request.getQuantity()<br>    );<br>    // Save order and process the request<br>    return new OrderResponse(order.getId(), &quot;SUCCESS&quot;);<br>}</pre><p>Every time this method is called, several objects may be created. Some of them are needed only while processing the request and can become unused soon after the request is completed.</p><p>Generational ZGC separates objects based on their lifetime:</p><pre>Java Heap<br>│<br>├── Young Generation<br>│   └── Short-lived objects<br>│<br>└── Old Generation<br>    └── Long-lived objects</pre><p>New objects are placed in the young generation. Objects that survive longer can be promoted to the old generation. This allows ZGC to focus more frequently on short-lived objects while handling long-lived objects differently.</p><p>In Java 21, Generational ZGC had to be enabled explicitly:</p><pre>java -XX:+UseZGC -XX:+ZGenerational -jar application.jar</pre><p><strong>In simple terms:</strong> Generational ZGC makes ZGC smarter about object lifetimes by treating short-lived and long-lived objects differently, helping reduce garbage collection overhead while keeping pause times low.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69475c3cdd26" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>