<?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 Mayank Pant on Medium]]></title>
        <description><![CDATA[Stories by Mayank Pant on Medium]]></description>
        <link>https://medium.com/@mayankpant-dev?source=rss-35632dfbbe6e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hv2VkZA6ppHIPTGEFc3fPQ.jpeg</url>
            <title>Stories by Mayank Pant on Medium</title>
            <link>https://medium.com/@mayankpant-dev?source=rss-35632dfbbe6e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 03:03:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mayankpant-dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Java Message Service (JMS)]]></title>
            <link>https://mayankpant-dev.medium.com/java-message-service-jms-36b552daf53e?source=rss-35632dfbbe6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/36b552daf53e</guid>
            <category><![CDATA[jakarta-message-service]]></category>
            <category><![CDATA[java-messaging-service]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[jms]]></category>
            <dc:creator><![CDATA[Mayank Pant]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 16:08:12 GMT</pubDate>
            <atom:updated>2025-12-19T16:08:58.588Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java/Jakarta Message Service (JMS)</h3><p>Let’s learn JMS first to set the groundwork for learning ActiveMQ later on.</p><h3>Introduction</h3><p>JMS is a standard specification that defines a set of interfaces and protocols for reliable and asynchronous messaging.</p><p>It provides a way for applications to communicate with each other without knowing the details of the underlying communication protocols, such as TCP/IP or HTTP.</p><p>JMS provides a standard way for clients to create, send, receive, and read messages, regardless of the messaging style used.</p><p>The latest JMS version is called Jakarta Message Service and is part of jakarta.jms package, and it contains tons of interfaces.</p><h3>Understanding JMS</h3><p>Imagine you have two applications:</p><ul><li>Application A produces some information</li><li>Application B needs to use that information</li></ul><p>The simplest way is: A directly calls B (like an API call).</p><p>This works, but it creates <em>tight dependency</em>:</p><ul><li>B must be running</li><li>B must respond immediately</li><li>If B is slow or down, A is affected</li><li>A and B must agree on timing</li></ul><p>As systems grow, this becomes fragile.</p><h4>What JMS is</h4><p>JMS is a way for applications to communicate without talking to each other directly.So instead of:</p><blockquote><em>“Hey B, do this now”</em></blockquote><p>Application A says:</p><blockquote><em>“Here is a message for whoever needs it”</em></blockquote><p>and leaves.</p><p>That message is stored in the middle, and:</p><ul><li>The receiver can process it later</li><li>The sender doesn’t need to wait</li><li>Both sides can run independently</li></ul><h4>Why this is important</h4><p>This approach gives you <em>freedom</em>:</p><ul><li>Sender and receiver don’t need to run at the same time</li><li>A slow receiver doesn’t slow down the sender</li><li>Temporary failures don’t break the system</li><li>You can scale sender and receiver separately</li></ul><p>This is especially useful in real systems where:</p><ul><li>Traffic spikes</li><li>Parts of the system go down</li><li>Work needs to be done in the background</li></ul><h4>What JMS actually provides</h4><p>JMS is <strong>not a product</strong> and <strong>not a server</strong>.</p><p>JMS is a <strong>common language</strong> for messaging, a <strong>set of rules</strong> everyone agrees on</p><p>It says:</p><ul><li>How messages are sent</li><li>How messages are stored</li><li>How messages are delivered</li><li>What guarantees exist</li></ul><p>Because everyone follows the same rules you can change the messaging vendor and your application code stays the same.</p><h4>What sits in the middle</h4><p>Between sender and receiver is a <strong>message system</strong> (often called a broker).</p><p>Its job is simple:</p><ul><li>Accept messages</li><li>Hold them safely</li><li>Deliver them when possible</li></ul><p>JMS defines how applications talk to this system, not how the system is built.</p><h4>Real-world examples</h4><p>JMS is useful when:</p><ul><li>An order is placed and many things must happen later</li><li>A payment is processed and notifications follow</li><li>Logs, emails, or reports are handled in background</li><li>Systems talk across teams or companies</li></ul><blockquote><strong><em>JMS lets systems communicate by leaving messages instead of making calls.</em></strong></blockquote><h4>Why JMS is standardized</h4><p>Different companies build different messaging systems.</p><p>Without JMS:</p><ul><li>Each one has its own way</li><li>Code becomes locked to one vendor</li></ul><p>With JMS:</p><ul><li>Everyone follows the same communication rules</li><li>Applications stay portable</li><li>Long-term maintenance becomes easier</li></ul><blockquote>JMS is a Java standard that defines how applications exchange messages in a loosely coupled, message-based way.</blockquote><blockquote>It specifies the rules vendors must follow, while leaving the implementation details to them.</blockquote><blockquote>Developers program against the JMS APIs, so switching the messaging provider does not require changing application code.</blockquote><h3>Core Concepts</h3><p>Key Concepts:</p><ul><li><strong>ConnectionFactory:</strong> Creates connections to the JMS provider</li><li><strong>Connection:</strong> Represents an active connection to the messaging server</li><li><strong>Session:</strong> A single-threaded context for producing and consuming messages</li><li><strong>Destination:</strong> Where messages are sent (Queue or Topic)</li><li><strong>MessageProducer:</strong> Sends messages to a destination</li><li><strong>MessageConsumer:</strong> Receives messages from a destination</li></ul><h4>Messaging Models</h4><p>Note that in a real-world scenario, you would typically create the producer and consumer in separate applications or threads, and use different destinations for different types of messages.</p><p><strong>Point-to-Point (Queue)</strong>: One sender, one receiver. Each message is consumed by exactly one consumer. Think of it like a task queue where workers pick up jobs.</p><p><strong>Publish-Subscribe (Topic)</strong>: One sender, multiple receivers. Each message is delivered to all subscribed consumers. Like a newsletter where everyone gets a copy.</p><h4>Message Types</h4><p>JMS supports several message types:</p><ul><li><strong>Message</strong>: The base interface, used for simple notifications without a body, often with only headers and properties</li><li><strong>TextMessage</strong>: Carries a java.lang.String as its payload, ideal for XML, JSON, or plain text.</li><li><strong>MapMessage</strong>: Stores name-value pairs, where names are Strings and values are Java primitives, accessed by name or sequentially.</li><li><strong>BytesMessage</strong>: Transports a stream of uninterpreted bytes, useful for binary data or interfacing with external systems.</li><li><strong>StreamMessage</strong>: A stream of primitive values (like int, double, boolean) in order, read sequentially.</li><li><strong>ObjectMessage</strong>: Contains a single, serializable Java object, making it easy to pass complex application data.</li></ul><h4>Acknowledgment Modes</h4><p>When creating a session, you specify how messages are acknowledged:</p><ul><li><strong>AUTO_ACKNOWLEDGE</strong>: The session automatically acknowledges a message once the listener successfully finishes processing it or after receive() returns.</li><li><strong>CLIENT_ACKNOWLEDGE</strong>: The consumer manually calls message.acknowledge() to confirm receipt; useful for batch processing or complex validation before marking as done.</li><li><strong>DUPS_OK_ACKNOWLEDGE</strong>: A &quot;lazy&quot; mode where the session acknowledges delivery later, potentially leading to duplicate messages but reducing overhead.</li><li><strong>SESSION_TRANSACTED</strong>: Message delivery and acknowledgment are tied to local JMS transactions, committing or rolling back together with other operations</li></ul><h4>Common JMS Providers</h4><p>You’ll need a JMS provider implementation like Apache ActiveMQ, RabbitMQ, IBM MQ, or AWS SQS. The code remains largely the same regardless of provider.</p><h4>Use Cases</h4><p>JMS is great for asynchronous processing, decoupling microservices, handling background jobs, event-driven architectures, and ensuring reliable message delivery between systems.</p><h3>Features of JMS</h3><ol><li><strong>Messaging Models:</strong> JMS supports two messaging models, Publish-Subscribe and Point-to-Point. <br>In Publish-Subscribe, messages are broadcasted to multiple subscribers, while in Point-to-Point, messages are delivered to only one receiver.</li><li><strong>Reliable Delivery:</strong> JMS ensures reliable message delivery by supporting transactional messaging and message persistence. <br>Message persistence ensures that messages are not lost in case of system failures. Transactional messaging ensures that either all or none of the messages in a transaction are delivered.</li><li><strong>Asynchronous Communication:</strong> JMS allows applications to communicate asynchronously, which means that they do not have to wait for a response from the receiver. This is useful in situations where a sender does not need an immediate response, or when the receiver may be temporarily unavailable.</li><li><strong>Message Filtering:</strong> JMS allows messages to be filtered based on criteria such as message properties, message content, and message headers. This is useful in situations where a receiver is interested in only certain types of messages.</li><li><strong>Message Transformation:</strong> JMS allows messages to be transformed between different message formats, such as XML, JSON, or plain text. This is useful when different systems use different message formats.</li><li><strong>Scalability:</strong> JMS supports distributed systems and can handle high message volumes, making it suitable for large-scale applications.</li><li><strong>Security:</strong> JMS provides several security features, such as authentication, encryption, and authorization, to protect messages from unauthorized access.</li></ol><h3>Dissecting the documentation and understanding the latest JMS version</h3><p>For historical reasons JMS offers alternative sets of interfaces for sending and receiving messages:</p><ul><li><strong>Java Message Service 1.0</strong> defined two domain-specific APIs, one for point-to-point messaging (queues) and one for pub/sub (topics). Although these remain part of Jakarta Messaging for reasons of backwards compatibility they should be considered to be completely superseded by the later APIs.</li><li><strong>Java Message Service 1.1</strong> introduced a new unified API which offered a single set of interfaces that could be used for both point-to-point and pub/sub messaging. This is referred to here as the classic API.</li><li><strong>Jakarta Messaging 2.0</strong> introduces a simplified API which offers all the features of the classic API but which requires fewer interfaces and is simpler to use.</li></ul><p>Each API offers a different set of interfaces for connecting to a Jakarta Messaging vendor and for sending and receiving messages. However they all share a common set of interfaces for representing messages and message destinations and to provide various utility features.</p><h4>Interfaces common to multiple APIs</h4><p>The main interfaces common to multiple APIs are as follows:</p><ul><li>Message, BytesMessage, MapMessage, ObjectMessage, StreamMessage and TextMessage - a message sent to or received from a Jakarta Messaging provider.</li><li>Queue - an administered object that encapsulates the identity of a message destination for point-to-point messaging</li><li>Topic - an administered object that encapsulates the identity of a message destination for pub/sub messaging.</li><li>Destination - the common supertype of Queue and Topic</li></ul><h4>Classic API interfaces</h4><p>The main interfaces provided by the classic API are as follows:</p><ul><li>ConnectionFactory - an administered object used by a client to create a Connection. This interface is also used by the simplified API.</li><li>Connection - an active connection to a Jakarta Messaging provider</li><li>Session - a single-threaded context for sending and receiving messages</li><li>MessageProducer - an object created by a Session that is used for sending messages to a queue or topic</li><li>MessageConsumer - an object created by a Session that is used for receiving messages sent to a queue or topic</li></ul><h4>Simplified API interfaces</h4><p>The simplified API provides the same messaging functionality as the classic API but requires fewer interfaces and is simpler to use. The main interfaces provided by the simplified API are as follows:</p><ul><li>ConnectionFactory - an administered object used by a client to create a JMSContext. This interface is also used by the classic API.</li><li>JMSContext - an active connection to a Jakarta Messaging provider and a single-threaded context for sending and receiving messages</li><li>JMSProducer - an object created by a JMSContext that is used for sending messages to a queue or topic</li><li>JMSConsumer - an object created by a JMSContext that is used for receiving messages sent to a queue or topic</li></ul><h4>Legacy domain-specific API interfaces</h4><p>Although the domain-specific API remains part of Jakarta Messaging for reasons of backwards compatibility it should be considered to be completely superseded by the classic and simplified APIs.</p><p>The main interfaces provided by the domain-specific API for point-to-point messaging are as follows:</p><ul><li>QueueConnectionFactory - an administered object used by a client to create a QueueConnection.</li><li>QueueConnection - an active connection to a Jakarta Messaging provider</li><li>QueueSession - a single-threaded context for sending and receiving messages</li><li>QueueSender - an object created by a QueueSession that is used for sending messages to a queue</li><li>QueueReceiver - an object created by a QueueSession that is used for receiving messages sent to a queue</li></ul><p>The main interfaces provided by the domain-specific API for pub/sub messaging are as follows:</p><ul><li>TopicConnectionFactory - an administered object used by a client to create a TopicConnection.</li><li>TopicConnection - an active connection to a Jakarta Messaging provider</li><li>TopicSession - a single-threaded context for sending and receiving messages</li><li>TopicPublisher - an object created by a TopicSession that is used for sending messages to a topic</li><li>TopicSubscriber - an object created by a TopicSession that is used for receiving messages sent to a topic</li></ul><h4>Administered Objects</h4><p>Administered objects are <strong>pre-configured resources</strong> that applications use to interact with the messaging provider.</p><p>These objects are created and configured by an administrator, not by application code. They contain provider-specific details such as connection information and destination configuration, but they are exposed to applications in a standard, portable way.</p><p>This design ensures that application code does not depend on vendor-specific settings.</p><h4>Administration and Portability</h4><p>Messaging providers differ widely in how they are installed, configured, and managed. If applications had to deal with these differences directly, portability would be difficult.</p><p>To solve this, Jakarta Messaging separates <strong>administration from application logic</strong>. Administrators handle setup and configuration, while developers write code that works the same across environments and vendors.</p><p>This separation is achieved through administered objects.</p><h4>Types of Administered Objects</h4><p>There are two main administered objects used by Jakarta Messaging clients:</p><ul><li><strong>ConnectionFactory</strong><br>Used by an application to establish a connection to the messaging provider. The application does not need to know how the connection is created or configured.</li><li><strong>Destination</strong><br>Represents the location where messages are sent or received. Applications refer to destinations by name rather than by physical or vendor-specific details.</li></ul><h4>Role of JNDI</h4><p>Administered objects are stored in <strong>JNDI (Java Naming and Directory Interface)</strong>.</p><p>JNDI acts as a naming directory where applications can look up the resources they need by name. Instead of embedding configuration details in code, applications simply request the required resources from JNDI at runtime.</p><p>This approach enables:</p><ul><li>cleaner application code</li><li>environment-specific configuration without code changes</li><li>easier maintenance and vendor flexibility</li></ul><h4>More Reading?</h4><p><a href="https://jakarta.ee/learn/docs/jakartaee-tutorial/current/messaging/jms-concepts/jms-concepts.html">Jakarta Messaging Concepts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36b552daf53e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[equals() & hashCode() methods in Java]]></title>
            <link>https://medium.com/the-java-interview-playbook/equals-hashcode-methods-in-java-e99bc1066851?source=rss-35632dfbbe6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e99bc1066851</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hashcode-java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[equals-method-java]]></category>
            <category><![CDATA[java-interview-questions]]></category>
            <dc:creator><![CDATA[Mayank Pant]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 12:06:12 GMT</pubDate>
            <atom:updated>2025-12-12T07:48:06.924Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><p>The methods equals() and hashCode() come from java.lang.Object and determine how objects are compared (and used in hash-based collections).</p><p>By default, equals() compares object references and hashCode() returns a number derived from the object’s identity ,i.e., an int hash code value.</p><p>In practice, most classes override them to define <em>logical</em> equality (same data) and consistent hashing.</p><p>Adhering to their contract is crucial aspect of working with collections like HashMap, HashSet, and other data structures that rely on hashing. Failing to maintain this contract can lead to bugs (e.g. lost map entries) and unpredictable behavior.</p><h3>The equals() Method</h3><p>The equals(Object obj) method, by default in Object class, uses reference equality to compare two objects. <br>But in most cases, it is overridden to perform logical equality by comparing relevant fields in that particular class. And hence we can say that equals method checks whether two objects are logically equal.</p><p>When overriding, one must follow the formal contract rules:</p><ul><li><strong>Reflexive:</strong> x.equals(x) must return true for any non-null x.</li><li><strong>Symmetric:</strong> x.equals(y) should return the same as y.equals(x).</li><li><strong>Transitive:</strong> if x.equals(y) and y.equals(z) then x.equals(z) must hold.</li><li><strong>Consistent:</strong> repeated calls return the same result if objects don’t change.</li><li><strong>Non-null:</strong> x.equals(null) must always return false.</li></ul><p>These requirements are mandated by Java’s specification. For example, a typical override looks like:</p><pre>@Override<br>public boolean equals(Object obj) {<br>    // If both the object reference are same, no need to compare contents, and just return true<br>    if (this == obj) return true;<br><br>    // If the obj passed in is null, then to avoid NPE while comparison, it is better to just return false early on<br>    if(obj == null) return false;<br><br>    // If obj is not of type Person, then how can we compare it to Person, so return false, else it will give ClassCastException later on<br>    if (!(obj instanceof Person)) return false;<br><br>    // Type cast the obj to Person and do the required comparison<br>    Person other = (Person) obj;<br><br>    // Here name can be null, so Objects.equals is used<br>    // It handles null values and delegates to the .equals() method for non-null comparisons<br>    return Objects.equals(this.name, other.name)<br>        &amp;&amp; this.age == other.age;<br>}</pre><p>In this code, two Person instances are equal if their name and age fields match. <br>IDEs and libraries (e.g. Lombok’s @EqualsAndHashCode) often generate such methods automatically.</p><h3>The hashCode() Method</h3><p>The hashCode() method is present inside the Object class and hence every object can call this method and get a value sinceObject class is parent class of all the classes. Hence, this is valid even if the class does not implement the hashCode() method:</p><pre>MyObj obj = new MyObj();<br>int hashValue = obj.hashCode();</pre><p>The hashCode() method returns an int and is used by hash-based collections to place objects into buckets.</p><p>For each different object it will give a different hash code value. This hash code value is generated using the memory address of the object, and then performing some operations onto it.</p><p><strong>But there is no implementation of </strong><strong>hashCode() in </strong><strong>Object class also, how so?<br></strong>In Java’s Object class, the hashCode() method does have a body, but you don’t see it in the source code because it is a native method.</p><pre>public native int hashCode();</pre><p><strong>Why does it not have a body?<br></strong>Because hashCode() is implemented in native code (typically C/C++) inside the JVM, not in Java.<br>When a method is marked native, the implementation is provided by the JVM, not in the Java source.</p><p><strong>Why did Java designers make </strong><strong>hashCode() native?<br></strong>Because the hashCode() requires the memory address of the object to perform some operations, and Java does not have access to this memory, which the JVM knows best.<br>Java code does not have direct access to raw memory addresses, so JVM must compute it.</p><p>When overriding, one must follow the formal contract rules:</p><ul><li><strong>Consistency:</strong> The hash code of an object must remain the same across multiple calls within the same execution if the object’s state (fields used in equals()) doesn’t change.</li><li><strong>Equals-consistency:</strong> If x.equals(y) is true, then x.hashCode() == y.hashCode() must hold.</li><li><strong>Collision allowed:</strong> It’s allowed (though not ideal) for unequal objects to have the same hash code (a collision).</li></ul><h3>equals() and hashCode()</h3><p>While overriding equals() and hashCode() methods, any fields used in equals() should also be used to compute hashCode(). For example:</p><pre>@Override<br>public int hashCode() {<br>    return Objects.hash(name, age);<br>}</pre><p>This uses the same fields (name, age) as the equals() example above, ensuring consistency.</p><p><strong>Here’s how the </strong><strong>equals() and </strong><strong>hashCode() are related:<br></strong>If two objects are equal according to equals() method, they’ll have the same hash code. <br>If two objects have same hash code, then it is not necessary that they will be equal according to equals() method. This can be considered as a hash-collision.<br><strong>Analogy: </strong>Consider two photographs of Kapil Sharma. You can compare these 2 photos and say that his name is Kapil, meaning that you compared the two objects using .equals() . If this is true, both pictures are equal, then they must generate the same hash code, same name in this case.<br>But, if we provide same hash code to 2 different objects, say we give the name “Kapil” to 2 objects, then can we say with guarantee that both objects / photos will be same?<br>No right, as one picture can be of Kapil Sharma and another can be of Kapil Dev. So, same hash code does not guarantee objects to be equal, i.e., equals() method can give false in this case.</p><p>Too many collisions (different objects sharing a hash) can degrade performance, but correctness only demands the weaker rules.</p><p>No matter how many times you call the hashCode() method on an object, the value will be same.</p><h3>The equals–hashCode Contract</h3><p>The two methods are linked by a formal contract: <strong>“if two objects are equal according to </strong><strong>equals(), they must<em> </em>have the same </strong><strong>hashCode()”</strong>.<br>Violating this rule breaks the expectations of hash-based collections.</p><p>Objects which are .equals() MUST have the same .hashCode(). The converse is not required: unequal objects may (due to collision) or may not share a hash code.</p><p>If the contract is violated (for example, by overriding only equals() but not hashCode()), collections can misbehave.</p><p>Hence if we override equals(), we must also override hashCode().</p><p>The core takeaway is: <strong>always override both or neither</strong>. <br>For classes where logical equality is needed (e.g. value objects), implement both consistently; for purely identity-based classes (e.g. entities with unique IDs), it’s often fine to use the default implementations.</p><h3>How Hash-Based Collections Use equals() and hashCode()</h3><p>Collections like HashMap and HashSet rely on this contract. A HashMap stores entries in buckets determined by hash codes, then checks keys with equals(). For a key lookup map.get(k), the process is:</p><ol><li>Compute k.hashCode() and use it to find the bucket (array index).</li><li>In that bucket, traverse any entries: for each key k1, check k == k1 or k.equals(k1).</li><li>If a matching key is found, return its value; otherwise return null.</li></ol><p>HashMap uses hashCode(), == and equals() for entry lookup in this sequence.<br>A collision (two keys with the same bucket index) means multiple entries are chained (as a linked list or tree).</p><p>When inserting (put()), if an existing key in the bucket is .equals() to the new key, its value is replaced; if not, a new entry is added.</p><p>For example, if three distinct keys have identical hashCode(), the map will link them in the same bucket. If keys K1, K2, K3 all map to the same bucket (they share the bucket index), but equals() is false for each pair, so all three coexist as separate entries in that bucket.</p><p>In a HashSet, the same logic applies (a HashSet is backed by a HashMap internally). An element is considered already present if an existing element in the set is equals() to it and has the same hash code. Thus, correct overrides ensure that collections correctly identify duplicates and retrieve elements as expected.</p><h3>In-depth Interview Questions:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCpVALR9HeTE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCpVALR9HeTE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCpVALR9HeTE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3f11360fbea3ff21ff454bafebca7a6/href">https://medium.com/media/f3f11360fbea3ff21ff454bafebca7a6/href</a></iframe><ul><li><a href="https://www.javamadesoeasy.com/2015/02/overriding-equals-and-hashcode-method.html">Overriding equals and hashcode method - Top 18 Interview questions and answers in java for experienced and freshers</a></li><li><a href="https://medium.com/@AlexanderObregon/common-java-hashcode-interview-questions-and-answers-f079d305e629">Common Java Hashcode Interview Questions and Answers</a></li><li><a href="https://medium.com/@iyusubov444/interview-questions-java-equals-hashcode-methods-revisited-7b0cd80aa903">Interview Questions - Java equals &amp; hashCode Methods Revisited</a></li></ul><h3>Consequences of Incorrect Overrides</h3><p>Failing to override both methods correctly leads to subtle bugs:</p><ul><li><strong>Only </strong><strong>equals() overridden, no custom </strong><strong>hashCode():</strong> Two logically equal objects may end up in different buckets. If you put a key into a HashMap with a custom equals() but default hashCode(), retrieving with an “equal” new key fails (returns null). The objects compare as equal but their hash codes differ, so the lookup goes to the wrong bucket and doesn’t find the entry.</li><li><strong>Only </strong><strong>hashCode() overridden, default </strong><strong>equals():</strong> Here two logically equal objects have the same bucket, but equals()(identity check) sees them unequal. The map treats them as distinct keys. Even if hash codes match, a lookup still fails if equals() isn’t also overridden.</li><li><strong>Neither overridden (both default):</strong> Objects are only equal if they’re the same instance. This is rarely the desired “logical” equality, but it does not violate the equals–hashCode contract. It simply means each object is unique as far as collections are concerned.</li></ul><p>If you have two objects which are .equals(), but have different hash codes, you lose! In practice, you might not notice a problem immediately, but stored data can become inaccessible or keyed incorrectly.</p><h3>Overriding equals() and hashCode(): Examples</h3><p>Below is an illustrative example. Consider a simple Person class:</p><pre>public class Person {<br>    private String name;<br>    private int age;<br>    public Person(String name, int age) { ... }<br>    @Override<br>    public boolean equals(Object obj) {<br>        if (this == obj) return true;<br>        if (!(obj instanceof Person)) return false;<br>        Person other = (Person) obj;<br>        return age == other.age<br>            &amp;&amp; Objects.equals(name, other.name);<br>    }<br>    @Override<br>    public int hashCode() {<br>        return Objects.hash(name, age);<br>    }<br>}</pre><p>Here, equals() returns true when name and age match, and hashCode() uses the same fields. <br>If we did not override hashCode(), two Person(&quot;Alice&quot;,30) objects (equal by equals()) would likely have different default hashes (identity-based), breaking HashMap lookup.</p><p>Likewise, in hash-based collections:</p><pre>Map&lt;Person,String&gt; map = new HashMap&lt;&gt;();<br>map.put(new Person(&quot;Alice&quot;, 30), &quot;Engineer&quot;);<br>// Later…<br>String role = map.get(new Person(&quot;Alice&quot;, 30)); // returns &quot;Engineer&quot; only if equals/hashCode aligned</pre><p>Without the proper overrides, role would be null even though logically the key exists.</p><h3>Common Mistakes</h3><p>Programmers often err in the following ways:</p><ul><li><strong>Overriding one and not the other:</strong> As stressed above, this breaks the contract.</li><li><strong>Using mutable fields:</strong> Including fields that can change (like a dateModified or email) in equals()/hashCode() can break collections. For example, a Customer’s email is updated, changing its hashCode, so a previously stored key can’t be found. Use immutable fields in hashCode() or avoid mutable keys.</li><li><strong>Violation of symmetry/transitivity:</strong> For instance, using class inheritance unwisely: if subclass equals() compares only superclass fields, symmetry or transitivity can break.</li><li><strong>Inconsistent field use:</strong> Using different fields in equals() vs. hashCode() violates consistency. Both methods should be based on the <em>same</em> set of significant fields.</li><li><strong>Not checking for null/class:</strong> A bad equals() might throw a ClassCastException or return true for null inputs. Always return false for null and compare classes (as in standard recipes).</li><li><strong>Performance pitfalls:</strong> Including heavy computations or non-deterministic values (like current time) in hashCode()can degrade performance or violate consistency.</li></ul><p>Each of these mistakes has bitten developers, often only revealed by failing tests or customer issues. Libraries like EqualsVerifier can help catch many of these errors.</p><h3>Best Practices</h3><ul><li><strong>Override both or neither:</strong> If logical equality matters, implement <em>both</em> equals() and hashCode() together. Otherwise, use the default implementations.</li><li><strong>Use the same fields:</strong> Make sure that any field used in equals() also contributes to hashCode(). This keeps the contract intact.</li><li><strong>Prefer immutable keys:</strong> Immutable objects (like String, Integer, or custom objects with final fields) make excellent hash keys because their hash codes don’t change. If a class is mutable, be very cautious about using it as a key or storing it in sets.</li><li><strong>Use helper libraries:</strong> IDEs can auto-generate these methods correctly. Libraries like Apache Commons Lang (HashCodeBuilder/EqualsBuilder) or Lombok’s @EqualsAndHashCode reduce boilerplate and errors.</li><li><strong>Test your implementation:</strong> Tools like <strong>EqualsVerifier</strong> can automatically check that your equals()/hashCode() obey the contract and handle edge cases (null, symmetry, etc.). Always include unit tests for complex equals()logic.</li><li><strong>Domain-Driven Guidance:</strong> In Domain-Driven Design, <strong>value objects</strong> (objects defined by their data) should override equals()/hashCode(), whereas <strong>entities</strong> (objects with unique identity) may rely on their identity (ID) instead. This aligns with the idea that value objects are “equal by value” while entities are “equal by identity.”</li></ul><h3>Sources</h3><p>Theory:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJqOCsnu-Ios%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJqOCsnu-Ios&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJqOCsnu-Ios%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8cb3af95a36412bd2c924e678b80299/href">https://medium.com/media/c8cb3af95a36412bd2c924e678b80299/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fn-KC2WqvG_k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dn-KC2WqvG_k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fn-KC2WqvG_k%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/de845581efa7aee97a4f6d02d4f179ef/href">https://medium.com/media/de845581efa7aee97a4f6d02d4f179ef/href</a></iframe><p><a href="https://medium.com/@AlexanderObregon/javas-objects-equals-method-explained-3a84c963edfa">Java’s Objects.equals() Method Explained</a></p><p>Examples:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIwUwIrz9Ge8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIwUwIrz9Ge8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIwUwIrz9Ge8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba42425c9f3177d937f38c26af911912/href">https://medium.com/media/ba42425c9f3177d937f38c26af911912/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F3pAUtNuBLiw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D3pAUtNuBLiw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3pAUtNuBLiw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e66bfec017d7c1547648cab6edbb86a/href">https://medium.com/media/7e66bfec017d7c1547648cab6edbb86a/href</a></iframe><p>Interview questions:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FNr56SlbMed4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DNr56SlbMed4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FNr56SlbMed4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b55a50cfd2d3490074a3ef3d30c9c01/href">https://medium.com/media/0b55a50cfd2d3490074a3ef3d30c9c01/href</a></iframe><p>More deep dive?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwJgua6AobQU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwJgua6AobQU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwJgua6AobQU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/446238b933db12dd2b53e999418d2356/href">https://medium.com/media/446238b933db12dd2b53e999418d2356/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXhK6LG3JbFU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXhK6LG3JbFU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXhK6LG3JbFU%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f8de242eb799111c2cb971763d4e482/href">https://medium.com/media/5f8de242eb799111c2cb971763d4e482/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e99bc1066851" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-java-interview-playbook/equals-hashcode-methods-in-java-e99bc1066851">equals() &amp; hashCode() methods in Java</a> was originally published in <a href="https://medium.com/the-java-interview-playbook">The Java Interview Playbook</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Hibernate in Java — Part 2: Using class config]]></title>
            <link>https://mayankpant-dev.medium.com/working-with-hibernate-in-java-part-2-using-class-config-3a39999ee4ba?source=rss-35632dfbbe6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a39999ee4ba</guid>
            <dc:creator><![CDATA[Mayank Pant]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 09:28:29 GMT</pubDate>
            <atom:updated>2026-03-12T14:31:08.448Z</atom:updated>
            <content:encoded><![CDATA[<h3>Working with Hibernate in Java — Part 2: Using class config</h3><p><a href="https://medium.com/@mayankpant.dev/working-with-hibernate-in-java-part-1-using-xml-config-318708b53b86">Working with Hibernate in Java — Part 1: Using xml config</a></p><p>Similar to the above article, we want to connect to the database but we don’t want to use xml file, rather we want to store the configuration details inside a class so that it is more manageable.</p><p>To do this, we will create a new class: CustomPersistenceUnitInfo which implements PersistenceUnitInfo and override the methods, and provide what and where we want to connect to:</p><pre>public class CustomPersistenceUnitInfo implements PersistenceUnitInfo {<br>    @Override<br>    public String getPersistenceUnitName() {<br>        // persistence-unit name, similar to what we gave in xml file<br>        return &quot;my-persistence-unit&quot;;<br>    }<br><br>    @Override<br>    public String getPersistenceProviderClassName() {<br>        // We are telling which jpa implementation we are going to use<br>        return &quot;org.hibernate.jpa.HibernatePersistenceProvider&quot;;<br>    }<br><br>    @Override<br>    public String getScopeAnnotationName() {<br>        return &quot;&quot;;<br>    }<br><br>    @Override<br>    public List&lt;String&gt; getQualifierAnnotationNames() {<br>        return List.of();<br>    }<br><br>    @Override<br>    public PersistenceUnitTransactionType getTransactionType() {<br>        return PersistenceUnitTransactionType.RESOURCE_LOCAL;<br>    }<br><br>    @Override<br>    public DataSource getJtaDataSource() {<br>        // We also need a datasource as jpa does not handles connection to the database, it depends on a datasource to do that<br>        // We are going to use one of the best datasource out there, hikariCP<br>        HikariDataSource dataSource = new HikariDataSource();<br><br>        dataSource.setJdbcUrl(&quot;jdbc:mysql://localhost/jpa_2025_ch1&quot;);<br>        dataSource.setUsername(&quot;root&quot;);<br>        dataSource.setPassword(&quot;rootroot&quot;);<br>        return dataSource;<br>    }<br><br>    @Override<br>    public DataSource getNonJtaDataSource() {<br>        return null;<br>    }<br><br>    @Override<br>    public List&lt;String&gt; getMappingFileNames() {<br>        return List.of();<br>    }<br><br>    @Override<br>    public List&lt;URL&gt; getJarFileUrls() {<br>        return List.of();<br>    }<br><br>    @Override<br>    public URL getPersistenceUnitRootUrl() {<br>        return null;<br>    }<br><br>    @Override<br>    public List&lt;String&gt; getManagedClassNames() {<br>        return List.of(&quot;com.mayank.entities.Product&quot;);<br>    }<br><br>    @Override<br>    public boolean excludeUnlistedClasses() {<br>        return false;<br>    }<br><br>    @Override<br>    public SharedCacheMode getSharedCacheMode() {<br>        return null;<br>    }<br><br>    @Override<br>    public ValidationMode getValidationMode() {<br>        return null;<br>    }<br><br>    @Override<br>    public Properties getProperties() {<br>        return null;<br>    }<br><br>    @Override<br>    public String getPersistenceXMLSchemaVersion() {<br>        return &quot;&quot;;<br>    }<br><br>    @Override<br>    public ClassLoader getClassLoader() {<br>        return null;<br>    }<br><br>    @Override<br>    public void addTransformer(ClassTransformer classTransformer) {<br><br>    }<br><br>    @Override<br>    public ClassLoader getNewTempClassLoader() {<br>        return null;<br>    }<br>}</pre><p>Most of them returns null, but the ones we are going to use are explained in comments.</p><p>Next, we will use this class config when creating an EntityManagerFactory:</p><pre>EntityManagerFactory emf = new HibernatePersistenceProvider()<br> .createContainerEntityManagerFactory(new CustomPersistenceUnitInfo(), new HashMap&lt;&gt;());</pre><p>Rest of the code stays same as the previous article.</p><h3>Adding DataSorce Dependency</h3><p>Since we are configuring the datasource above, we need to add the dependency for that in our pom.xml:</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.zaxxer&lt;/groupId&gt;<br>  &lt;artifactId&gt;HikariCP&lt;/artifactId&gt;<br>  &lt;version&gt;5.0.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h3>DataSource</h3><p><strong>What is DataSource? Why do we need it?<br></strong>A DataSource is simply an object that gives Hibernate JDBC Connections: Connection conn = dataSource.getConnection();</p><p>Hibernate does not want to manage raw driver connections itself — too slow &amp; unsafe. So DataSource does:</p><ul><li>Opens connections for Hibernate</li><li>Provides connection pooling (very important!)</li><li>Reuses connections instead of creating new ones</li><li>Manages idle, max, and timeout settings</li></ul><p><strong>Hibernate ALWAYS needs a way to talk to the database</strong>, no matter how you configure it. There are only two ways to give Hibernate DB connection info: XML-based, and programmatic (class-based) configuration.<br>Either way, Hibernate cannot work unless it knows how to open DB connections.<br>So class-based configuration <strong>replaces</strong> persistence.xml, not the database setup.</p><p><strong>What does HikarCP do?<br></strong>HikariCP is a high-performance connection pool. Hibernate uses it to:</p><ul><li>Keep a pool of ready-made DB connections</li><li>Reuse them to avoid expensive reconnects</li><li>Manage lifecycle of connections</li><li>Handle max pool size, idle timeout, validation, leak detection, etc.</li></ul><p>It’s used because connections are very expensive (20–200ms).<br>Hikari makes them almost free (0.1–1ms reuse).</p><p>This is why Spring Boot defaults to Hikari.</p><h3>Why did we not pass datasource details when using persistence.xml?</h3><p>Because we relied on a default or container-managed DataSource. When we use:</p><pre>&lt;persistence-unit name=&quot;myPU&quot;&gt;<br>   &lt;provider&gt;org.hibernate.jpa.HibernatePersistenceProvider&lt;/provider&gt;<br>&lt;/persistence-unit&gt;</pre><p>Hibernate/JPA expects the environment (like Spring Boot, application server, etc.) to provide a DataSource automatically.</p><p>So even if persistence.xml has no datasource details, Spring Boot / Hibernate will inject one through JPA vendor adapters or in-memory database defaults, or fail with “No DataSource configured” error.</p><p><strong>Why do we need to pass DataSource details with class based config then?<br></strong>Because we are taking responsibility for giving Hibernate:</p><ul><li>JDBC URL</li><li>Driver</li><li>Username/password</li><li>Connection pool</li></ul><p>Because no external environment is helping.</p><p><strong>Programmatic == you configure everything manually.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a39999ee4ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StringBuffer, StringBuilder & StringTokenizer in Java]]></title>
            <link>https://mayankpant-dev.medium.com/stringbuffer-stringbuilder-stringtokenizer-in-java-ed6ce9398410?source=rss-35632dfbbe6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed6ce9398410</guid>
            <category><![CDATA[springbuilder]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[stringbuffer]]></category>
            <category><![CDATA[string-vs-stringbuilder]]></category>
            <dc:creator><![CDATA[Mayank Pant]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 05:44:19 GMT</pubDate>
            <atom:updated>2025-11-29T05:44:19.218Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@mayankpant.dev/string-in-java-explained-immutability-string-pool-tricky-interview-questions-222f81ae4547">String in Java Explained: Immutability, String Pool &amp; Tricky Interview Questions</a></p><h3>StringBuffer</h3><p>Why StringBuffer is needed? And what are the drawbacks of String?</p><p>When we have fixed content then we can use String, but when we have changing content then it is never recommended to use String. Because every modification will result into creation of a new object which will increase the memory utilization. To prevent this, we should use StringBuffer, as only one object will be created and we can modify the same object as many time as we want to. <em>All required changes will be performed in the same object only. For such type of requirement we should go for StringBuffer.</em></p><h3>StringBuffer constructors</h3><p>In case of StringBuffer there comes the concept of length and capacity. With String, we only have a fixed amount of chars that we can store and cannot change it, so there is only length. But StringBuffer can grow in size, so length gives us the actual size currently and capacity gives us the amount of characters that the object can hold.</p><p>By default StringBuffer has 16 capacity</p><p>StringBuffer sb = new StringBuffer(“durga”);</p><p>When the current capacity is filled, then a new StringBuffer object with capacity = (current capacity + 1) x 2 will be created and contents will be copied to it.</p><p>StringBuffer sb = new StringBuffer(int initialCapacity);<br>When we know that we want to store a large string then we can also explicitly pass the capacity.</p><p>StringBuffer sb = new StringBuffer(String s);<br>Internally the capacity in this case is calculated as: capacity = s.length() + 16. Had they not done this, then a string with length greater than 16 would require additional operations to be stored correctly.<br>Had they not added 16 then there would not be space for the sb to grow, it needed further resize which would be expensive.</p><h3>StringBuffer methods</h3><ul><li>public int length()</li><li>public int capacity()</li><li>public char charAt(int index): Gives StringIndexOutofBoundException in case of index out of bound, and not StringBufferIndexOutofBoundException as there is no such exception.</li><li>public void setCharAt(int index, char newChar): Replaces character at given index</li><li>public StringBuffer append(String s): Many overloaded methods for this for each data type. Adds data at last</li><li>public StringBuffer insert(int index, String s): Here also we can insert any data type to insert.</li><li>public StringBuffer delete(int index, int end): Deletes from start index to end — 1 index. Range deletion</li><li>public StringBuffer deleteCharAt(int index):</li><li>public StringBuffer reverse()</li><li>public void setLength(int length): Remove additional characters and only takes those which fall in the specified length. If current length is less than passed length then empty spaces will be added.</li><li>public void ensureCapacity(int capacity): Sets the capacity for sb object</li><li>public void trimToSize(): To deallocate extra memory given to a sb. Maybe you initialized with greater capacity and don’t need that now. Extra memory will be deallocated.</li></ul><h3>StringBuilder</h3><p>StringBuffer had a problem. Every method in StringBuffer is synchronized, meaning it is thread safe. This meant that it is slower in a multi-threaded environment. To overcome this, StringBuilder was introduced in 1.5v of Java.</p><p>Everything is similar to StringBuffer, only difference being that no method are synchronized. Else all the constructors and methods are same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UuFKjDlld1e6q2fZhkcZQ.png" /></figure><h4>String vs StringBuffer vs StringBuilder</h4><p>When content is fixed and won’t change frequently, go for String.<br>When content is not fixed, keeps on changing, but thread safety is required, then go for StringBuffer.<br>When content is not fixed, keeps on changing, but we don’t want thread safety, then go for StringBuilder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhzZrAnyHjbPWIGBKLLqpQ.png" /></figure><h4>Is String thread-safe?</h4><p>Not only String, but all immutable objects in Java are by-default thread safe because no one is allowed to do any modification on the object.</p><h4>Method Chaining</h4><p>In almost all methods of String, StringBuffer, and StringBuilder the return type is of the same type. So we can chain additional methods to the output of the previous operation, hence forming a method chain.</p><h3>StringTokenizer</h3><p>What is String tokenization and how it is possible to perform String Tokenization in Java Applications?</p><p>The process of dividing a string into tokens is called as String Tokenization.</p><p>To perform String Tokenization Java has provided a predefined class in the form of java.util.StringTokenizer class.</p><p>To perform String Tokenization in java applications we have to use the following steps:</p><ul><li>Create StringTokenizer Class Object: To create StringTokenizer class object we have to use the following constructor: public StringTokenizer(String data)</li><li>Ex: StringTokenizer st = new StringTokenizer(“Durga Software Solutions”);</li><li>When JVM encounter the above instruction, it will take the provided String and divide the provided String into no of tokens and JVM will store the generated tokens by creating object for StringTokenizer class.</li></ul><p>NOTE: When StringTokenizer class object is created with the no of tokens then a pointer or cursor will be created before the first token.</p><p>To get no of tokens in StringTokenizer class object we have to use the following method: public int countTokens()</p><p>To retrieve Tokens from StringTokenizer Object:</p><ul><li>Check whether more tokens are available or not from the current cursor position by using the following method: `public boolean hasMoreTokens()`</li><li>It will return true value if at-least next token exists</li><li>It will return false value if no more tokens are there</li><li>If at-least next token is available then it reads next token and moves cursor to next position by using the following method: public String nextToken()</li></ul><pre>import java.util.*;<br>class Test {<br> public static void main(String[] args) {<br>  StringTokenizer st = new StringTokenizer(&quot;Durga Software Solutions&quot;);<br>  System.out.println(&quot;No Of Tokens:&quot;+st.countTokens());<br>  while(st.hasMoreTokens()) {<br>   System.out.println(st.nextToken());<br>  }<br> }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGLTKIHM-rregPh26f_sIg.png" /></figure><h3>Interview Questions</h3><p><strong>Q:: What is the difference between `String` and `StringBuffer`?<br></strong>Ans:: String class objects are immutable objects, and immutable objects do not allow modifications over their content. If we are trying to perform modifications over immutable object then operations are allowed, but, the resultant data will not be stored back in original object, it will be stored by creating new object.<br>StringBuffer objects are mutable objects, they allow modifications on their content.</p><p><strong>Q:: What are the differences between StringBuffer and StringBuilder?<br></strong>Ans::</p><ul><li>StringBuffer class was introduced in JDK1.0 version. StringBuilder class was introduced in JDK5.0 version.</li><li>StringBuffer is synchronized. StringBuilder is not synchronized.</li><li>Almost all the methods are synchronized in StringBuffer. No method is synchronized in StringBuilder.</li><li>StringBuffer is able to allow only one thread to access data. StringBuilder is able to allow more than one thread to access data.</li><li>StringBuffer is following sequential execution. StringBuilder is following parallel execution.</li><li>StringBuffer will increase execution time. StringBuilder will reduce execution time.</li><li>StringBuffer will reduce application performance. StringBuilder will increase application performance.</li><li>StringBuffer is able to give guarantee for Data Consistency. StringBuilder is unable to give guarantee for data consistency.</li><li>StringBuffer is thread safe. StringBuilder is not thread safe.</li></ul><p><strong>Q:: What is the difference between the following 2 Statements<br></strong>a) String str = new String(“Durga Software Solutions”);<br>b) String str = “Durga Software Solutions”;</p><p>Ans:: To create String class object if we use first statement then one String object will be created at heap memory as per new keyword and another String object will be created at String Constant Pool Area inside heap memory as per string literal.<br>To create String object, if we use second statement, then String object will be created at String Constant Pool Area only.</p><p>Note: The objects which are created in String Constant Pool Area are not eligible for Garbage Collection. The objects which are created in Heap memory are eligible for Garbage Collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVh0TroRO3sz-JD66jZPFw.png" /></figure><p>Q:: What is the difference between == Operator and `equals()`Method?</p><p>Ans:: == is basically a comparison operator, it will check whether the provided operand values are same or not, where operands may be normal primitive variables or object reference variables.<br>equals() method is defined in java.lang.Object class, it is implemented in such a way that it provides comparison between two object reference values.<br>String class has overridden Object class equals() method in such a way such that it provides comparison between two String objects content.</p><pre>class A {}<br><br>class Test {<br> public static void main(String[] args) {<br>  A a1=new A();<br>  A a2=new A();<br>  <br>  int i=10;<br>  int j=10;<br>  <br>  String str1=new String(&quot;abc&quot;);<br>  String str2=new String(&quot;abc&quot;);<br>  <br>  System.out.println(i == j);// true: as primitive, so checks value<br>  System.out.println(a1 == a2);// false<br>  System.out.println(str1 == str2);// false<br>  System.out.println(a1.equals(a2));// false<br>  System.out.println(str1.equals(str2));//true<br> }<br>}</pre><h3>How String Interning Works</h3><p>Java provides the intern() method to manually add strings to the pool:</p><pre>String fifth = new String(&quot;hello&quot;).intern(); <br>String sixth = &quot;hello&quot;; <br> <br>System.out.println(fifth == sixth); // true</pre><p>Here, fifth is initially created as a separate object, but calling intern()checks the string pool for an existing ”hello”. Since it is already present, fifth is redirected to the pooled instance instead of keeping its separate allocation.</p><p>Interning is useful when working with dynamically created strings that should match pooled literals. For example, strings loaded from a database or generated at runtime won’t automatically be part of the pool unless explicitly interned.</p><h3>How the String Pool Is Managed</h3><p>The string pool is part of the JVM’s method area (also known as the runtime constant pool). In older Java versions (before Java 7), it was stored in the permanent generation (PermGen) space. Starting with Java 7, it was moved to the heap, allowing it to grow as needed.</p><p>Because the pool stores only one copy of each literal, it helps reduce redundant objects in memory. However, excessive interning of non-repeating strings can lead to increased memory usage. Interned strings are never garbage-collected unless they have no remaining references in the program. Too many unique interned strings can put pressure on the heap.</p><h3>String Pool Size and Java Versions</h3><p>The string pool has changed over different Java versions. As mentioned earlier, before Java 7, the string pool was in the fixed-size PermGen space, which could cause OutOfMemoryError. Java 7 moved it to the heap for dynamic growth.</p><p>From Java 7 onward, the pool was moved to the heap, allowing it to grow dynamically based on application needs. This change made interning safer, but it also means that excessive interning of unique strings can still lead to higher heap consumption.</p><h3>Handling Empty and Null Strings</h3><p>In Java, it’s crucial to differentiate between an empty string and a null reference. An empty string (””) is a valid string object with a length of zero, whereas a null string doesn’t refer to any object. Checking for both conditions is a common practice to avoid `NullPointerException`:</p><pre>String emptyString = &quot;&quot;; <br>String nullString = null; <br> <br>// Check for empty string <br>if (emptyString.isEmpty()) { <br> System.out.println(&quot;String is empty&quot;); <br>} <br> <br>// Check for null string <br>if (nullString == null) { <br> System.out.println(&quot;String is null&quot;); <br>}</pre><h3>Regular Expressions</h3><p>Java supports regular expressions through the `java.util.regex` package, which includes the Pattern and Matcher classes. Regular expressions provide a powerful way to search, edit, and manipulate text based on pattern matching.</p><pre>String text = &quot;Java 123 JavaScript&quot;; <br>Pattern pattern = Pattern.compile(&quot;\\d+&quot;); // Pattern to match one or more digits <br>Matcher matcher = pattern.matcher(text); <br> <br>while (matcher.find()) { <br> System.out.println(&quot;Found a number: &quot; + matcher.group()); // Outputs &quot;123&quot; <br>}</pre><h3>String Formatting</h3><p>Java also offers the String.format() method and the java.text.MessageFormat class for formatting strings, which is particularly useful for creating strings with variable data in a readable manner.</p><pre>String formattedString = String.format(&quot;My favorite language is %s!&quot;, &quot;Java&quot;); <br>System.out.println(formattedString); // Outputs &quot;My favorite language is Java!&quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed6ce9398410" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String in Java Explained: Immutability, String Pool & Tricky Interview Questions]]></title>
            <link>https://mayankpant-dev.medium.com/string-in-java-explained-immutability-string-pool-tricky-interview-questions-222f81ae4547?source=rss-35632dfbbe6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/222f81ae4547</guid>
            <category><![CDATA[string]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tricky-questions]]></category>
            <category><![CDATA[string-pool]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Mayank Pant]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 18:21:41 GMT</pubDate>
            <atom:updated>2025-12-02T23:58:57.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>Importance of String</h3><p>String related questions are a must ask in interviews.</p><p>In certifications, there are around 20 questions either directly or in-directly related to Strings.</p><h3>String Class</h3><p>String, by definition are just sequence of characters. The String class also implements the same and internally it stores the values in a char array.</p><p>Let’s start from the very basics:<br>When we write String name = “Mayank Pant” then we are saying that, we have a reference variable called name of type String and we know that this is a reference variable as it points to the String that we store.</p><p>So in String name = “Mayank Pant&quot;<br>String = Data type class<br>name = reference variable<br>”Mayank Pant” = an object</p><p><strong>How does it work internally?</strong><br>When we write the following code, use the image below to guess what will happen in memory:</p><pre>String a = &quot;Mayank&quot;;<br>String b = &quot;Mayank&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMjpPY1c6W2xPwcvPwON4Q.png" /></figure><p>Here 2 concepts that come into play: String Pool, and Immutability</p><p>String Pool is basically a separate space in heap memory to store Strings. It stores strings in such a way that if there are 10 strings with the same value, say “Mayank”, then only one String will be created in string pool and all the reference variables will point to this value only. So, in the diagram, the first one is correct. String pool is there for optimization.</p><p>Immutability is a concept where we are not allowed to change the value of a variable, or the language does not allow that. Immutability is there for security reasons.</p><p>Q:: In the above, what if we change the value of “Mayank” to “Mayank Pant” using the variable a, will it change the value for b variable as well since they were pointing to the same value?</p><p>Ans:: NO! The answer is immutability. Since String object are immutable, we can’t change this object.</p><p>Q:: In this example, are we changing the value of name variable?</p><pre>String name = &quot;Mayank&quot;;<br>System.out.println(name);<br>name = &quot;Mayank Pant&quot;;<br>System.out.println(name);</pre><p>Ans:: NO! We are creating a new String object, and our name variable is pointing to this value now and the old value is as is, but if no one is referencing this then it will be garbage collected.</p><h4>Why immutability?</h4><p>For security reasons. <br>Say for example, 10 people have name as “Mayank”, so each will point to just one String object in memory. But if someone thinks to change their name, then it will create a new String object in memory and keep the original value untouched. This helps as one person deciding to change his name does not lead to a changed name for everyone.</p><p>This is what I imagine Java developers were thinking when they created this:<br>“We need to optimize memory. A lot of String objects are being created. Let’s just keep Strings in a sort of Set — no duplicate values. If the same value comes in, it can simply point to the previously created one. Yes! This works, memory usage is reduced now.<br>But… but a user changed their name, and suddenly everyone who was using the old name ended up with the new one. We can’t let that happen. Make the object immutable! Great, now everything is under control.<br>But what if someone wants to change their value? Ahhh… just create a new String object and keep the old one unchanged.”</p><p><a href="https://javarevisited.blogspot.com/2010/10/why-string-is-immutable-or-final-in-java.html">Why String is Immutable or Final in Java? Explained</a></p><h3>String comparison</h3><pre>String a = &quot;Mayank&quot;;<br>String b = &quot;Mayank&quot;;<br>SOUT(a == b); // True</pre><p>We can compare Strings this way. <br>This “==” operator checks if both the variable is pointing to the same object or not. If not, it will return false.</p><p>Q:: But same value object will be stored only once and variables will point to this same object, so this will always return true. Is there a way to create multiple objects of same value?</p><p>How to create different objects of same value?<br>We can say to the compiler that I don’t care about the optimization that you are doing, I want you to create different objects for same value, I don’t care if it’s already in string pool or not. We are explicitly saying this.<br>String c = new String(“Mayank”);<br>Now, this new object will be stored outside of string pool, but in heap memory.<br>Now if we do a == c then this will return false, as both the variables are pointing to different objects. So this “==” operator does not check values, it only compares if they are pointing to same object or not.</p><p>Q:: How to only compare values?<br>Using .equals() method which we can override and use according to our need.</p><p><a href="https://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html">Difference between equals method and &quot;==&quot; operator in Java - Interview Question</a></p><h3>Printing Strings</h3><p>When we call the System.out.println() method and pass in any value, it may be int, string, or array, then for each of this there is a overloaded method present in println() and internally it calls the toString() method to get the string representation of the passed value. And then it simply prints this string representation onto the provided output like cli.</p><p>We have the ability to override this `toString` method to pretty print in a way that we like.</p><pre>SOUT(new int[] {1, 2, 3, 4}); // Prints out giberish<br>SOUT(Arrays.toString(new int[] {1,2, 3, 4})); // Pretty prints the array according to overriden method in Arrays</pre><p><strong>Using printf to print according to your needs:</strong><br>We have different placeholders which we can use according to our need. Example: To print float value upto 2 decimal places, we use %.2f.</p><pre>float value = 1332.168f;<br>System.out.printf(&quot;Value: %.2f&quot;, value);<br>String name = &quot;Mayank&quot;;<br>System.out.printf(&quot;Name is: %s and surname is %s&quot;, name, &quot;Pant&quot;);</pre><h3>Concatenation</h3><p>What happens when we use the + operator with different data types? <br>When using char value, it’s converted first to its ascii equivalent and then operation is performed. <br>In case of Strings, they are not converted, so concatenation occurs.</p><pre>SOUT(&#39;a&#39; + &#39;b&#39;); // 195<br>SOUT(&quot;a&quot; + &quot;b&quot;); // ab<br>SOUT(&#39;a&#39; + 3); // 100 -&gt; which is ascii value of d<br>SOUT(&quot;a&quot; + 1); // a1 → int value will be converted to wrapper class Integer that will call toString<br>// After a few steps it becomes SOUT(&quot;a&quot; + &quot;1&quot;). Similarly below examples<br>SOUT(&quot;a&quot; + new ArrayList&lt;&gt;()) // a[] -&gt; as ArrayList toString method will be called and it returned []<br>SOUT(5 + new ArrayList&lt;&gt;()); // ERROR<br>SOUT(5 + &quot;&quot; + new ArrayList&lt;&gt;()); // 5[]</pre><p>So we can say that the System.out.println() method takes an expression where it can operate on primitive types. <br>Complex types are also applicable but the only condition is there should be atleast one String as well. And if there is one string in operation then the result will be concatenation.</p><p>The + operator is overloaded for String type. Operator overloading.<br>Operator overloading is not supported in Java as it leads to poor code, for example in C/C++ we can overload operator to do anything. So, Java implicitly provides operator overloading just for + operator that too for String type to support string concatenation.</p><h3>String Performance</h3><p>Take for example, we want a string that has n character, here n = 26.</p><pre>String res = &quot;&quot;;<br>for(int i = 0; i &lt; 25; i++) {<br> char ch = (char)(&#39;a&#39; + i);<br> res += ch;<br>}<br>SOUT(res);</pre><p>But here, for each iteration a new string object will be created as they are immutable. And all the previous strings, other than the final one are all a memory waste. In these cases we require a class that is mutable and allows addition of new chars easily without increasing the time complexity. Example: StringBuilder, StringBuffer.</p><h3>Methods of String Class</h3><p><a href="https://dev.java/learn/numbers-strings/strings/">Strings - Dev.java</a></p><h3>String Questions</h3><p>Q:: String vs StringBuffer — Mutability vs immutability and what will be the output of below code:</p><pre>String s = &quot;Durga&quot;<br>s.concat(&quot;Soft&quot;);<br>SOUT(s);<br><br>StringBuffer sb = new StringBuffer(&quot;Durga&quot;);<br>sb.append(&quot;Soft&quot;);<br>SOUT(sb);</pre><p>Q:: Double equal operator vs equals method. Also, output of the following:</p><pre>String s1 = new String(&quot;Durga&quot;);<br>String s2 = new String(&quot;Durga&quot;);<br><br>SOUT(s1 == s2); // False<br>SOUT(s1.equals(s2)) // True<br><br>StringBuffer sb1 = new StringBuffer(&quot;Durga&quot;);<br>StringBuffer sb2 = new StringBuffer(&quot;Durga&quot;);<br><br>SOUT(sb1 == sb2); // False<br>SOUT(sb1.equals(sb2)); // False</pre><p>Thinking of solution: String object created using new keyword, so outside of String pool, hence 2 different objects. So first SOUT will be false as they point to different objects. Since operator overloading is not there in java so for StringBuffer also same applies and first SOUT will be false.<br>For second SOUT, in String it will be true as both values are equal. In case of StringBuffer they might have overridden the equals method.</p><p>Correct answer for it:<br>equals() method comes from the Object class and the main reason for it is for comparing two object reference (not values). <br>In String class it is overridden to compare values rather than reference. <br>But in StringBuffer it is not overridden, so Object class equals() method will be called which was originally designed for reference comparison, and hence second SOUT for SB results in false.</p><p><strong>But why is it not overridden?</strong></p><ul><li>Mutability: StringBuffer objects are designed to be mutable, meaning their content can be changed after creation. If equals() were overridden to compare the content, the equality of two StringBuffer objects could change over time. This violates the equals() contract, which requires consistency: if two objects are equal, they should remain equal unless one of them is modified.</li><li>Reference Equality is Often Sufficient: In most scenarios where StringBuffer is used, comparing references (using double equals) is the desired behavior. Developers typically care if two StringBuffer variables point to the exact same object in memory rather than whether two distinct StringBuffer objects happen to contain the same sequence of characters at a given moment.</li><li>Problems with hashCode(): If equals() were overridden based on content, hashCode() would also need to be overridden to maintain the contract that equal objects must have equal hash codes. However, for mutable objects like StringBuffer, the hash code would change whenever the content changes. This poses significant issues when using StringBuffer objects as keys in hash-based collections (like HashMap or HashSet), as the object could become “lost” in the collection if its hash code changes after insertion.</li></ul><p>Q:: Heap vs String constant pool — How many objects will be created for each statement String s = new String(“Durga”); and String s2 = “Soft”</p><p>Ans:: For first statement, since new keyword is used, so an object will be created in heap memory for sure and s will reference this object only. But in the back end, JVM will also create a string object in the string pool memory as a string literal value is used. This will be stored for future purposes.<br>For the second statement, since we have a string literal, so an object will be created in SCP location. <br>So, 2 objects (1 in heap and 1 in SCP) for first statement, and 1 object (in SCP) for second statement.</p><p>Q:: Where is this SCP located?</p><p>Ans:: Till Java 1.6v in PermGen / Method Area<br>From 1.7v, somewhere in Heap for memory optimization so that it can grow freely.</p><p>Q:: How many object will be created in total for the below code?</p><pre>String s1 = new String(&quot;Durga&quot;);<br>String s2 = new String(&quot;Durga&quot;);<br>String s3 = &quot;Durga&quot;;<br>String s4 = &quot;Durga&quot;;</pre><p>Ans:: First statement: 2 objects, 1 in heap and 1 in SCP for future reference.<br>Second statement: 1 object in heap but none in SCP as the string with same value already exists there.<br>Third statement: 0 since same value string in SCP already exists. <br>Fourth statement: similar to third<br>Total = 3 objects</p><p>Q:: How many objects will be created by below code?</p><pre>String s = new String(&quot;Durga&quot;);<br>s.concat(&quot;Software&quot;);<br>s = s.concat(&quot;Solutions&quot;);</pre><p>Ans:: 1st - 2 object, 1 in heap and 1 in SCP.<br>2nd - Since string literal is present, so “Software” will be stored in SCP. Another object “DurgaSoftware” will be created in heap<br>3rd - “Solutions” will be stored in SCP. Another object “DurgaSolutions” will be created in heap and s will reference this new value.<br>Total: 6 objects</p><p>Q:: How many objects created for below code?</p><pre>String s1 = new String(&quot;Spring&quot;);<br>s1.concat(&quot;Fall&quot;);<br>String s2 = s1.concat(&quot;Winter&quot;);<br>s2.concat(&quot;Summer&quot;);<br>SOUT(s1);<br>SOUT(s2);</pre><p>Ans:: Output - 8 objects</p><p>Q:: Find output of following code and explain it</p><pre>String s1 = new String(&quot;You cannot change me&quot;);<br>String s2 = new String(&quot;You cannot change me&quot;);<br>SOUT(s1 == s2); <br>// False; address comparison, outside of SCP hence different<br><br>String s3 = &quot;You cannot change me&quot;; // Already exists in SCP due to above code<br>SOUT(s1 == s3); <br>// False; Location are different, one in SCP other in heap<br><br>String s4 = &quot;You cannot change me&quot;;<br>SOUT(s3 == s4); <br>// True; both are literal, in SCP, are same value, hence true<br><br>String s5 = &quot;You cannot&quot; + &quot; change me&quot;; // Will be evalueated at compile time only, hence interpreted as whole string<br>SOUT(s4 == s5); // True<br><br>String s6 = &quot;You cannot&quot;; // created in SCP<br>String s7 = s6 + &quot; change me&quot;; // if atleast one variable is there in expression then it will be calculated at runtime<br>// &quot;change me&quot; will be first created in SCP. Then &quot;You cannot change me&quot; since computed at run time will be a new object stored in the heap. Internally it uses StringBuilder to create the string, hence different objects<br><br>SOUT(s4 == s7); <br>// False; s7 is in heap<br><br>final String s8 = &quot;You cannot&quot;; // Since literal, will be stored in SCP first, but that value is already there<br>String s9 = s8 + &quot; change me&quot;; // since s8 is final meaning that it&#39;s value will not change, hence final variables value are put in at compile time only. Hence this expression will be evaluated at compile time and becomes similar to s5.<br><br>SOUT(s4 == s9); <br>// True</pre><p>Q:: What will be output of following code</p><pre>String s1 = new String(&quot;durga&quot;);<br>String s2 = s1.toUpperCase();<br>String s3 = s1.toLowerCase();<br>SOUT(s1 == s2); // False<br>SOUT(s1 == s3); // True</pre><p>Ans:: At runtime, after performing the operation, if there is no change in the string then no new object will be created. The variable will point to existing one only. This rule is same whether the object is in heap or SCP area.</p><p>Q:: What will be output of following code</p><pre>String s1 = &quot;durga&quot;; // in SCP<br>String s2 = s1.toString(); // since at runtime there is no change to object so s2 will point to same object, it does not matter where this object is, if no change at runtime, same object will be used<br><br>String s3 = s1.toLowerCase(); // since no change to string, s3 will also point to same object, does not matter where it is<br>String s4 = s1.toUpperCase(); // string changed, new object will be created, since it is at runtime so it will be in heap<br><br>SOUT(s1 == s2); // True<br>SOUT(s1 == s3); // True<br>SOUT(s1 == s4); // False</pre><p>Ans:: Internally toLowerCase checks if there are any uppercase chars or not. If not, then no changes needs to be made and hence it returns the same object.</p><p><strong>Q: Why SCP is available only for String but not for StringBuffer?<br></strong>Ans: String is widely used in each and every program and hence there are special privileges, whereas StringBuffer is rarely used and hence no special privileges. <br>Example: You go to a shop daily and once a while you forget your wallet but you still get udhaar, this is like String, special privileges. But if you go to shop once a year and ask for udhaar then there will be nothing of that sort as you are not a frequent buyer, so no privileges. Like StringBuffer.</p><p><strong>Q: Why String objects are immutable, and StringBuffer are mutable?<br></strong>Ans: Because of SCP, String object will be referenced by multiple objects, and to prevent one reference from changing value for all other reference immutability concept is necessary. <br>In StringBuffer each object is referenced by a single reference variable and hence changing value will not affect others, so immutability concept is not required.</p><p><strong>Q: In addition to String are there any other immutable objects in Java?<br></strong>Ans: Yes! All 8 wrapper class objects are immutable as there is the concept of reusing the values there also.</p><h3>Importance of SCP</h3><ul><li>Memory optimization / utilization: Take for example a registration form where each voter has to fill in their name, city, etc. Now there might be 1 crore people living in a city and if we create new object for each occurrence then we will have 1 crore object just for city name and we will run out of memory. This problem is solved in Java using SCP concept, which holds only one object for single value and 1 crore variable can reference that object, saving massively on memory.</li><li>Immutability: Since 1 crore variables are referring to a single object so we need a way so that when a variable changes it’s value it does not change for others. So immutability was introduced in SCP area. Changes made by a variable will be made to a new string object and it will then point to that object. Immutability is there for SCP. If no SCP, no immutability is required.</li></ul><h3>Important Constructors of String class</h3><ol><li>String s = new String(): Default constructor</li><li>String s = new String(String literal); : We can pass a string literal value to the constructor also</li><li>String s = new String(StringBuffer sb);: If we want to make String object using a StringBuffer object</li><li>String s = new String(StringBuilder sb);</li><li>String s = new String(char[] ch);: String is just a char array, so we can pass it to its constructor to create a string object from it as well</li><li>String s = new String(byte[] b);</li></ol><h3>Important methods of String class</h3><ol><li>public boolean isEmpty()</li><li>public int length()</li><li>public String replace(char old, char new);: Every old occurrence will be replaced with new one.</li><li>public String substring(int i);: Returns a substring of a string starting from index i to the end index</li><li>public String substring(int begin, int end);: Returns a substring of a string starting from index begin upto the index end — 1</li><li>public int indexOf(char ch);: Returns the index of passed char in the string. If not found, returns -1. If multiple occurrences are there, returns the first one.</li><li>public int lastIndexOf(char ch);</li><li>public String toLowerCase();</li><li>public String toUpperCase();</li><li>equals(), equalsIgnoreCase()</li><li>public String trim(): When you want to remove spaces from beginning and end of a String. Does not remove blank spaces from middle.</li></ol><h3>Create your own immutable class</h3><p>Immutable object are those whose value once set cannot be changed. If you try to change the value, you will get a new object with updated value. <br>We want to create such a class, that if new value is passed, new object is returned but if no value change is there then same object will be returned:</p><pre>class Immu{<br> private int value;<br> <br> public Immu(int val) {<br>  value = val;<br> }<br> <br> public Immu modify(int val) {<br>  if(this.value == val) {<br>   return this;<br>  } else {<br>   return new Immu(val);<br>  }<br> }<br>}<br><br>Immu obj1 = new Immu(10);<br>Immu obj2 = obj1.modify(100); // since values are different so new object will be created<br>Immu obj3 = obj1.modify(10); // same values; so same object will be returned<br><br>SOUT(obj1 == obj2); // False<br>SOUT(obj1 == obj3); // True</pre><p>Due to this modify method, our Immu class is now immutable. <br>In String class, every method is implemented in this way only, making String class immutable.<br>To not allow others to change the class by overriding the behaviour we should make the class as final. All immutable class should be defined as final. String is also final.</p><h3>Final vs Immutable</h3><p>Can I declare the StringBuffer reference variable as final and then I will get an immutable object?<br>Ans:: No! Final is different and immutability is different. Immutability is concept of objects, final is for reference variables.</p><pre>final StringBuffer sb = new StringBuffer(&quot;durga&quot;);<br>sb.append(&quot;software&quot;);<br>SOUT(sb);</pre><p>The output of above code is “durga software” and this proves that using final keyword does not make the object as immutable. The final keyword just stops the reference variable from being re-assigned to some other object. To prove that we cannot re-assign a final variable, if we add the below code:</p><pre>sb = new StringBuffer(&quot;solutions&quot;);</pre><p>It should give a compile time error that we cannot re-assign a final variable. And hence final is for reference variable, and immutability is for objects. <br>StringBuffer object cannot be made immutable because they are made for mutability purpose, if you want to change it, you will have to change each and every method implementation in StringBuffer.</p><h4>Which of the following are meaningful?</h4><ol><li>final variable // True</li><li>final object</li><li>immutable variable</li><li>immutable object // True</li></ol><h3>Interview Questions</h3><ul><li><a href="https://javarevisited.blogspot.com/2012/10/10-java-string-interview-question-answers-top.html">Top 15 Java String interview Question Answers for 3 to 5 Years Experienced</a></li><li><a href="https://javarevisited.blogspot.com/2013/07/java-string-tutorial-and-examples-beginners-programming.html">10 Things Every Java Programmer Should Know about String</a></li></ul><h3>Sources</h3><p>Basics:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzL1DPZ0Ovlo%3Fstart%3D104%26feature%3Doembed%26start%3D104&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzL1DPZ0Ovlo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzL1DPZ0Ovlo%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0555a5523b11dab46c831917d2fdf847/href">https://medium.com/media/0555a5523b11dab46c831917d2fdf847/href</a></iframe><p>Deep Dive — Most Important:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLd3UqWTnYXOlrdBwt2DTnF3u3W-1Kozk0&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLd3UqWTnYXOlrdBwt2DTnF3u3W-1Kozk0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGnpEm89Y0fg%2Fhqdefault.jpg%3Fsqp%3D-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE%3D%26rs%3DAOn4CLDCdASyOfPEFvXKcanyAliSozA3Ig%26days_since_epoch%3D20421&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/586cf35bb2a0490f200073470990dcae/href">https://medium.com/media/586cf35bb2a0490f200073470990dcae/href</a></iframe><p>Crash Course:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FHvpUTLSt5XM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DHvpUTLSt5XM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FHvpUTLSt5XM%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0d1bed1ff830ea9da3ac9538d13bd11/href">https://medium.com/media/c0d1bed1ff830ea9da3ac9538d13bd11/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=222f81ae4547" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in Java: Process vs Thread]]></title>
            <link>https://mayankpant-dev.medium.com/multithreading-in-java-process-vs-thread-64ff1cfd8933?source=rss-35632dfbbe6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/64ff1cfd8933</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Mayank Pant]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 17:48:58 GMT</pubDate>
            <atom:updated>2025-11-27T17:48:58.311Z</atom:updated>
            <content:encoded><![CDATA[<p>I struggled with this topic for a long time. I read dozens of articles, watched videos, and still felt like I didn’t truly get it. I could repeat the definitions, but the mental model was missing.</p><p>I could understand higher-level multithreading concepts, but the moment the interviewer asked “What’s the difference between a process and a thread?”, I froze.</p><p>Until now.</p><p>After exhausting ChatGPT, Grok, and Gemini for explanations, I finally built a mental model that sticks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qh3amxTOCRTlcUodRiaY6w.png" /><figcaption>Process (container) vs Thread (execution unit)</figcaption></figure><h4>Process</h4><p>Think of your house, an isolated entity which has its own rooms, furniture, layout, and utilities. Nothing outside the house can randomly walk in and touch your stuff. It does not depend on outer things.</p><p>Process is similar to your house. It is a fully isolated container with its own:</p><ul><li>Code Segment</li><li>Heap</li><li>Stack</li><li>Data Segment</li><li>It’s own resources like: File handles, network connections, OS objects, environment variables.</li><li>Its own runtime context: CPU registers, Program counter, OS-level PCB (Process Control Block)</li></ul><p><strong>And no other process can touch it directly. This isolation is what makes security &amp; stability possible.</strong></p><p>Let’s also look at the key properties of process:</p><p><strong>Heavyweight</strong> → Takes more OS time to create.</p><p><strong>Full isolation</strong> → One process crashing usually doesn’t kill others.</p><p><strong>Interprocess communication (IPC)</strong> is needed for communication:</p><ul><li>Pipes</li><li>Sockets</li><li>Shared memory</li><li>Message queues</li></ul><h3>Thread</h3><p>A thread is a smaller execution unit that lives inside a process. I think of it like a worker inside the house who shares all the rooms and furniture.</p><p>Every process must have at least one thread -&gt; the “main” thread.</p><p>All the threads in same process share things with each other like:</p><ul><li>Same heap memory</li><li>Same static variables</li><li>Same open files</li><li>Same network sockets</li><li>Same code</li></ul><p>But each thread also gets its own:</p><ul><li>Thread stack</li><li>Program counter</li><li>CPU register state</li><li>Local variables</li></ul><p>This is why:</p><ul><li>One thread crashing can kill the whole process</li><li>But one thread blocking doesn’t stop others</li></ul><h3>Why do threads exist?</h3><p>Threads allow:</p><ol><li><strong>Parallel execution</strong> (multi-core CPUs)<br>Each thread can run on a different core.</li><li><strong>Concurrency</strong><br>Multiple tasks appear to run at once, even on single-core CPUs via time slicing.</li><li><strong>Faster context switching</strong><br>Switching between threads is cheaper than switching between processes.</li><li><strong>Shared memory communication</strong><br>Threads share data instantly, unlike isolated processes.</li></ol><h3>Real-world example</h3><p>Imagine you use a browser:</p><p>🟥 <strong>Process</strong> = Chrome<br>🟨 <strong>Threads</strong> =</p><ul><li>1 thread renders the page</li><li>1 thread fetches data</li><li>1 thread handles input</li><li>1 thread runs JS engine</li></ul><p>All share memory → fast<br>If one misbehaves → can crash tab</p><h3>CPU Scheduling Difference</h3><h4>Process scheduling</h4><ul><li>Context switch is heavy</li><li>OS saves &amp; restores entire memory context</li><li>Expensive for the CPU</li></ul><h4>Thread scheduling</h4><ul><li>Lightweight</li><li>Only a small CPU register set + program counter needs switching</li><li>Very fast</li></ul><h3>Safety &amp; Race Conditions</h3><p>Because threads share memory, they can conflict:</p><pre>Thread A reads x<br>Thread B writes x<br>Thread A writes x<br>Thread B writes x</pre><p>This leads to:</p><ul><li>Race conditions</li><li>Inconsistent state</li><li>Lost updates</li></ul><p>Hence we need:</p><ul><li>synchronized</li><li>locks</li><li>volatile</li><li>atomic variables</li><li>CAS</li></ul><h3>Conclusion</h3><p>Once you understand this mental model: Process = container; Thread = worker, all of Java multithreading starts making sense.<br>It becomes clear why threads are faster, why they share memory, and why synchronization problems exist.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64ff1cfd8933" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Hibernate in Java — Part 1: Using xml config]]></title>
            <link>https://mayankpant-dev.medium.com/working-with-hibernate-in-java-part-1-using-xml-config-318708b53b86?source=rss-35632dfbbe6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/318708b53b86</guid>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Mayank Pant]]></dc:creator>
            <pubDate>Mon, 24 Nov 2025 09:42:53 GMT</pubDate>
            <atom:updated>2025-11-30T09:10:33.116Z</atom:updated>
            <content:encoded><![CDATA[<h3>Working with Hibernate in Java — Part 1: Using xml config</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*mYxq2t8s1WkTs1d-.png" /></figure><p>We don’t want to use Spring because, at the moment, we are trying to learn Hibernate, which is a framework itself. So we just want to focus on one framework at this point, and that is Hibernate.</p><h3>Creating a simple project</h3><p>First, we create the most basic Maven project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUpKnfS1rmEj9iAJl2yFUQ.png" /></figure><h3>Adding dependency</h3><p>Adding hibernate-core dependency</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;org.hibernate.orm&lt;/groupId&gt;<br>  &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;<br>  &lt;version&gt;7.1.8.Final&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p>We also need to connect to the database, for that we need a vendor, and in this case we are using MySQL. So we need the mysql-connector dependency.</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;com.mysql&lt;/groupId&gt;<br>  &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt;<br>  &lt;version&gt;9.5.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><h3>Connecting to the database</h3><p>We need to connect to the database now. There are 2 ways to do this:</p><ol><li>Using xml file: In resources, we create a folder called META-INF and place a persistence.xml file that tells our app where the database is and how to connect to it. We don&#39;t need to remember this file; we can just copy and paste it from the docs.</li><li>Programatically: The configuration that we do in xml, can easily be done in a class form</li></ol><p>As part of this tutorial we will stick with using xml config file. You can copy-paste this one:</p><pre>&lt;persistence xmlns=&quot;http://xmlns.jcp.org/xml/ns/persistence&quot;<br>             xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; version=&quot;2.2&quot;<br>             xsi:schemaLocation=&quot;http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd&quot;&gt;<br>    &lt;!-- Define persistence unit --&gt;<br>    &lt;persistence-unit name=&quot;my-persistence-unit&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&gt;<br>        &lt;description&gt;description&lt;/description&gt;<br>        &lt;provider&gt;org.hibernate.jpa.HibernatePersistenceProvider&lt;/provider&gt;<br><br>        &lt;exclude-unlisted-classes&gt;false&lt;/exclude-unlisted-classes&gt;<br><br><br>        &lt;properties&gt;<br>            &lt;!-- database connection --&gt;<br>            &lt;property name=&quot;jakarta.persistence.jdbc.driver&quot; value=&quot;com.mysql.cj.jdbc.Driver&quot; /&gt;<br><br>            &lt;!-- Ends with your database table name--&gt;<br>            &lt;property name=&quot;jakarta.persistence.jdbc.url&quot; value=&quot;jdbc:mysql://localhost/jpa_2025_ch1&quot; /&gt;<br>            &lt;property name=&quot;jakarta.persistence.jdbc.user&quot; value=&quot;root&quot; /&gt;<br>            &lt;property name=&quot;jakarta.persistence.jdbc.password&quot; value=&quot;&quot; /&gt;<br>        &lt;/properties&gt;<br>    &lt;/persistence-unit&gt;<br>&lt;/persistence&gt;</pre><h3>Coding Part</h3><p>We use EntityManager, which is sort of like the manager for context. And this can be used to control the context and the transaction that we are doing.</p><pre>EntityManager em = null;<br>try {<br>    em.getTransaction().begin();<br>    /*<br>    * What you want to persist goes here.<br>    */<br>    em.getTransaction().commit();<br>} finally {<br>    em.close();<br>}</pre><p>How to get the EntityManager?<br>It uses the Factory pattern, so we need EntityManagerFactory to create one.</p><p>How to get EntityManagerFactory? <br>We can use the Persistence class method createEntityManagerFactory() and instruct it to use the persistence.xml file&#39;s persistence-unit-name</p><pre>EntityManagerFactory emf = Persistence.createEntityManagerFactory(&quot;my-persistence-unit&quot;);<br>EntityManager em = emf.createEntityManager();</pre><p>This give us the the EntityManager which we can use to persist the object.</p><h3>Describing Entity</h3><p>Next, we need to describe our Entity. Why? <br>Because our database can have many tables, and not all are considered Entity. We can have many-to-many mapping and the intermediate table might not be an entity.</p><p>For this, we need to describe in our Java code which tables are considered as entity. And then we can describe separately the relationships between these entities.</p><ul><li>We create a new package called entities</li><li>Create a class, lets say Product</li><li>Annotate it with @Entity to let hibernate know that this represents a table in database.</li><li>We then provide all the fields in this class, and these fields relate to columns in that table.</li></ul><pre>@Entity  <br>public class Product {  <br><br>    @Id  <br>    private Long id;  <br>    private String name;  <br><br>    public Long getId() {  <br>        return id;  <br>    }  <br><br>    public void setId(Long id) {  <br>        this.id = id;  <br>    }  <br><br>    public String getName() {  <br>        return name;  <br>    }  <br><br>    public void setName(String name) {  <br>        this.name = name;  <br>    }  <br>}</pre><ul><li>We then create an object for this in our class and tell the entity manager to persist it.</li></ul><pre>EntityManager em = emf.createEntityManager();<br>try {<br>    em.getTransaction().begin();<br>    Product p = new Product();<br>    p.setId(3);<br>    p.setName(&quot;Apple&quot;);<br><br>    em.persist(p); // add this to the context --&gt; NOT AN INSERT QUERY<br><br>    em.getTransaction().commit();<br>} finally {<br>    em.close();<br>}</pre><p>This persist does not mean that it will be an INSERT operation on the database. That is the philosophy of JDBC. In JPA, this can or cannot be an insert, all depends on the context.</p><p>Think of this like, context managing all your queries, and it keeps track of the operation you do on objects. It then, at the end when the transaction is to be committed, will mirror the context onto the database and if there are differences then that will be committed to the database.</p><h3>DataSource?</h3><p>In your config, Hibernate <strong>creates an internal DataSource automatically</strong> using the JDBC properties you provided.</p><p>You did <strong>NOT</strong> define a DataSource. Hibernate <strong>builds one internally</strong> when it sees:</p><pre>&lt;property name=&quot;jakarta.persistence.jdbc.url&quot; …/&gt; <br>&lt;property name=&quot;jakarta.persistence.jdbc.user&quot; …/&gt; <br>&lt;property name=&quot;jakarta.persistence.jdbc.password&quot; …/&gt; <br>&lt;property name=&quot;jakarta.persistence.jdbc.driver&quot; …/&gt;</pre><p>So yes — a DataSource <em>is being used</em>, but it is: a basic, internal Hibernate-managed DataSource (not pooled, inefficient but works)</p><p>Hibernate does NOT do:</p><ul><li>DriverManager.getConnection()</li><li>open/close sockets</li><li>pooling</li><li>retries</li></ul><p>It delegates all connection logic to a DataSource.<br>So if you do not provide one: Hibernate builds a <strong>simple, unpooled DataSource</strong> behind the scenes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=318708b53b86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unraveling the Magic of JIT Compilation and HotSpot JVM: A Journey Through Java’s Performance…]]></title>
            <link>https://mayankpant-dev.medium.com/unraveling-the-magic-of-jit-compilation-and-hotspot-jvm-a-journey-through-javas-performance-dddadd7d8dd5?source=rss-35632dfbbe6e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dddadd7d8dd5</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[jit]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Mayank Pant]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 07:02:12 GMT</pubDate>
            <atom:updated>2024-06-06T07:05:21.338Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unraveling the Magic of JIT Compilation and HotSpot JVM: A Journey Through Java’s Performance Evolution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNSUSAQCJs3tt-0VvvDwnw.jpeg" /></figure><p>Java, with its promise of “write once, run anywhere,” revolutionized software development in the mid-1990s. However, as applications grew in complexity, performance became a critical concern. Enter JIT compilation and the HotSpot JVM, two pivotal innovations that transformed Java’s execution speed and scalability.</p><h4>The Need for Speed</h4><p>Java’s bytecode execution model, while portable, initially suffered from performance overheads due to interpretation. As applications became more demanding, the performance gap between Java and natively compiled languages widened, prompting the search for solutions to enhance execution speed.</p><h4>Enter JIT Compilation</h4><p>Just-In-Time (JIT) compilation emerged as a game-changer. Instead of interpreting bytecode line by line, JIT compilers analyze code at runtime and selectively compile frequently executed portions (hot spots) into native machine code. Let’s understand this with an analogy:</p><p>Imagine you’re reading a recipe book while cooking. Initially, you follow each step as described (bytecode interpretation). However, if you notice yourself repeatedly using certain instructions, you jot down those steps on a sticky note for quick reference (JIT compilation). This way, you optimize your cooking process and save time.</p><h4>Unveiling HotSpot JVM</h4><p>HotSpot JVM, introduced by Sun Microsystems, took JIT compilation to new heights. It dynamically analyzes application behavior, identifies hot spots, and applies adaptive optimization techniques to generate highly efficient native code. Think of it as having a smart assistant in your kitchen:</p><p>Your assistant observes your cooking habits, identifies the steps you repeat frequently, and prepares a customized cooking plan to streamline your process. This adaptive approach ensures optimal performance tailored to your specific needs.</p><h4>Evolution and Adoption</h4><p>Over the years, JIT compilation and HotSpot JVM evolved to address the demands of modern software development. New optimization techniques were introduced, and performance bottlenecks were mitigated. Today, Java’s performance rivals that of natively compiled languages, making it a top choice for a wide range of applications.</p><h4>Practical Applications</h4><p>Let’s delve into real-world examples to illustrate the impact of JIT compilation and HotSpot JVM:</p><ul><li><strong>Enterprise Software</strong>: Large-scale applications benefit from HotSpot’s adaptive optimization, delivering fast and reliable performance.</li><li><strong>Web Applications</strong>: Java-based web servers leverage JIT compilation to handle high traffic loads efficiently.</li><li><strong>Scientific Computing</strong>: Performance-sensitive computations benefit from HotSpot’s advanced optimization techniques, enabling complex simulations and data analysis.</li></ul><h4>Conclusion: Embracing Performance Excellence</h4><p>JIT compilation and HotSpot JVM represent the culmination of Java’s quest for performance excellence. By combining dynamic compilation, adaptive optimization, and real-time profiling, Java has cemented its position as a powerhouse in the world of software development. Whether you’re a beginner exploring the basics or a seasoned engineer fine-tuning performance-critical applications, understanding JIT and HotSpot JVM is key to unlocking Java’s full potential in today’s competitive landscape.</p><p>And remember, when your Java code is running faster than ever, it’s okay to give a little shout-out to your trusty JIT compiler and HotSpot JVM — they’re the unsung heroes behind the scenes, making your software shine brighter than ever! 🚀</p><h4>References</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSCcJXxw1Rfk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSCcJXxw1Rfk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSCcJXxw1Rfk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c16f844c95fad790f7da77f15e13578d/href">https://medium.com/media/c16f844c95fad790f7da77f15e13578d/href</a></iframe><ul><li><a href="https://julio-falbo.medium.com/understand-jvm-and-jit-compiler-part-1-a94c27d32478">Understand JVM and JIT Compiler — Part 1</a></li><li><a href="https://www.slideshare.net/slideshow/javaone-2012-jvm-jit-for-dummies/14604502">JavaOne 2012 - JVM JIT for Dummies</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dddadd7d8dd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>