<?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 Mohit Pal on Medium]]></title>
        <description><![CDATA[Stories by Mohit Pal on Medium]]></description>
        <link>https://medium.com/@mohit-pal?source=rss-300d7748f246------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g2fQIRyc67La1e3SMJXTtA.png</url>
            <title>Stories by Mohit Pal on Medium</title>
            <link>https://medium.com/@mohit-pal?source=rss-300d7748f246------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 02:59:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohit-pal/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[System Design. Without it, we’re all just Vibe Coders.]]></title>
            <link>https://mohit-pal.medium.com/system-design-without-it-were-all-just-vibe-coders-2d9dbc726010?source=rss-300d7748f246------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d9dbc726010</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-course]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mohit Pal]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 08:03:58 GMT</pubDate>
            <atom:updated>2026-07-12T11:41:26.786Z</atom:updated>
            <content:encoded><![CDATA[<h4>A beginner-friendly guide to understanding core system design concepts using everyday analogies.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECAMgHNtiq77xZd9okqpPg.png" /><figcaption>Image created by author via ChatGPT</figcaption></figure><p>Earlier today I saw this on the internet: “It’s 2026, dude, you can’t even get a Junior SWE job without passing a hardcore system design interview.”</p><p>Well, it seems to be right.</p><p>Some of us would say it’s been roughly 3 years and 7 months since ChatGPT was released, and the paradigm has shifted from <strong><em>Coding</em> to <em>Building</em></strong>, so we should learn System Design. But —</p><p>System Design has been around since before AI. The real problem was that students were learning to code, not to architect.</p><p>System Design is way-way more interesting than writing the code. It tells you how the daily things you use are actually connected and works on your clicks.</p><p>And honestly, that was fair enough at the time, because that’s just how the situation was.</p><p>Especially in the Indian community, which produces roughly <strong>1.5 million</strong> (15 lakh) engineering graduates every year — making it one of the largest technical talent pools in the world — out of which only about 5% — 10% were actually learning System Design.</p><h3>So How Does a Click Works?</h3><p>You open Instagram. <br>You tap a story.<br>Half a second later, a video is playing on your phone that was sitting on a server somewhere on the planet.</p><p>That’s the whole point of good engineering.</p><p>This is Part 1 of a three-part series where we pull on a thread properly. This part is about <strong>communication. </strong>How a request works and finds a server, and how the two of them actually talk once they’re connected. Part 2 is about where the data lives once it gets there. Part 3 is about what happens when a million people show up and try to do this at the same time.</p><p>Let’s start with the two characters in this story.</p><h3>1. Client and Server Concept</h3><p>Nearly everything you’ve ever used on a screen is a conversation between exactly two kinds of participants. <strong>Client and Server.</strong></p><p>The <strong>client</strong> is the one asking. You, your browser, your phone’s Instagram app, the terminal you’re typing curl into — all clients. They don&#39;t do the heavy lifting. They ask, they wait, they display2.</p><p>The <strong>server</strong> is the one answering. It’s a machine — or more realistically, a fleet of machines — sitting somewhere, awake at 3 a.m. on a Tuesday, waiting for someone to ask it something.</p><p>Think of it less like a computer thing and more like a restaurant.</p><p>You (the client) don’t walk into the kitchen and cook your own food. You sit at a table, tell a waiter what you want, and the kitchen (the server) does the work and sends a plate back out. You never see the kitchen. You don’t need to. That separation — ask over here, do the work over there — is <strong>client-server architecture</strong> in its entirety.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KcFKwz1aKawmFwZPt7UBTQ.png" /><figcaption>Image created by author via ChatGPT</figcaption></figure><p>It sounds too simple to matter. It matters enormously, because it immediately creates a problem nobody warns you about when you’re first learning to code: <strong>if the client and server are two separate machines, possibly on two separate continents, how does the client even know where to send the request?</strong></p><p>You can’t just shout “server!” into your Wi-Fi and hope. <br>You need an address.</p><h3>2. IP Addresses: The Actual Coordinates</h3><p>Every device that talks on the internet — your laptop, your phone, a server in a data center in Virginia — has an <strong>IP address</strong>.</p><p>Something like 142.250.183.206.</p><p>The best way to think about an IP address isn’t “phone number,” even though that’s the comparison everyone reaches for first.</p><p>It’s closer to <strong>GPS coordinates</strong>. <strong>Geographic coordinates came into use first</strong>, beating phone numbers by more than <strong>2,000 years</strong>. Coordinates work perfectly. They’re also miserable to use in daily life. Nobody plans a Paris trip by telling their partner “let’s meet at 48.8584, 2.2945” unless you were playing a ‘deathmatch game’ with a friend — but rather, “Darling, let’s meet at the Eiffel Tower.”</p><p>An <strong>IP addres</strong>s does the same job for a machine on a network: it’s a precise, unambiguous <strong>point on the internet</strong>, and it just happens to be the server that Netflix streams video from.</p><p>People aren’t even good at remembering what they ate for breakfast — let alone long series of numbers — but they are very good at remembering names.</p><p>That mismatch — is the entire reason the next system exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWDfvpxCVh673aI-uRI77A.png" /><figcaption>Image created by author via ChatGPT</figcaption></figure><h3>3. DNS: The World’s Most Important Address Book</h3><p>When you type <strong>google.com</strong> into a browser, you are not giving the browser an address. You&#39;re giving it a <em>name</em>, and something, somewhere, has to translate that name back into coordinates before anything can actually happen.</p><p>That something is <strong>DNS — the Domain Name System</strong>.</p><p>It’s the internet’s Google Maps/Address book, and it works exactly like the contacts app on your phone. You don’t memorize your friend’s number; you save their name once, and every time you call them, your phone quietly looks the number up on your behalf. You never see this happen. You just tap “<strong>MOM ♡</strong>” and it rings.</p><p>DNS does this at planetary scale. Type google.com, and behind the scenes:</p><ol><li>Your device asks a DNS, “what’s the IP address for google.com?&quot;</li><li>The DNS server looks it up (it’s actually a small relay race across several servers, but the effect is the same).</li><li>It hands back an <strong>IP address</strong>.</li><li><em>Now</em> your browser knows where to send the actual request.</li></ol><p>You can watch this handoff happen yourself. Open a terminal and type:</p><pre>ping google.com</pre><p>You’ll see a raw IP address appear in the output — that’s DNS doing its job, one lookup before you ever load a single pixel of the page.</p><p>So the chain so far reads: a name gets you coordinates, and coordinates get you to a machine. Eiffel Tower → 48.8584° N, 2.2945° E → an actual pile of iron in Paris. google.com → 142.250.183.206 → an actual server in a data center.</p><p>But here’s a wrinkle worth sitting with, because it explains a lot of infrastructure decisions you’ll see later: <strong>companies move their servers.</strong></p><p>They migrate data centers (large big servers), they add new machines, they retire old ones. If a client had to remember a raw IP forever, moving servers would break everyone’s connection overnight. DNS is what lets a company change <em>where</em> Google actually lives without you ever noticing, because you were never relying on the address directly — you were relying on the name, and the name just gets re-pointed.</p><h3>4. Proxy and Reverse Proxy: The Middlemen You Never See</h3><p>Here’s something that surprises a lot of people learning this for the first time: your request often doesn’t go straight to the server, even after DNS hands you an address.</p><p>Frequently, it goes through a middleman first.</p><p><strong>A proxy sits on your side, the client’s side.</strong> <br>Picture hiring a translator to make a phone call on your behalf, in a language you don’t speak, to someone who never learns your name — only the translator’s.</p><p><strong>You → proxy → server</strong></p><p>The server sees the <strong>proxy’s identity</strong>, not yours. That’s the whole value proposition: your real IP, your real location, stays hidden behind the translator. This is what <strong>VPNs(Virtual Private Networks) </strong>and corporate networks are doing every time they route your traffic.</p><p><strong>A reverse proxy is the same idea, flipped, and sitting on the server’s side.</strong> Now it’s the company protecting <em>itself</em>, not you. Instead of exposing its actual servers directly to the entire internet — which is a bit like a restaurant publishing the home address of every chef — the company puts a reverse proxy in front.</p><p><strong>server → proxy → you</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-fOqWHPC5G6oxpgLqmB3A.png" /><figcaption>Image created by author via ChatGPT</figcaption></figure><p>Every request lands there first. It decides which server actually handles it, absorbs a chunk of malicious traffic before it ever reaches anything important, and can quietly spread requests across a dozen machines behind the scenes.</p><p>The one-line way to keep these straight: <strong>a proxy hides the client from the server; a reverse proxy hides the server from the client.</strong></p><p>Once you accept that requests routinely pass through one or more of these hidden layers, a new, very human question shows up: how long does all of this actually take?</p><h3>5. Latency: The Tax of Distance</h3><p>Latency is the <strong>delay between sending a request and getting a response back</strong>.</p><p>Even on a perfectly healthy connection, it’s <strong>never zero</strong>, <strong>because</strong> information doesn’t travel infinitely fast — it travels at a large but finite fraction of the speed of light, through cables that go the long way around continents and under oceans.</p><p>Here’s a scenario that makes it concrete. Your server lives in a data center in New York. Your user is in Jaipur. That user taps a button, and the request has to travel roughly 12,000 kilometers to New York, get processed, and travel 12,000 kilometers back. That full there-and-back journey is what engineers mean by <strong>round-trip time</strong>, and it’s the backbone of what latency measures.</p><p>What you <em>can</em> do is shrink the distance it has to travel. That’s why large platforms run <strong>multiple data centers</strong> scattered across the world instead of one central fortress. For example, a <strong>request gets routed to a</strong> <strong>closest server</strong> like in Mumbai instead of New York, and the trip shrinks from 12,000 kilometers to a few hundred. Same request, same server logic, a fraction of the wait.</p><p>The intuition to keep: <strong>closer server, faster response.</strong> It’s the single most reliable lever for cutting latency, and you’ll see it resurface later when we talk about CDNs in Part 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8i-_X2NYhu6p3o0TjOYwPw.png" /><figcaption>Image created by author via ChatGPT</figcaption></figure><p>We now know how a request finds an address-<strong>IP Address</strong>, gets translated from a name-<strong>DNS</strong>, possibly detours through a middleman-<strong>Proxy</strong>, and pays a distance tax along the way-<strong>Latency</strong>.<strong> </strong>What we haven’t covered yet is the actual language the client and server speak once they’re finally, physically connected.</p><h3>6. HTTP and HTTPS: The Rules of the Conversation</h3><p>Two computers being connected does not mean they can understand each other; much like how two strangers standing close together do not necessarily speak the same language. They require a grammar that both agree upon.</p><p>On the web, that grammar is <strong>HTTP — HyperText Transfer Protocol</strong> and it only defines <strong>how data is transferred or how data physically moves</strong>— and it’s why nearly every address you’ve ever typed starts with <strong>http://</strong> or <a href="https://./"><strong>https://</strong>.</a></p><p>HTTP exchange is almost boringly simple:</p><ul><li>Your browser (the client) sends a <strong>request</strong>, which includes headers (metadata like what browser you’re using, what kind of data you want) and sometimes a body (actual data, like the contents of a form you filled out).</li><li>The server processes it.</li><li>The server sends back a <strong>response</strong> — either the data you asked for, or an error code you’ve definitely seen before, like 404 (not found) or 500 (server broke).</li></ul><p>For a long time, this all happened in using HTTP which sends data in simple <strong>plain text</strong>.</p><p>Meaning:</p><ul><li><strong>anyone intercepting that request/traffic on the way can read it</strong><br>like — a nosy router, a compromised Wi-Fi hotspot at a coffee shop — could read every word of it,</li><li>passwords, your credit card number, personal data → all exposed</li></ul><p>Now… who would want that. No one.</p><p><strong>HTTPS</strong> fixes exactly that.</p><p>The <strong>“S” stands for Secure</strong>, and it works by wrapping every request and response in <strong>SSL/TLS encryption</strong> before it ever leaves your device.</p><p>Someone can still intercept the traffic — encryption doesn’t stop that — but what they intercept is<strong> unreadable noise</strong> instead of your actual data. This is why <strong>HTTPS became the default</strong>, not the exception.</p><p><strong>Now since HTTP only defines how data physically moves,</strong> the question is who moves it and what does it contains?</p><p>That’s a separate job entirely, and it belongs to APIs.</p><h3>7. APIs: The Contract Between Systems</h3><p>An <strong>API — Application Programming Interface</strong> — is an agreement that clearly specifies what a client can request, and the form in which the response will be received.</p><p>For example: If you go to restaurant and ask “I want some peace and quiet” <br>the manager would politely say “Sorry, we don’t sell that here”.</p><p>A restaurant has a menu for a reason. You need to know that if you order item #7, you will get the exact dish described next to it, every single time, served exactly how it was promised.</p><p>That is the entire value of an API: <strong>it hides the complicated implementation (kitchen work) and exposes only the promise (menu).</strong></p><p>Underneath the hood, an API almost always uses HTTP as its physical transport layer. Think of it this way:</p><ul><li><strong>HTTP</strong> is <em>how</em> the data physically travels.</li><li><strong>The API</strong> is <em>what</em> the data actually means when it arrives.</li></ul><p>When a request comes in, the API runs whatever internal logic it needs to — like a database request or calling other hidden services. Then, it packs the answer into structured data, usually in a format called JSON, and sends it back.</p><p>This is why APIs are everywhere, invisibly: your banking app, your food delivery app, your fitness tracker syncing steps to the cloud — all of it is one system asking another system, through an API.</p><p>Knowing <em>that</em> APIs exist raises an obvious next question: what the way to design one? There are two dominant philosophies worth understanding side by side, because you will absolutely encounter both.</p><h3>8. REST: Treat Everything Like an Object</h3><p><strong>REST — Representational State Transfer.</strong> It’s less a specific technology and more a set of conventions that most of the internet quietly agreed to follow.</p><p>REST leans on three ideas:</p><p><strong>It’s stateless.</strong> The server doesn’t remember you between requests. Every single request has to carry everything the server needs to understand it — like calling a customer service line where the agent has zero memory of your last call, so you re-explain your account details every single time.</p><p>Annoying for humans, but it’s exactly what lets REST servers scale so cleanly: any server in a fleet can handle any request, because none of them are relying on remembering you specifically.</p><p><strong>It treats everything as a resource.</strong> A user is a resource at /users. An order is a resource at /orders. Each URL <strong>names a</strong> <strong><em>thing</em></strong>, <strong>not an <em>action</em></strong>.</p><p><strong>It reuses a small, standard vocabulary of HTTP methods</strong> to describe what you want to do to that thing:</p><p>GET to read it, <br>POST to create it, <br>PUT/PATCH to update whole thing/to update only a part of it, <br>DELETE to remove it.</p><p>Once you know this pattern, you can guess how most REST APIs behave without ever reading their documentation.</p><p>REST’s popularity isn’t an accident — it’s simple, predictable, and plays nicely with caching. But it has a real weakness that only shows up once your app gets complicated: <strong>the server decides what shape the response takes, not you.</strong></p><p>If you need a user’s name, their profile photo, and their last five posts, and the API wasn’t designed to bundle all three, you’re stuck firing off three separate requests — one for the user, one for the profile, one for the posts — each one paying its own latency tax.</p><p>That specific pain point is why an entirely different approach showed up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baAUqqxuwr-o8lrXY_aJIw.png" /><figcaption>Left: REST API , Right: GraphQL API</figcaption></figure><h3>9. GraphQL: Let the Client Order Exactly What It Wants</h3><p><strong>GraphQL</strong>, which Facebook introduced in 2015, flips REST’s core assumption.</p><p>Instead of the server deciding what a response contains, <strong>the client specifies exactly the fields it needs, and gets back exactly that — nothing more, nothing less.</strong></p><p>Go back to the three-request example above. In REST, fetching a user’s info, their profile, and their recent posts might cost you three round trips:</p><p>GET /users/123, <br>GET /users/123/profile, <br>GET /users/123/posts</p><p>In GraphQL, you send a single query that essentially says <strong>&quot;give me this user&#39;s name, their bio, and their last five post titles, all together&quot;</strong> — and one response comes back containing precisely that, structured exactly as requested.</p><pre>{<br>  user(id: &quot;123&quot;) {<br>    name<br>    profile { bio }<br>    posts { title }<br>  }<br>}</pre><p>It’s the difference between ordering a fixed combo meal (<strong>REST </strong>— you get what’s on the menu, take it or leave it) and telling a chef exactly which ingredients you want on your plate (GraphQL — but now the kitchen has to actually understand your custom order, which is genuinely more work for the server to support).</p><p>Neither is strictly “better.”</p><p>REST’s rigidity is also its predictability and its cache-friendliness; GraphQL’s flexibility is also its complexity.</p><p>Most large platforms end up using both, for different parts of their systems, depending on which trade-off matters more in that specific corner of the product.</p><p>REST and GraphQL both share one deep assumption, though: a request goes out, a response comes back, and then the conversation is over. The client has to ask again if it wants anything new.</p><p>For most of what you do online, that’s completely fine. For a chat app, it’s a disaster.</p><h3>10. WebSockets: When “Ask Again Later” Isn’t Good Enough</h3><p>Try to imagine building live chat, a multiplayer game, or a stock ticker using the request-response pattern we just described.</p><p>The client would have to keep asking, over and over: <em>“anything new? anything new? anything new?”</em></p><p>This is called <strong>polling</strong>, and it’s exactly as wasteful as it sounds — most of those questions get answered with “nope, nothing,” and every single one of them still costs a full round trip.</p><p><strong>WebSockets</strong> solve this by throwing out the ask-and-wait model entirely.</p><p>Instead of a request that opens and closes, a WebSocket <strong>opens one connection and keeps it open</strong>, like leaving a phone call connected instead of hanging up and redialing every time you have something new to say.</p><p>Once that connection exists, both sides — client and server — can send data to each other <strong>at any moment, in either direction</strong>, with no need to “ask” first.</p><p>That’s why your messages in a chat app appear the instant someone sends them, instead of thirty seconds later when your app happens to check again. The connection was already open. There was nothing to wait for.</p><p>WebSockets solve real-time communication beautifully — for a client talking to a server. But there’s a related problem they don’t cover: what happens when it’s not a person waiting for an update, but a <em>server</em> that needs to hear from another server?</p><h3>11. Webhooks: “Don’t Call Me, I’ll Call You”</h3><p>Say your app processes payments through Stripe. Without some way for Stripe to notify you, your only option would be polling their servers every few seconds asking:</p><p>“did the payment go through yet? did it go through yet?” — burning API calls on a question that’s almost always “not yet.”</p><p><strong>Webhooks</strong> invert that relationship entirely. You give Stripe a URL — your webhook endpoint.</p><p>You register it once. And from then on, the moment something actually happens on their end — a payment succeeds, a subscription renews — <em>they</em> send <em>you</em> an HTTP request, unprompted, containing the details of that event. Your server receives it and reacts: updates a database, sends a confirmation email, kicks off whatever comes next.</p><p>It’s the classic Hollywood casting line, repurposed for infrastructure: <em>don’t call me, I’ll call you.</em></p><p>You’ll recognize this pattern everywhere once you know to look for it — GitHub triggering a deployment the moment code gets pushed, Twilio pinging your server the second a text message arrives without you ever having to ask.</p><h3>Putting It All Together</h3><p>Step back and look at the shape of everything we just covered, because it really is one continuous story, not eleven disconnected facts:</p><p>A client needs to reach a server, so it needs an <strong>address</strong> — an IP. Humans can’t work with raw addresses, so we invented <strong>DNS</strong> to translate friendly names into them. That request might not go straight to the destination — it could pass through a <strong>proxy</strong> protecting the client, or a <strong>reverse proxy</strong> protecting the server. However it travels, it pays a real <strong>latency</strong> cost measured in physical distance. Once it arrives, client and server need a shared grammar to actually understand each other — that’s <strong>HTTP</strong>, made safe by <strong>HTTPS</strong>. On top of that transport, an <strong>API</strong> defines the actual contract of what can be asked for and what will come back, following either the <strong>REST</strong> convention or the <strong>GraphQL</strong> convention depending on how much flexibility the client needs. And when a single request-response isn’t enough — when things need to happen live, or servers need to talk to servers without being asked — <strong>WebSockets</strong> and <strong>webhooks</strong> step in to keep everyone in sync in real time.</p><p>That’s the entire nervous system of a modern application. Every tap, swipe, and click you make today ran this exact gauntlet, start to finish, in well under a second.</p><p>But none of this explains something fairly important: once a request finally <em>lands</em> on a server, where does the data it’s asking about actually come from? What happens after “the server processes it” — what is it processing, and where does it live?</p><p>That’s Part 2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d9dbc726010" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java String: All About It — Part II]]></title>
            <link>https://mohit-pal.medium.com/java-string-all-about-it-part-ii-18bf2f466c19?source=rss-300d7748f246------2</link>
            <guid isPermaLink="false">https://medium.com/p/18bf2f466c19</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[string-manipulation]]></category>
            <category><![CDATA[string]]></category>
            <dc:creator><![CDATA[Mohit Pal]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 07:01:17 GMT</pubDate>
            <atom:updated>2026-07-05T07:01:17.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*kkbB3BrUZ8fQFJ_kvgKLCg.png" /><figcaption>Part-II</figcaption></figure><p>In Part I, we covered the foundational concepts of Java Strings: immutability, the String Constant Pool, and how to handle mutable text using StringBuffer and StringBuilder.</p><p>Now, it is time to dive deeper. In this second part, we will explore advanced memory management techniques, how the Java compiler optimizes string operations under the hood, and the modern methods introduced in recent Java releases to make string manipulation easier than ever.</p><h3>Deep Dive into String Memory: String.intern()</h3><p>We know that creating a string using the new keyword forces Java to allocate memory in the general Heap, bypassing the String Pool. But what if you dynamically generate strings at runtime and want to store them in the pool to save memory?</p><p>This is where the intern() method comes in.</p><p><strong>How JVM Handles intern():</strong></p><ul><li><strong>1. Pool Check:</strong> JVM searches the String Constant Pool for an equal string.</li><li><strong>2. If Found:</strong> Returns the existing reference directly from the pool.</li><li><strong>3. If Not Found:</strong> Adds the string to the pool and returns this new reference.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xt_GdKizgpstyumQlaSkcg.jpeg" /><figcaption>Conceptualizing String.intern()</figcaption></figure><pre>String s1 = new String(&quot;Java&quot;);<br>String s2 = s1.intern(); <br>String s3 = &quot;Java&quot;;<br><br>System.out.println(s1 == s2); // False (s1 is in Heap, s2 is in Pool)<br>System.out.println(s2 == s3); // True (Both point to the same Pool reference)</pre><p><strong>Use Case:</strong> If your application processes millions of duplicate strings (e.g., parsing a massive XML/JSON file with repeated tags or keys), using intern() can drastically reduce your application’s memory footprint.</p><h3>The Truth About String Concatenation (+)</h3><p>A common piece of advice in Java is: <em>“Never use the + operator in a loop; use StringBuilder instead.”</em> But how does the + operator actually work?</p><p>In older versions of Java (up to Java 8), when you write:</p><pre>String result = &quot;Hello&quot; + &quot; &quot; + &quot;World&quot;;</pre><p>The Java compiler automatically converts this under the hood to:</p><pre>String result = new StringBuilder().append(&quot;Hello&quot;).append(&quot; &quot;).append(&quot;World&quot;).toString();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhy52p5inuHYhPXLOiD9wQ.jpeg" /><figcaption>Compiler Optimization of String Concatenation</figcaption></figure><p>Because of this, using + for simple, one-line concatenations is perfectly fine and highly optimized. However, if you use + inside a for loop, the compiler creates a <em>new</em> StringBuilder instance during every single iteration, which wastes memory and CPU cycles.</p><p><em>(Note: Starting with Java 9, string concatenation using + is handled dynamically via invokedynamic, making it even more efficient, but the rule to avoid + inside large loops still applies.)</em></p><h3>StringJoiner (Java 8)</h3><p>Before Java 8, joining a list of strings with a delimiter (like a comma) required messy loops and manual checks to remove the trailing comma. Java 8 introduced StringJoiner to solve this elegantly.</p><p>You can specify a delimiter, and optionally, a prefix and suffix:</p><pre>StringJoiner joiner = new StringJoiner(&quot;, &quot;, &quot;[&quot;, &quot;]&quot;);<br>joiner.add(&quot;Apple&quot;);<br>joiner.add(&quot;Banana&quot;);<br>joiner.add(&quot;Mango&quot;);<br><br>System.out.println(joiner.toString()); <br>// Output: [Apple, Banana, Mango]</pre><p>Alternatively, you can use the highly convenient String.join() method:</p><pre>String result = String.join(&quot;-&quot;, &quot;2026&quot;, &quot;07&quot;, &quot;05&quot;);<br>System.out.println(result); // Output: 2026-07-05</pre><h3>Modern String Methods (Java 11 and Beyond)</h3><p>Java 11 and subsequent releases brought some much-needed utility methods to the String class, removing the need for third-party libraries like Apache Commons Lang for basic checks.</p><p><strong>1. isBlank() vs isEmpty()</strong></p><ul><li>isEmpty() only checks if the string length is 0.</li><li>isBlank() checks if the string is empty OR contains only white spaces.</li></ul><pre>String text = &quot;   &quot;;<br>System.out.println(text.isEmpty()); // False<br>System.out.println(text.isBlank()); // True</pre><p><strong>2. strip() vs trim()</strong><br>trim() has been around since the early days of Java, but it only removes spaces based on <strong>ASCII values (&lt;= 32)</strong>.</p><p>strip() is Unicode-aware and removes <strong>all leading and trailing</strong> whitespace characters, making it the modern standard.</p><p><strong>3. repeat(int count)</strong><br>Need to duplicate a string multiple times?</p><pre>String line = &quot;-&quot;.repeat(10);<br>System.out.println(line); // Output: ----------</pre><p><strong>4. lines()</strong><br>This method returns a Stream&lt;String&gt; extracted from a multi-line string, partitioned by line terminators (\n, \r, or \r\n). It is incredibly useful for parsing large blocks of text.</p><pre>String multiLine = &quot;Line 1\nLine 2\nLine 3&quot;;<br>multiLine.lines().forEach(System.out::println);</pre><h3>Conclusion</h3><p>Java Strings may seem basic, but they are deeply integrated into the JVM’s memory management and optimization strategies. By understanding how the String Pool works, leveraging intern() when necessary, and utilizing modern methods like StringJoiner and isBlank(), you can write Java code that is not only cleaner but significantly more performant.</p><p><strong><em>Connect With Me</em></strong><em>: </em><a href="https://www.linkedin.com/in/in-mohit/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/mohit01-10"><strong><em>GitHub</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18bf2f466c19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java String: All about it]]></title>
            <link>https://mohit-pal.medium.com/java-string-all-about-it-46f504d45443?source=rss-300d7748f246------2</link>
            <guid isPermaLink="false">https://medium.com/p/46f504d45443</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[string-vs-stringbuilder]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[heap-memory]]></category>
            <category><![CDATA[spring-buffer]]></category>
            <dc:creator><![CDATA[Mohit Pal]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 07:29:03 GMT</pubDate>
            <atom:updated>2026-07-04T07:29:03.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*UMutuAIJhuy5Ji8EGqgrVA.png" /></figure><p>Strings are one of the most widely used concepts in Java programming. Whether you are manipulating data, logging information, or building user interfaces, you will inevitably work with strings. However, beneath their simple appearance lies a sophisticated memory management system and a carefully designed architecture.</p><p>In this article, we will explore the core concepts of Java Strings, including immutability, memory storage, and the mutable alternatives: StringBuffer and StringBuilder.</p><p>Java Strings are objects that are backed by a char array and are immutable. The class java.lang.String is used to create a string object.</p><h3>Why are Java Strings Immutable?</h3><p>In Java, once a String object is created, its data or state cannot be changed. If you try to modify it, a new String object is created instead. Java intentionally makes strings immutable for several crucial reasons:</p><ol><li><strong>Security:</strong> Strings are frequently used to store sensitive information like usernames, passwords, and database connections. Immutability ensures that once a value is validated, it cannot be maliciously altered.</li><li><strong>Performance Improvement:</strong> Because strings are immutable, they can be heavily cached and reused by the JVM.</li><li><strong>Optimize Memory Usage:</strong> Immutability allows Java to safely share the same string instances across multiple references in a special memory area (the String Pool).</li><li><strong>Thread Safety:</strong> Immutable objects are inherently thread-safe. Multiple threads can access a string concurrently without the risk of data corruption or the need for explicit synchronization.</li></ol><p><strong>What Happens if We Try to Modify a String?</strong><br>Let’s look at a practical example:</p><pre>public static void main(String[] args) {<br>    String s1 = &quot;java&quot;;<br>    <br>    // Assign the new string to a variable<br>    String s2 = s1.concat(&quot; rules&quot;);<br>    <br>    // Now s2 refers to &quot;java rules&quot;<br>    System.out.println(&quot;s1 refers to &quot; + s1); // Output: java<br>    System.out.println(&quot;s2 refers to &quot; + s2); // Output: java rules<br>}</pre><p>As shown, calling concat() on s1 does not change s1. Instead, it creates a brand new string s2.</p><figure><img alt="How are Strings Stored?" src="https://cdn-images-1.medium.com/max/660/1*3yMvuLkXq_phhU1k6XqKFg.png" /><figcaption>How are Strings Stored?</figcaption></figure><h3>How are Strings Stored?</h3><p>All Strings in Java are stored inside the <strong>Heap Memory</strong>, but they are managed in two distinct ways depending on how they are created:</p><p><strong>1. String Constant Pool (String Pool)</strong><br>It is a separate space inside the Heap Memory. When you create a string using a literal (e.g., String str1 = “Hello”;), the JVM checks the String Constant Pool inside the heap.</p><ul><li><strong>Exists?</strong> If the string already exists in the pool, the JVM simply returns a reference to the same object.</li><li><strong>No?</strong> If it does not exist, the JVM creates a new instance in the pool.</li></ul><pre>class StringStorage {<br><br>  public static void main(Stringll args)<br>  {<br>    // String created using String literal<br>    String s1 = &quot;TAT&quot; ;<br>    String s2 = &quot;TAT&quot;;<br><br>    // String created using &#39;new&#39; keyword<br>    String s3 = new String (original:&quot;TAT&quot;);<br>    String s4 = new String(original:&quot;TAT&quot;);<br><br>    System.out-println(s1);<br>    System.out-println(s2);<br>    System.out-println(s3);<br>    System.out.println(s4);<br>  }<br>}</pre><p><strong>2. Heap Memory (Outside the Pool)</strong><br>When you use the new keyword (e.g., String s3 = new String(“TAT”);), Java bypasses the pool check for object creation. It explicitly creates a new instance in the general Heap memory, even if an identical string literal already exists in the String Pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*EA2LjzrI23W2iSNFF0TLyw.jpeg" /><figcaption>JVM String Allocation Visualization</figcaption></figure><h3>Handling Mutable Strings: StringBuffer &amp; StringBuilder</h3><p>Because creating a new object every time a string is modified can degrade performance, Java provides two mutable classes for heavy string manipulation:</p><h4>StringBuffer Class</h4><ul><li><strong>Mutable:</strong> Can grow and shrink as needed.</li><li><strong>Synchronized:</strong> Thread-safe, making it reliable in multi-threaded environments.</li><li><strong>Example:</strong></li></ul><pre>StringBuffer sb = new StringBuffer(&quot;Java&quot;);<br>sb.append(&quot; Programming&quot;);<br>System.out.println(sb); // Output: Java Programming</pre><h4>StringBuilder Class</h4><ul><li><strong>Mutable:</strong> Similar to StringBuffer but <strong>not</strong> synchronized.</li><li><strong>Performance:</strong> Because it lacks thread safety (no synchronization overhead), it offers significantly higher performance.</li><li><strong>Example:</strong></li></ul><pre>StringBuilder sb = new StringBuilder(&quot;Java&quot;);<br>sb.append(&quot; Programming&quot;);<br>System.out.println(sb); // Output: Java Programming</pre><h3>Real-Life Use Cases</h3><p>Choosing between String, StringBuffer, and StringBuilder depends on your application’s specific needs:</p><ul><li><strong>String:</strong> Best for constant, unchanging text.</li><li><em>Examples:</em> E-commerce labels (“Add to cart”, “Out of stock”), transaction statuses (“Transaction successful”, “Invalid PIN”), or fixed UI buttons (“Like”, “Comment”, “Share”).</li><li><strong>StringBuffer:</strong> Best when multiple threads need to safely write to the same sequence of characters.</li><li><em>Examples:</em> Shared chat histories, Jenkins CI/CD logs of jobs/tasks, or a banking system logging deposit and withdrawal threads concurrently.</li><li><strong>StringBuilder:</strong> Best for rapid string concatenation in a single-threaded scenario.</li><li><em>Examples:</em> Single-threaded operations, personal direct chat messages, or real-time in-game indicators and notifications.</li></ul><h3>Comparison Summary</h3><pre>String               | StringBuffer              | StringBuilder<br>-------------------- | --------------------------| --------------------------<br>Immutable            | Mutable                   | Mutable<br>Thread-safe          | Thread-safe               | Not thread-safe<br>Slower               | Moderate                  | Faster<br>Use for fixed values | Use in multi-threaded env | Use in single-threaded env</pre><p><strong><em>Connect With Me</em></strong><em>: </em><a href="https://www.linkedin.com/in/in-mohit/"><strong><em>LinkedIn</em></strong></a><strong><em>, </em></strong><a href="https://github.com/mohit01-10"><strong><em>GitHub</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46f504d45443" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>