<?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 Adheesha Chamod on Medium]]></title>
        <description><![CDATA[Stories by Adheesha Chamod on Medium]]></description>
        <link>https://medium.com/@adheeshachamoddesilva?source=rss-5739435eddfc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*heecVGDJW0eO-wtqsm7rKw.png</url>
            <title>Stories by Adheesha Chamod on Medium</title>
            <link>https://medium.com/@adheeshachamoddesilva?source=rss-5739435eddfc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:03:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adheeshachamoddesilva/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: String Pool, The Hidden Memory Trick That’ll Save Your App]]></title>
            <link>https://medium.com/@adheeshachamoddesilva/java-string-pool-the-hidden-memory-trick-thatll-save-your-app-1bb91542c462?source=rss-5739435eddfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bb91542c462</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Adheesha Chamod]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 02:31:54 GMT</pubDate>
            <atom:updated>2025-11-03T02:31:54.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Java Logo" src="https://cdn-images-1.medium.com/max/571/1*RbPEUWUiJ--KmdsqFybdig.jpeg" /></figure><p>Ever wondered why Java treats Strings differently? The answer lies in a clever memory optimization called the String Pool.</p><p>Let’s uncover this with practical examples.</p><h3>What Exactly Is the String Pool?</h3><p>Think of the String Pool as Java’s recycling center for text.</p><p>Instead of creating new String objects every time, Java keeps a special storage area in memory. When you create a String, Java first checks: <em>“Do I already have this exact text?”</em> If yes, it reuses it. If no, it stores it.</p><p>This happens in a special memory region called the <strong>Heap</strong> (specifically in the String Pool area).</p><p>Why does Java do this? <em>Think:</em> Strings are everywhere in your code. Without pooling, your app would waste tons of memory creating duplicate Strings.</p><h3>Quick Detour: What’s the Heap?</h3><p>The Heap is where Java stores all objects during runtime. Every time you use the new keyword, a new object is created in the Heap.</p><p>The Heap has different areas for different purposes. The String Pool is a special section within the Heap dedicated to storing <strong>String literals</strong>.</p><p>Now back to the String Pool!</p><h3>How String Creation Really Works</h3><p>Here’s where it gets interesting. There are two ways to create Strings, and they behave very differently.</p><pre>String str1 = &quot;Hello&quot;;              // Literal<br>String str2 = &quot;Hello&quot;;              // Literal<br>String str3 = new String(&quot;Hello&quot;);  // new keyword<br><br>System.out.println(str1 == str2);   // true<br>System.out.println(str1 == str3);   // false</pre><p>What just happened?</p><ul><li>str1 and str2 point to the same object in the String Pool; in other words, both hold the same memory address</li><li>str3 creates a new object in the regular Heap memory, outside the pool, so this holds a different memory address</li><li>The == operator compares the memory address, not the actual content.</li></ul><p>So, str1 == str2 is true, but str1 == str3 is false, even though they all contain the same content, “Hello”.</p><h3>Visualizing the String Pool</h3><p>Let’s see how str1, str2, and str3 actually live in memory:</p><figure><img alt="Diagram showing str1, str2 pointing to String Pool, str3 to Regular Heap" src="https://cdn-images-1.medium.com/max/1024/1*QAlEhZA_xy-gyWxA4ryXtg.png" /></figure><p>Both str1 and str2 point to the same “Hello” in the pool. But str3 has its own separate copy in the regular Heap area.</p><h3>The intern() Method</h3><p>What if you create a String with new but want to pool it? That’s where intern() comes in. It helps manual pooling.</p><pre>String str1 = &quot;Java&quot;;<br>String str2 = new String(&quot;Java&quot;);<br>String str3 = str2.intern();<br><br>System.out.println(str1 == str2);  // false<br>System.out.println(str1 == str3);  // true</pre><p>The intern() method tells Java: <em>“Check the pool. If this String exists there, give me that reference. If not, add this to the pool and give me the reference.”</em></p><p>After calling intern(), str3 now points to the same pooled “Java” as str1.</p><h3>When String Concatenation Breaks the Pool</h3><p>Here’s a tricky scenario that catches many developers:</p><pre>String s1 = &quot;Hello&quot;;<br>String s2 = &quot;World&quot;;<br>String s3 = &quot;HelloWorld&quot;;<br>String s4 = s1 + s2;<br><br>System.out.println(s3 == s4);  // false</pre><p>Why false? Because s1 + s2 creates a new String object at runtime. The compiler can’t predict what s1 and s2 will contain.</p><p>But watch this:</p><pre>String s5 = &quot;Hello&quot; + &quot;World&quot;;<br>System.out.println(s3 == s5);  // true</pre><p>Now it’s true! The compiler sees two literals being concatenated. It optimizes this at compile-time and puts “HelloWorld” directly into the pool.</p><h3>Compile-Time vs Runtime</h3><pre>final String f1 = &quot;Hello&quot;;<br>final String f2 = &quot;World&quot;;<br>String s1 = &quot;HelloWorld&quot;;<br>String s2 = f1 + f2;<br><br>System.out.println(s1 == s2);  // true</pre><p>Since f1 and f2 are final, the compiler knows their values won’t change. It performs the concatenation at compile-time, so s2 goes into the pool.</p><p>Remove final, and you get false again.</p><h3>Real-World Performance Impact</h3><p>Let’s see the String Pool in action with a performance test:</p><pre>public class StringPoolDemo {<br>    public static void main(String[] args) {<br>        // Without String Pool<br>        long start = System.nanoTime();<br>        for (int i = 0; i &lt; 1000000; i++) {<br>            String s = new String(&quot;Java&quot;);<br>        }<br>        long end = System.nanoTime();<br>        System.out.println(&quot;Without pool: &quot; + (end - start) + &quot; ns&quot;);<br>        <br>        // With String Pool<br>        start = System.nanoTime();<br>        for (int i = 0; i &lt; 1000000; i++) {<br>            String s = &quot;Java&quot;;<br>        }<br>        end = System.nanoTime();<br>        System.out.println(&quot;With pool: &quot; + (end - start) + &quot; ns&quot;);<br>    }<br>}</pre><p>Output from my machine:</p><pre>Without pool: 177163400 ns<br>With pool: 34236900 ns</pre><p>The pooled version was 5x faster and used significantly less memory.</p><h3>Common Pitfalls to Avoid</h3><p><strong>(1) Using </strong><strong>== for String comparison</strong></p><pre>String input = scanner.nextLine(); // User enters &quot;yes&quot;<br>if (input == &quot;yes&quot;) {              // WRONG! This might be false<br>    // This code might never execute<br>}<br><br>if (input.equals(&quot;yes&quot;)) {         // CORRECT!<br>    // This works reliably<br>}</pre><p>User input creates new String objects. Always use equals() for content comparison.</p><p><strong>(2) Unnecessary intern() calls</strong></p><pre>// Don&#39;t do this<br>String s = new String(&quot;Hello&quot;).intern();<br><br>// Just do this<br>String s = &quot;Hello&quot;;</pre><p>If you’re using a literal, it’s already pooled. No need for intern().</p><p><strong>(3) Overusing intern() on dynamic strings</strong></p><pre>// Bad practice<br>for (int i = 0; i &lt; 1000000; i++) {<br>    String s = (&quot;User&quot; + i).intern();<br>}</pre><p>You’re flooding the String Pool with a million unique Strings. The pool isn’t garbage-collected easily, so this wastes memory.</p><h3>When to Use What</h3><p><strong>Use String literals (</strong><strong>&quot;...&quot;) when:</strong></p><ul><li>You have constant text values</li><li>You want automatic pooling</li><li>Memory efficiency matters</li></ul><p><strong>Use </strong><strong>new String() when:</strong></p><ul><li>You explicitly need a new object (rare case)</li><li>You’re working with character arrays or byte arrays</li></ul><p><strong>Use </strong><strong>intern() when:</strong></p><ul><li>You have dynamically created Strings that appear frequently</li><li>You’re sure the String will be reused many times</li><li>Memory footprint is a critical concern</li></ul><h3>The Immutability Connection</h3><p>The String Pool only works because Strings are <strong>immutable</strong>.</p><p>If you could modify a String, changing one reference would affect all references pointing to the same pooled object. Chaos!</p><pre>String s1 = &quot;Java&quot;;<br>String s2 = &quot;Java&quot;;<br><br>// If Strings were mutable:<br>s1.changeToUppercase();         // Hypothetical<br>// Now s2 would also be &quot;JAVA&quot; - unexpected!</pre><p>Immutability guarantees that sharing the same String object is safe.</p><h3>Key Takeaways</h3><ol><li>String literals automatically go into the String Pool</li><li>new String() creates objects outside the pool</li><li>Use equals() to compare String content, not ==</li><li>The pool saves memory by reusing identical Strings</li><li>Compile-time concatenation gets pooled; runtime doesn’t</li><li>Use intern() sparingly and wisely</li><li>Immutability makes the String Pool possible</li></ol><h3>Wrapping Up</h3><p>The String Pool is one of Java’s smartest optimizations. Understanding it helps you write more efficient code and ace those tricky interview questions.</p><p>Next time you write String name = &quot;...&quot;, you&#39;ll know there&#39;s a whole memory management dance happening behind the scenes.</p><p>Now go forth and pool responsibly!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bb91542c462" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding JWT Authentication: How JSON Web Tokens Work]]></title>
            <link>https://medium.com/@adheeshachamoddesilva/understanding-jwt-authentication-how-json-web-tokens-work-849462715cbc?source=rss-5739435eddfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/849462715cbc</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Adheesha Chamod]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 02:31:48 GMT</pubDate>
            <atom:updated>2025-10-20T02:31:48.814Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="JWT — JSON Web Token" src="https://cdn-images-1.medium.com/max/800/1*RF01KPiB3xKqZW565YFqJw.png" /></figure><p>If you’ve been working with modern web applications, you’ve probably encountered JWT. It’s become the standard for authentication in APIs and microservices. But what exactly is a JWT, and why has it become so popular?</p><p>In this guide, we’ll break down JWT in a way that makes sense, covering what they are, how they work, and best practices for using them in your applications.</p><h3>What is JWT?</h3><p>JWT stands for JSON Web Token. It’s a compact, URL-safe token format that contains JSON-encoded information. Think of it as a secure container for transmitting data between parties.</p><p>Here’s a real example for JWT:</p><pre>eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE3NjA3Mjc4MzEsImV4cCI6MTc2MDcyOTEwMiwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsImZpcnN0TmFtZSI6IkpvaG5ueSIsImxhc3ROYW1lIjoiUm9ja2V0IiwiZW1haWwiOiJqcm9ja2V0QGV4YW1wbGUuY29tIiwicm9sZSI6IlVTRVIiLCJ1c2VybmFtZSI6ImpvaG5ueXJvY2tldCIsInVzZXJJZCI6IlUwMDA3In0.A4YkEhGRoEwZHBzx-u-hCLYcmEKcTpliSOt2h3jtbQE</pre><p>Let’s break down what makes this token tick.</p><h3>Structure of JWT</h3><p>A JWT consists of three parts separated by dots, like in the above example. Let’s decode each section of our example token:</p><h4><strong>Part 1: Header</strong></h4><p>Decoding the first part gives us the header:</p><pre>{<br>  &quot;typ&quot;: &quot;JWT&quot;,<br>  &quot;alg&quot;: &quot;HS256&quot;<br>}</pre><ul><li>typ (type): Identifies this as a JWT token</li><li>alg<strong> </strong>(algorithm): Specifies the signing algorithm. HS256 (HMAC SHA-256) is a <strong>symmetric algorithm</strong> using the same secret key for both signing and verification. RS256 (RSA SHA-256) is an <strong>asymmetric algorithm </strong>that uses a public key for verification and a private key for signing.</li></ul><p>Simply, the header tells receivers: “This is what I am and how to verify me.”</p><h4>Part 2: Payload</h4><p>Decoding the second part gives us the payload. This contains the actual data about the user.</p><pre>{<br>  &quot;iss&quot;: &quot;Online JWT Builder&quot;,<br>  &quot;iat&quot;: 1760727831,<br>  &quot;exp&quot;: 1760729102,<br>  &quot;aud&quot;: &quot;www.example.com&quot;,<br>  &quot;sub&quot;: &quot;jrocket@example.com&quot;,<br>  &quot;firstName&quot;: &quot;Johnny&quot;,<br>  &quot;lastName&quot;: &quot;Rocket&quot;,<br>  &quot;email&quot;: &quot;jrocket@example.com&quot;,<br>  &quot;role&quot;: &quot;USER&quot;,<br>  &quot;username&quot;: &quot;johnnyrocket&quot;,<br>  &quot;userId&quot;: &quot;U0007&quot;<br>}</pre><p>Those keys are called “claims”.</p><p><strong>Standard Claims:</strong></p><ul><li>iss (issuer): Who created this token</li><li>iat (issued at): Creation timestamp</li><li>exp (expiration): When it expires</li><li>aud (audience): Who should accept it</li><li>sub (subject): Unique identifier of the user</li></ul><p><strong>Custom Claims:</strong></p><ul><li>userId , role , username, firstName, lastName, email: User-specific details</li></ul><p><strong><em>Critical</em></strong><em>: The payload is base64-encoded, not encrypted. Anyone can decode and read this data using tools like </em><a href="https://www.jwt.io/"><em>jwt.io</em></a><em>. So, never include passwords or sensitive information in JWT.</em></p><h4>Part 3: Signature</h4><p>The signature proves the token hasn’t been tampered with.</p><p>In HS256, this is how a signature is created:</p><pre>HMACSHA256(<br>  base64UrlEncode(header) + &quot;.&quot; + base64UrlEncode(payload),<br>  &quot;qwertyuiopasdfghjklzxcvbnm123456&quot;<br>) <br>= A4YkEhGRoEwZHBzx-u-hCLYcmEKcTpliSOt2h3jtbQE</pre><p>If anyone modifies the payload, for example, changing role from “USER” to “ADMIN”, the signature becomes invalid and the token is rejected.</p><h3>Why JWT?</h3><p>Traditional <strong>session-based authentication</strong> requires servers to store session data and query it with every request. If you have multiple servers, sessions must be shared across them, creating complexity.</p><p><strong>JWT enables stateless authentication: </strong>Everything the server needs is in the token itself.</p><p>When a user makes a request:</p><ol><li>Server receives the JWT</li><li>Verifies the signature using a secret key</li><li>Reads claims directly from the payload</li><li>Makes authorization decisions, no database query needed</li></ol><p>Imagine you have a microservice with separate services for products, orders, inventory, and notifications.</p><p>With JWTs:</p><ul><li>Each service can independently verify tokens using the shared secret key (HS256) or public key (RS256)</li><li>No shared session store needed</li><li>Services remain decoupled and scale independently</li><li>When a user places an order, their token travels through all services, each verifying it independently</li></ul><p>You can also spin up 100 API server instances without worrying about session affinity; any server can handle any request.</p><h3>How Token Verification Works</h3><p>When the server receives a user’s token, here’s what happens:</p><h4><strong>Step 1–2: Extract and Decode</strong></h4><p>Server extracts the token from the <strong>Authorization header</strong> and decodes the header and payload from base64.</p><h4><strong>Step 3: Retrieve the Signing Key</strong></h4><p><strong>For Symmetric Algorithms (HS256):</strong> Uses a secret key stored in:</p><ul><li>Environment variables (JWT_SECRET=qwertyuiopasdfghjklzxcvbnm123456)</li><li>Secret management systems (AWS Secrets Manager, HashiCorp Vault)</li><li>Same key for signing and verification</li><li>All servers need access to this shared secret</li></ul><p><strong>For Asymmetric Algorithms (RS256):</strong></p><ul><li>Authentication server signs with private key (kept secret)</li><li>Other services verify with a public key (can be distributed freely)</li><li>Public keys are distributed via <strong>JWKS endpoints</strong>: <a href="https://auth.yourapp.com/.well-known/jwks.json">https://auth.yourapp.com/.well-known/jwks.json</a></li><li>More secure for microservices since services never see the private key</li></ul><h4><strong>Step 4–5: Verify Signature</strong></h4><p>Server recomputes the signature using the header, payload, and secret key, then compares it with the token’s signature. If they match, the token is authentic.</p><h4><strong>Step 6: Validate Claims</strong></h4><ul><li>Is it expired? (current time &lt; exp)</li><li>Is the issuer (iss) correct?</li><li>Is the audience (aud)correct?</li><li>Are the required claims present?</li></ul><p>If all checks pass, the user is authenticated.</p><p>The diagram below illustrates this flow:</p><figure><img alt="JWT Authentication Flow — Login and Resource Access" src="https://cdn-images-1.medium.com/max/753/1*D04_TwMJTHeZr7_42cWteQ.png" /></figure><h3>Token Refresh</h3><p>Since access tokens should be short-lived, you need refresh tokens to avoid constant re-authentication.</p><h4>Two-Token System</h4><p><strong>Access Token (JWT):</strong></p><ul><li>Short-lived (15 minutes to 1 hour)</li><li>Included in every API request (In the Authorization header)</li><li>Contains user claims</li><li>Can be stored in memory or localStorage</li></ul><p><strong>Refresh Token:</strong></p><ul><li>Long-lived (7–30 days)</li><li>Used only to get new access tokens</li><li>Random string (not a JWT)</li><li>Stored in httpOnly cookies</li><li>Stored in a database for revocation control</li></ul><h4>Token Refresh Flow</h4><p><strong>Login:</strong></p><pre>1. Client → Server: Login credentials (username and password)<br><br>2. Server → Client: Login response<br>{<br>  &quot;access_token&quot;: &quot;eyJ0eXAiOiJKV1QiLCJhbGc...&quot;,<br>  &quot;refresh_token&quot;: &quot;f5e8c7d4-a3b2-4f1e-9d8c...&quot;,<br>  &quot;expires_in&quot;: 1271<br>}</pre><p><strong>Making Requests:</strong></p><pre>Client → Server: In each request (for protected endpoints)<br><br>Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE3NjA3Mjc4MzEsImV4cCI6MTc2MDcyOTEwMiwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsImZpcnN0TmFtZSI6IkpvaG5ueSIsImxhc3ROYW1lIjoiUm9ja2V0IiwiZW1haWwiOiJqcm9ja2V0QGV4YW1wbGUuY29tIiwicm9sZSI6IlVTRVIiLCJ1c2VybmFtZSI6ImpvaG5ueXJvY2tldCIsInVzZXJJZCI6IlUwMDA3In0.A4YkEhGRoEwZHBzx-u-hCLYcmEKcTpliSOt2h3jtbQE</pre><p><strong>When Access Token Expires:</strong></p><pre>1. Client → Server: Token refresh endpoint<br>POST /auth/refresh<br>{ &quot;refresh_token&quot;: &quot;f5e8c7d4-a3b2...&quot; }<br><br>2. Server:<br>  1. Validates refresh token exists in database<br>  2. Checks expiration and revocation status<br>  3. Issues new access token (and optionally new refresh token)</pre><p><strong>Key Security Features:</strong></p><p><strong><em>Refresh Token Rotation</em></strong><em>:</em> Issue a new refresh token each time and invalidate the old one. If stolen, the token becomes invalid after legitimate use once.</p><p><strong><em>Database Storage</em></strong><em>:</em> Store refresh tokens (hashed) in your database with user_id, expiration, and revocation status. This allows immediate revocation when needed.</p><p><strong><em>Revocation</em></strong><em>:</em> When a user logs out or suspicious activity is detected, mark refresh tokens as revoked. This provides the “kill switch” that pure stateless JWTs lack.</p><p>The diagram below shows how the token refresh process works:</p><figure><img alt="JWT Token Refresh Flow" src="https://cdn-images-1.medium.com/max/829/1*CnYxsl5QwdyTCGZvgp-rHQ.png" /></figure><h3>Security Best Practices</h3><ul><li><strong>Never Store Sensitive Data</strong>: JWTs are encoded, not encrypted. Anyone can decode them.</li><li><strong>Always Set Expiration</strong>: Short-lived access tokens (15–60 min) limit exposure if compromised.</li><li><strong>Use Strong Algorithms</strong>: Stick with HS256 or RS256. Never use “none”.</li><li><strong>Strong Secret Keys</strong>: Use at least 256 bits of cryptographically random data. Generate with secure random generators (OpenSSL).</li><li><strong>Proper Storage</strong>: Use memory or <strong>httpOnly cookies</strong> for refresh tokens to prevent <strong>XSS attacks</strong>.</li><li><strong>Always Use HTTPS</strong>: Prevents token interception in transit.</li></ul><h3>Common Pitfalls to Avoid</h3><p><strong>(1) Token Size</strong>: JWTs are sent with every request. Adding too many claims creates performance issues</p><p><strong>Solution</strong>: Include only essential claims (userId, role). Fetch additional data via API calls when needed.</p><p><strong>(2) Token Revocation</strong>: Stateless JWTs can’t be immediately invalidated. If the user’s laptop is stolen, his access token remains valid until expiration.</p><p><strong>Solutions</strong>:</p><ul><li>Short expiration times (15–30 minutes)</li><li>Refresh token revocation in the database</li><li>Token blacklist using jti claim (reintroduces some state)</li><li>Token versioning in user records</li></ul><p><strong>(3) Clock Synchronization</strong>: Token expiration depends on <strong>synchronized clocks</strong>. Clock drift across servers can cause valid tokens to be rejected or expired tokens to be accepted.</p><p><strong>Solution</strong>: Use <strong>NTP </strong>(Network Time Protocol) to synchronize server clocks. Most cloud providers handle this automatically.</p><p><strong>(4) Overusing Claims</strong>: Don’t treat JWTs as a database. Including frequently changing data means users must re-authenticate to see updates.</p><p><strong>Solution</strong>: Include only stable, authorization-relevant data.</p><h3>When to Use JWT</h3><p><strong>Good Use Cases:</strong></p><ul><li>RESTful APIs serving multiple clients</li><li>Microservices with distributed authentication</li><li>Single Page Applications (SPAs)</li><li>Mobile applications</li><li>Stateless authentication requirements</li></ul><p><strong>Consider Alternatives When:</strong></p><ul><li>Building simple server-rendered apps</li><li>Need immediate token revocation</li><li>Complex, frequently-updated session data</li></ul><h3>Final Thoughts</h3><p>JWT has become the standard for modern authentication because it enables stateless, scalable authentication. In microservices, it allows independent verification without shared state. However, it requires careful implementation.</p><p><strong>Key Takeaways:</strong></p><ul><li>JWTs have three parts: header, payload, and signature</li><li>Stateless design eliminates server-side session storage</li><li>Verification uses secret keys (HS256) or public/private keys (RS256)</li><li>Use refresh tokens for longer sessions while keeping access tokens short-lived</li><li>Never put sensitive data in the payload; it’s encoded, not encrypted</li><li>Keep tokens small and set appropriate expirations</li></ul><p>Understanding these fundamentals will help you build secure, scalable authentication systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=849462715cbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java: StringBuilder vs StringBuffer: What’s the Real Deal?]]></title>
            <link>https://medium.com/@adheeshachamoddesilva/java-stringbuilder-vs-stringbuffer-whats-the-real-deal-1d63df9092be?source=rss-5739435eddfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d63df9092be</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Adheesha Chamod]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 11:53:51 GMT</pubDate>
            <atom:updated>2025-08-02T13:28:18.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*Ghoy-Ldy7FWSnbTGh7iXkw.jpeg" /><figcaption>StringBuilder vs StringBuffer</figcaption></figure><p>Hey! So you’re learning Java and came across these two similar-looking classes — <strong>StringBuilder </strong>and <strong>StringBuffer</strong>, right? Trust me, I was confused too when I first saw them. They look almost identical, but there’s actually an important difference that every Java developer should know.</p><p>Let me walk you through this step by step, and by the end, you’ll know exactly when to use which one and impress your interviewer if that’s what you’re after! 😇</p><h3>Why Do We Even Need These Classes?</h3><p>Before we jump into the differences, let’s understand why StringBuilder and StringBuffer exist in the first place.</p><p>In Java, regular strings are <strong>immutable</strong>. What does that mean? Once you create a string, you can’t change it. Every time you think you’re “modifying” a string, Java actually creates a brand new string object <em>(in the </em><strong><em>heap</em></strong><em>)</em>.</p><p>Check this out:</p><pre>public class StringExample {<br>    public static void main(String[] args) {<br>        String name = &quot;John&quot;;<br>        name = name + &quot; Doe&quot;;       // Creates a new string object!<br><br>        System.out.println(name);<br>    }<br>}</pre><p>Now imagine you’re building a long string by adding pieces one by one:</p><pre>public class StringConcatenationExample {<br>    public static void main(String[] args) {<br>        String result = &quot;&quot;;<br>        for (int i = 0; i &lt; 1000; i++) {<br>            result = result + &quot;Hello &quot;;   // Creates 1000 new string objects!<br>        }<br><br>        System.out.println(&quot;Final length: &quot; + result.length());<br>    }<br>}</pre><p>This is incredibly inefficient. You’re creating 1000 string objects in this process just to build one string. That’s where StringBuilder and StringBuffer come to the rescue.</p><h3>Meet StringBuilder and StringBuffer</h3><p>Both StringBuilder and StringBuffer are <strong>mutable</strong>. You can modify them without creating new objects every time. Think of them like expandable containers for characters.</p><p>Check this out:</p><pre>public class StringBuilderVsStringBufferExample {<br>    public static void main(String[] args) {<br>        // Using StringBuilder<br>        StringBuilder sb = new StringBuilder();<br>        sb.append(&quot;Hello&quot;);<br>        sb.append(&quot; &quot;);<br>        sb.append(&quot;World&quot;);<br>        <br>        String result1 = sb.toString();<br>        System.out.println(&quot;StringBuilder result: &quot; + result1);<br>        <br><br>        // Using StringBuffer<br>        StringBuffer sbf = new StringBuffer();<br>        sbf.append(&quot;Hello&quot;);<br>        sbf.append(&quot; &quot;);<br>        sbf.append(&quot;World&quot;);<br>        <br>        String result2 = sbf.toString();<br>        System.out.println(&quot;StringBuffer result: &quot; + result2);<br>    }<br>}</pre><p>Much better! Only one object, and we can keep adding to it.</p><h3>The Key Difference: Thread Safety</h3><p>Here’s the main difference between these two:</p><ul><li><strong>StringBuffer</strong> is <strong>thread-safe</strong> <em>(synchronized)</em></li><li><strong>StringBuilder</strong> is <strong>not thread-safe</strong> <em>(not synchronized)</em></li></ul><p>Wait, what does thread-safe mean? Imagine you have multiple threads <em>(think of them as workers)</em> trying to modify the same string at the same time.</p><p>With StringBuffer, Java makes sure only one thread can modify it at a time. With StringBuilder, multiple threads could try to modify it simultaneously, which could lead to corrupted data.</p><h3>When to Use Which?</h3><p>Here’s the simple rule:</p><p><strong>Use StringBuilder 99% of the time.</strong> Most of your Java programs run on a single thread, so you don’t need the thread safety overhead.</p><p><strong>Use StringBuffer only when:</strong></p><ul><li>You have multiple threads accessing the same string builder</li><li>You’re working with legacy code that already uses StringBuffer</li></ul><h3>Performance Difference</h3><p>Since StringBuffer has to deal with <strong>synchronization</strong>, it’s slower than StringBuilder.</p><p>Here’s a simple test:</p><pre>public class PerformanceComparisonTest {<br>    public static void main(String[] args) {<br>        long start;<br>        long end;<br>  <br>        // StringBuilder - faster<br>        StringBuilder sb = new StringBuilder();<br>        start = System.currentTimeMillis();<br>        for (int i = 0; i &lt; 100000; i++) {<br>            sb.append(&quot;test&quot;);<br>        }<br><br>        end = System.currentTimeMillis();<br>        System.out.println(&quot;StringBuilder: &quot; + (end - start) + &quot;ms&quot;);<br><br><br>        // StringBuffer - slower due to synchronization<br>        StringBuffer sbf = new StringBuffer();<br>        start = System.currentTimeMillis();<br>        for (int i = 0; i &lt; 100000; i++) {<br>            sbf.append(&quot;test&quot;);<br>        }<br><br>        end = System.currentTimeMillis();<br>        System.out.println(&quot;StringBuffer: &quot; + (end - start) + &quot;ms&quot;);<br>    }<br>}</pre><p>StringBuilder will typically be faster because it doesn’t have the synchronization overhead.</p><h3>Common Methods</h3><p>Both classes have the same methods.</p><p>Here are the most common ones:</p><pre>public class StringBuilderMethodsExample {<br>    public static void main(String[] args) {<br>        // Note: All these methods work exactly the same with StringBuffer<br>        // Just replace StringBuilder with StringBuffer if needed<br>        <br>        StringBuilder sb = new StringBuilder();<br><br>        // Adding content<br>        sb.append(&quot;Hello&quot;);<br>        sb.append(&quot; World&quot;);<br>        System.out.println(&quot;After append: &quot; + sb.toString());  // &quot;Hello World&quot;<br><br>        // Inserting at specific position<br>        sb.insert(5, &quot; Beautiful&quot;);<br>        System.out.println(&quot;After insert: &quot; + sb.toString());  // &quot;Hello Beautiful World&quot;<br><br>        // Deleting characters<br>        sb.delete(5, 15);<br>        System.out.println(&quot;After delete: &quot; + sb.toString());  // &quot;Hello World&quot;<br><br>        // Replacing characters<br>        sb.replace(0, 5, &quot;Hi&quot;); <br>        System.out.println(&quot;After replace: &quot; + sb.toString()); // &quot;Hi World&quot;<br><br>        // Converting to string<br>        String result = sb.toString();<br>        System.out.println(&quot;Final result: &quot; + result);<br><br>        // Getting length and capacity<br>        int length = sb.length();<br>        int capacity = sb.capacity();<br>        System.out.println(&quot;Length: &quot; + length + &quot;, Capacity: &quot; + capacity);<br>    }<br>}</pre><h3>A Real-World Example</h3><p>Let’s say you’re building a CSV file from data:</p><pre>import java.util.Arrays;<br>import java.util.List;<br><br>public class CSVBuildingExample {<br>    public static void main(String[] args) {<br>        // Create sample users for demonstration<br>        List&lt;User&gt; users = Arrays.asList(<br>            new User(&quot;John&quot;, 25),<br>            new User(&quot;Jane&quot;, 30),<br>            new User(&quot;Bob&quot;, 35)<br>        );<br>        <br><br>        // Bad way - creates many string objects<br>        String csv1 = &quot;&quot;;<br>        for (User user : users) {<br>            csv1 = csv1 + user.getName() + &quot;,&quot; + user.getAge() + &quot;\n&quot;;<br>        }<br><br>        System.out.println(&quot;Bad way result:&quot;);<br>        System.out.println(csv1);<br>        <br><br>        // Good way - uses StringBuilder<br>        StringBuilder csvBuilder = new StringBuilder();<br>        for (User user : users) {<br>            csvBuilder.append(user.getName())<br>                      .append(&quot;,&quot;)<br>                      .append(user.getAge())<br>                      .append(&quot;\n&quot;);<br>        }<br><br>        String csv2 = csvBuilder.toString();<br>        System.out.println(&quot;Good way result:&quot;);<br>        System.out.println(csv2);<br>    }<br>    <br><br>    // Simple User class for demonstration<br>    static class User {<br>        private String name;<br>        private int age;<br>        <br>        public User(String name, int age) {<br>            this.name = name;<br>            this.age = age;<br>        }<br>        <br>        public String getName() { return name; }<br>        public int getAge() { return age; }<br>    }<br>}</pre><p>Notice how I chained the append calls? That’s because these methods return the StringBuilder object itself, so you can chain them together.</p><h3>Interview Questions You Might Face</h3><p><strong>Q: What’s the difference between StringBuilder and StringBuffer?</strong></p><p><em>A: StringBuffer is thread-safe (synchronized) while StringBuilder is not. StringBuilder is faster for single-threaded applications.</em></p><p><strong>Q: When would you use StringBuffer over StringBuilder?</strong></p><p><em>A: When you have multiple threads that need to modify the same string builder simultaneously.</em></p><p><strong>Q: Why not just use regular String concatenation?</strong></p><p><em>A: Because strings are immutable in Java. Each concatenation creates a new string object, which is inefficient for multiple operations.</em></p><h3>Quick Tips</h3><ul><li><strong>Default capacity:</strong> Both start with a capacity of 16 characters. If you know you’ll need more, set it up front: new StringBuilder(100)</li><li><strong>Method chaining:</strong> Take advantage of it — sb.append(&quot;Hello&quot;).append(&quot; &quot;).append(&quot;World&quot;)</li><li><strong>Don’t forget </strong>toString()<strong>:</strong> Remember to convert back to a String when you&#39;re done</li><li><strong>Modern alternatives:</strong> For simple cases, consider String.join() or String.format()</li></ul><h3>Wrapping Up</h3><p>So there you have it! StringBuilder and StringBuffer are almost twins, with StringBuilder being the faster, more commonly used sibling, and StringBuffer being the thread-safe one that you’ll rarely need.</p><p>The most important thing to remember is that both are way better than regular string concatenation when you’re building strings piece by piece. Your code will be faster, and your memory usage will be much more efficient.</p><p>If you enjoyed this article, share your experiences or insights. Also, share this with others who might find it valuable. 😉</p><p>Happy coding! 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d63df9092be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Impact of Extensive Testing: How Weeks of Bug Fixing Transformed My Skills]]></title>
            <link>https://medium.com/@adheeshachamoddesilva/the-impact-of-extensive-testing-how-weeks-of-bug-fixing-transformed-my-skills-ecffc3dfb7f3?source=rss-5739435eddfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecffc3dfb7f3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[bug-fixing]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[skill-development]]></category>
            <category><![CDATA[api-design]]></category>
            <dc:creator><![CDATA[Adheesha Chamod]]></dc:creator>
            <pubDate>Thu, 10 Oct 2024 13:38:42 GMT</pubDate>
            <atom:updated>2024-10-22T05:52:44.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image to show how software bugs behave." src="https://cdn-images-1.medium.com/max/1024/1*hrxk7XAPLMk3MXI-cQo8NQ.jpeg" /></figure><p>As a young software engineer, working with my team on an API design tool called <a href="https://xapihub.io/">Xapi</a> has been a challenging yet rewarding experience. What began as an exciting project suddenly became a marathon of debugging and testing that lasted for weeks. But, as difficult as it was, this lengthy testing process uncovered issues that transformed not only the product but also my skill set as a software engineer. In this blog, I will share my experiences with you.</p><h3><strong>Uncovering Hidden Issues</strong></h3><p>We were excited when we first published our product. The user interface was sleek, the backend was robust, and everything appeared to be perfect during the initial testing phase. However, as the tool grew in popularity and more complicated use cases were discovered, we began to see an increase in the number of <strong>bugs</strong>. <em>This is the reality of software development. </em>🙂</p><p>At first, there were minor issues, like UI inconsistencies or rare backend issues that happened only in specific edge cases. But as we go deeper, we discovered that these “minor” issues, frequently led to major functional breakdowns. Some issues impacted the usability of our product making users frustrated, while others affected the underlying logic of the <strong>API designing</strong> feature, which is our core feature. This was a wake-up call.</p><p>Each bug fix revealed a new layer of complexity. With every fix, we discovered hidden dependencies across the systems. For example, a simple modification in the backend resulted in an unexpected error in the frontend.</p><h3><strong>Upgrading My Skills Through Hands-On Experience</strong></h3><p>This intense period of testing forced me to revisit my development skills. While I had a good understanding of Java, Spring Boot, API design, and API development, this deep dive into <strong>debugging </strong>made me realize how crucial error handling and reliable testing are. Here are some of the key areas where I grew:</p><h4><strong>(1) Understanding frontend and backend interaction</strong></h4><p>I began to realize how important it is for the frontend and backend to function smoothly together. A simple modification in the backend that led to an unexpected frontend error, taught me the importance of communication between the two sides of the application. This pushed me to improve my skills in debugging frontend while balancing them with backend logic.</p><h4><strong>(2) Mastering Testing tools and automation</strong></h4><p>We quickly realized that <strong>manual testing</strong> wasn’t enough. When it comes to our application, it is impossible to test every process manually every time, as there are many complex and long processes. I got hands-on experience with tools like <a href="https://junit.org/junit5/">JUnit </a>for <strong>unit testing</strong> and <a href="https://www.postman.com/product/what-is-postman/">Postman </a>for <strong>API testing</strong>. By setting up <strong>automated tests</strong> with tools like <a href="https://www.cypress.io/">Cypress </a>and <a href="https://karatelabs.github.io/karate/">Karate</a>, we quickly caught <strong>regression issues</strong> as we fixed bugs. That helped us to focus on new issues rather than worrying about breaking existing functionalities.</p><h4><strong>(3) Improved problem-solving and debugging skills</strong></h4><p>Every bug that was reported was a puzzle waiting to be solved. It pushed me to think critically and break down complex issues into smaller, manageable tasks — <strong>the divide-and-conquer method</strong>. This experience helped me approach debugging systematically and tracking down root causes instead of just fixing symptoms.</p><h4><strong>(4) Better collaboration and communication</strong></h4><p>I also learned the value of working with teammates to resolve issues. Each bug revealed an opportunity for knowledge-sharing and collaboration between the frontend, backend, and <strong>QA</strong> teams, making it easier to track down issues more easily.</p><h3><strong>Good Development and Testing Practices for a Resilient Product</strong></h3><p>Looking back, I can confidently say that without this extensive testing and debugging phase, Xapi would have been less reliable and user-friendly. To deliver a resilient, quality, and usable product that customers love. Here are some strategies we used that might help any development team to produce a robust, high-quality, resilient, and usable product that clients adore:</p><h4><strong>(1) Test early, test often</strong></h4><p>Don’t wait until the product is near completion to start testing. Begin testing as soon as the first feature is developed. Keep testing as you go. This allows for <strong>early detection</strong> of bugs before they become deeply embedded in the system.</p><h4><strong>(2) Automate testing</strong></h4><p>Use tools like Cypress and Karate for automated testing. Automated tests catch <strong>regression issues</strong> quickly and ensure that new code doesn’t break existing functionality. This is the most important strategy.</p><h4><strong>(3) Have a dedicated QA team</strong></h4><p>While developers should write and run their own tests, having a dedicated QA team to run more comprehensive and exploratory tests can uncover <strong>edge cases</strong> that developers might overlook.</p><h4><strong>(4) Use realistic as well as unrealistic data for testing</strong></h4><p>Testing with dummy data is fine for initial tests, but real-world scenarios often behave differently. Use realistic data or data that mirrors actual usage patterns to uncover real-world issues during testing. Also, it is necessary to do testing with unrealistic data, as we don’t know how the user will use our products and in such events, to ensure product stability.</p><h4><strong>(5) Invest in Continuous Integration and </strong>Continuous <strong>Deployment (CI/CD)</strong></h4><p>Setting up <strong>CI/CD pipelines</strong> ensures that every new piece of code is automatically tested and deployed. This allows teams to catch issues early and deploy fixes faster.</p><h4><strong>(6) Prioritize User Experience (UX)</strong></h4><p>Although end users may not notice backend issues, UI (User Interface) issues have the power to significantly impact the user experience as they are more noticeable. Make sure the UI is responsive, functional, and intuitive by extensively testing it.</p><h4><strong>(7) Have regular code reviews</strong></h4><p>Your code could seem to be perfect to you, but from another one’s perspective, it would not be perfect. So, encourage team members to review each other’s code. Code reviews help catch logical issues and bugs early in the development stage and lead to higher-quality, manageable and more readable code.</p><h4><strong>(8) Document bugs and fixes</strong></h4><p>Keep a detailed log of all bugs reported, the solutions applied, and the tests performed. You can do this by using project management tools like <a href="https://www.atlassian.com/software/jira">Jira</a>. This documentation helps in tracking recurring issues and provides valuable insight when similar problems arise in the future.</p><h3><strong>Conclusion</strong></h3><p>Testing and bug fixing take more time, but they are essential to produce a high-quality, resilient, and usable product. For me, this extensive process not only improved our project but also transformed my development skills to a whole new level. Even though bugs can be annoying, they also present chances for growth and learning.</p><p>By adopting good development and testing practices early, we can create products that users love and trust, all the while advancing our own professional development.</p><p>Finally, this is an open invitation to all curious readers, have a look by yourself if I lied or not: <a href="https://xapihub.io/"><strong>https://xapihub.io</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecffc3dfb7f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering: Understand the Prompting Techniques]]></title>
            <link>https://medium.com/@adheeshachamoddesilva/prompt-engineering-understand-the-prompting-techniques-7ecf829b35f8?source=rss-5739435eddfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ecf829b35f8</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[prompting-technique]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Adheesha Chamod]]></dc:creator>
            <pubDate>Sat, 24 Feb 2024 11:21:20 GMT</pubDate>
            <atom:updated>2024-02-24T11:21:20.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A vibrant abstract cityscape, with geometric shapes and bold colors, reminiscent of the works of Piet Mondrian." src="https://cdn-images-1.medium.com/max/768/1*jtQZnxfqko7n7HbA_dKFLA.jpeg" /><figcaption>Generated using Leonardo.Ai</figcaption></figure><p><em>Prompting techniques, help to guide LLMs (Large Language Models) like ChatGPT, Gemini, Microsoft Copilet, etc to boost output performance.</em></p><p><em>In my previous blog post “</em><a href="https://medium.com/@adheeshachamoddesilva/prompt-engineering-understand-the-prompt-patterns-d724e0fb966b"><em>Prompt Engineering: Understand the Prompt Patterns</em></a><em>”, I covered the six most useful prompt patterns. But in some situations, we can’t follow the prompt patterns for prompting. In such situations, we have to go with the “Prompting Techniques”. So, as the third part of the “Prompt Engineering” series, I thought it is better to cover prompting techniques.</em></p><p><em>Let’s start the topic.</em></p><p><strong>Prompting Techniques</strong></p><p>Here, I’m focusing on four of the most useful prompting techniques.</p><p>They are:</p><ol><li>Zero-shot Prompting</li><li>Few-shot Prompting</li><li>Chain-of-Thought Prompting (CoT)</li><li>Zero-shot CoT Prompting</li></ol><p><strong>(1) Zero-shot Prompting</strong></p><p>Under this technique, we consider the number of examples in a prompt. Here, there is no (zero) example at all.</p><p>Try the example prompt below.</p><p><em>Ex 1.1:</em></p><pre>Text: I think the vacation is okay.<br>Sentiment:</pre><p>In the above example prompt, there is no example in the prompt. Because of that, we can take it as a zero example prompt. So, it is a Zero-shot prompt.</p><p>If you didn’t get the idea, you will get a clear idea from the next section.</p><p><strong><em>Note:</em></strong><em><br>The example 1.1 has no examples in it. However, it gives a suitable answer. But try to provide examples in complex prompts to get the most suitable answers, otherwise, the LLM could misguide and give the incorrect answers.</em></p><p><strong>(2) Few-shot Prompting</strong></p><p>Here also, we consider the number of examples in a prompt. But not like in the Zero-shot prompting, under this technique, there should be at least one example in a prompt.</p><p>Consider the example prompts below. I highly recommend you to try these by yourself to get more understanding.</p><p><em>Ex 2.1:</em></p><pre>Question: &quot;What is the capital of the United States?&quot;<br>Answer: &quot;The capital of the United States is Washington D.C.&quot;<br><br>Question: &quot;What is the capital of France?&quot;<br>Answer:</pre><p><em>Ex 2.2:</em></p><pre>Beginning: &quot;Once upon a time, in a kingdom far away, there was a brave knight named Arthur.&quot;<br>Ending: &quot;After many battles, Arthur defeated the dragon and saved the kingdom.&quot;<br><br>Beginning: &quot;In the dense forests of the north, a cunning fox named Ray lived.&quot;<br>Ending: &quot;Using his wit, Ray outsmarted the wolf and proved that brains could win over brawn.&quot;<br><br>Beginning: &quot;In the heart of bustling New York, lived a timid pigeon named Pete.&quot;<br>Ending:</pre><p>If you tried the above examples, you would notice that the LLM gives the most suitable answer without much information. <em>How cool is that?</em></p><p>If you remember, in example 1.1, there were zero examples and, in that case, it is called a <strong>Zero-shot prompt</strong>. In example 2.1, there is one example. So, it is a <strong>One-shot prompt</strong>. When it comes to the example 2.2, there are two examples. So, it is a <strong>Two-shot prompt</strong>.</p><p>Likewise, according to the number of examples that a prompt has, we can categorize it.</p><p>What about if there are N number of examples in a prompt?</p><p>It is a <strong>N-shot prompt</strong></p><p><strong><em>Note:</em></strong><em><br>Few-shot prompting tends to provide more accurate answers than Zero-shot prompting. So, if it is possible, try to go with Few-shot prompting.</em></p><p><strong>(3) Chain-of-Thought Prompting (CoT)</strong></p><p>Try the example prompt below, which is created using Few-shot prompting.</p><p><em>Ex 3.1:</em></p><pre>Q: The odd numbers in this group add up to an even number: 4, 8, 9, 15, 12, 2, 1.<br>A: False<br><br>Q: The odd numbers in this group add up to an even number: 17,  10, 19, 4, 8, 12, 24.<br>A: True<br><br>Q: The odd numbers in this group add up to an even number: 16,  11, 14, 4, 8, 13, 24.<br>A: True<br><br>Q: The odd numbers in this group add up to an even number: 17,  9, 10, 12, 13, 4, 2.<br>A: False<br><br>Q: The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1. <br>A:</pre><p>If you tried the above example, the answer most probably would be wrong. This happens because the LLM rushes to provide the answer without <strong>“thinking”</strong>. So, how can we ask LLM to “think”, or can we do such a thing?</p><p>Yes! Consider the below example prompt to understand how we can do that.</p><p><em>Ex 3.2:</em></p><pre>Q: The odd numbers in this group add up to an even number: 4, 8, 9, 15, 12, 2, 1.<br>A: Adding all the odd numbers (9, 15, 1) gives 25. The answer is False.<br><br>Q: The odd numbers in this group add up to an even number: 17,  10, 19, 4, 8, 12, 24.<br>A: Adding all the odd numbers (17, 19) gives 36. The answer is True.<br><br>Q: The odd numbers in this group add up to an even number: 16,  11, 14, 4, 8, 13, 24.<br>A: Adding all the odd numbers (11, 13) gives 24. The answer is True.<br><br>Q: The odd numbers in this group add up to an even number: 17,  9, 10, 12, 13, 4, 2.<br>A: Adding all the odd numbers (17, 9, 13) gives 39. The answer is False.<br><br>Q: The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1. <br>A:</pre><p>The second example is created using the CoT prompting technique. If you tried this, you would notice that the answer is correct. Try to analyze the difference between examples 3.1 and 3.2.</p><p>In example 3.2, unlike in example 3.1, the thinking process (chain of thought…) to get the answer is included.</p><p>When the LLM go through the prompt, it notices the pattern that the example answer is in and, the LLM also tries to follow the same pattern when providing the answer instead of rushing only to the answer. Because of this, LLM has to “think” before answering.</p><p>Consider this as well to get a clear idea about this technique.</p><figure><img alt="Example for the CoT process" src="https://cdn-images-1.medium.com/max/940/1*1MOYUR4DYmm0U9pPqG5jTQ.jpeg" /><figcaption><a href="https://images.app.goo.gl/2aVdwkUckbtPGpGs6">Source</a></figcaption></figure><p><strong><em>Note:</em></strong><em><br>In some situations, like in example 3.1, the Few-shot technique could fail. So, it is better to use the CoT technique for complex scenarios.</em></p><p><strong>(4) Zero-shot CoT Prompting</strong></p><p>This is a combination of Zero-shot prompting and the CoT prompting. But, unlike in the CoT technique, this technique follows the CoT process, without examples.</p><p>Try the example prompt below.</p><p><em>Ex 4.1:</em></p><pre>I went to the market and bought 10 apples. <br>I gave 2 apples to the neighbour and 2 to the repairman. <br>I then went and bought 5 more apples and ate.<br><br>How many apples did I remain with?</pre><p>If you tried the above example prompt, probably the answer would be wrong. Now try the below prompt example.</p><p><em>Ex 4.2:</em></p><pre>I went to the market and bought 10 apples. <br>I gave 2 apples to the neighbour and 2 to the repairman. <br>I then went and bought 5 more apples and ate.<br> <br>How many apples did I remain with?<br>Let&#39;s think step by step.</pre><p>The second example is created using the Zero-shot CoT technique. If you tried this, you would notice that the answer is correct. Try to analyze the difference between examples 4.1 and 4.2.</p><p>The two examples are mostly the same, but the second one has an additional sentence “Let’s think step by step”.</p><p>Because of the sentence “Let’s think step by step”, the LLM tries to provide the answer with analytics, instead of rushing to the answer. This is also a technique to encourage the LLM to “think”. This is also pretty helpful since the answer has the thinking process and the user can use that to get a clear idea. So that the user can determine whether the answer is suitable or not from his perspective.</p><p><strong><em>Note:</em></strong><em><br>There could be a doubt like, “What prompting technique should I use?”. This is where the experience came into the picture. With the experience, you will understand what is the suitable technique that you should use.</em></p><p>This is the end of our topic and hope you got a clear idea about the prompting techniques. Try these by your self and you will figure out your own ways to write efficient prompts using prompting techniques.</p><p>If you enjoyed this small article, share your experiences or insights in the comments section. Also, share this with others who might find it valuable and click on the clap 👏 button to show your appreciation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ecf829b35f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering: Understand the Prompt Patterns]]></title>
            <link>https://medium.com/@adheeshachamoddesilva/prompt-engineering-understand-the-prompt-patterns-d724e0fb966b?source=rss-5739435eddfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d724e0fb966b</guid>
            <category><![CDATA[prompt-pattern]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <dc:creator><![CDATA[Adheesha Chamod]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 13:41:12 GMT</pubDate>
            <atom:updated>2024-02-03T13:41:12.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*MZvxG6a6I5SINjez0H8u2Q.jpeg" /><figcaption>Generated using Leonardo.Ai</figcaption></figure><p>In Prompt Engineering, having a good understanding of “Prompt Patterns” is crucial to write prompts to get effective answers.</p><p>So, as the second part of the “Prompt Engineering” series, I thought it is best to cover prompt patterns. In the first part of this series, I talked about the <a href="https://medium.com/@adheeshachamoddesilva/prompt-engineering-understand-the-key-elements-of-a-prompt-41c8742d7143">Key Elements of a Prompt</a>. If you are interested, refer it to learn more.</p><p>Let’s start the topic.</p><p><strong>What is a prompt pattern?</strong></p><p>Simply, it is a predefined format for a prompt. It helps to structure clear prompts. So, that can be easily understood by AI models like ChatGPT, Bard, Microsoft Copilot etc and provide effective answers.</p><p>Here, I’m going to talk about the 6 most essential prompt patterns that we can use in prompting.</p><p>They are:</p><ol><li>Persona Pattern</li><li>Audience Persona Pattern</li><li>Output Automator Pattern</li><li>Flipped Interaction Pattern</li><li>Context Manager Pattern</li><li>Reflection Pattern</li></ol><p>Now let’s focus on each of these patterns one by one.</p><p><strong>(1) Persona Pattern</strong></p><p>Contextual statement:</p><ul><li>Act as Persona X.</li><li>Perform task Y.</li></ul><p>Here, what we do is, we ask the AI model to pretend to be someone or ask to play the role of someone and perform the given task.</p><p>Try the below example prompts on your preferred AI model. <em>(try to use separate chats)</em></p><pre>Assume, you are a communications specialist. <br>Draft an email to your client advising them about a delay in the delivery schedule due to logistical problems.</pre><pre>Assume, you are a marketing expert. <br>Draft an email to a client advising them about a delay in the delivery schedule due to logistical problems.</pre><p>If you tried the above example prompts, you can see there is a clear difference between the two answers.</p><p><strong>(2) Audience Persona Pattern</strong></p><p>Contextual statements:</p><ul><li>Explain X to me.</li><li>Assume that I am Persona Y.</li></ul><p>Here, we ask AI to explain or deliver something to a specific audience. So, AI adjusts its task according to its audience.</p><p>Try the prompt examples below.</p><pre>Explain the use of prompt patterns. <br>Assume the audience is not well aware of this topic.</pre><pre>Explain the plot of the &quot;Game of Thrones&quot; series to me. <br>Assume that I am someone who has never watched a single episode.</pre><p>Try changing the audience and, see the difference by yourself.</p><p><em>I used the first prompt to get an idea to write this article. ^_^</em></p><p><strong>(3) Output Automator Pattern</strong></p><p>Contextual statements:</p><ul><li>Whenever you produce an output, consider step X or property Y.</li></ul><p>Simply, it is like this: “When I ask to do X, always do Y”.</p><p>Consider the following example prompts.</p><pre>From now on, whenever I ask you to compare something, use tabular format.</pre><pre>From now on, whenever I ask you to explain something, provide a detailed description.<br>Use simple English and simple sentences, since I&#39;m not pretty good at English.</pre><p>This type of prompt has to be executed at the top of the chat (or conversation) because here, we ask AI to structure the answers according to given steps or properties.</p><p>If you carefully went through the second example, you would understand that I used two prompt patterns at the same time. They are the output automator pattern and the audience persona pattern.</p><p>You can combine several prompt patterns according to your scenario. But always try to be simple.</p><p><strong>(4) Flipped Interaction Pattern</strong></p><p>Contextual statements:</p><ul><li>I would like you to ask me questions to achieve X.</li><li>You should ask questions until condition Y is met.</li></ul><p>You can use any contextual statements from the above two types, according to your scenario.</p><p>Consider the example prompts below.</p><pre>I want to improve my knowledge of &quot;Data Structures and Algorithms&quot;.<br>Ask me questions about this topic.</pre><pre>Assume you are an interviewer and you interview me for the position of software engineer intern at your company.<br>So, ask me 20 trivial questions.<br>Begin with the first question.</pre><p>Normally, we are the ones who ask questions from the AI. But now AI ask questions from us. So, this is what happens in this pattern, we flip the interaction.</p><p>I used two prompt patterns in the second example. Try to figure it out.</p><p><em>I used the second prompt to get ready for my interview. However, some of the questions were similar to the questions that the interviewer asked me. So, this pattern comes in handy for that kind of situation.</em></p><p><strong>(5) Context Manager Pattern</strong></p><p>Contextual statements:</p><ul><li>Within scope X.</li><li>Please consider Y.</li><li>Please ignore Z.</li></ul><p>This pattern helps to manage the content of the responses given by the AI models.</p><p>Consider the prompt example below.</p><pre>For our discussion about AI, only consider its applications in healthcare. <br>Please ignore its applications in other industries such as finance or entertainment.<br>Let&#39;s start.</pre><p><strong>(6) Reflection Pattern</strong></p><p>Contextual statements:</p><ul><li>Whenever you generate an answer.</li><li>Explain the reasoning and assumptions behind your answer.</li></ul><p>Consider the prompt examples below and try to get the idea by yourself.</p><pre>Whenever I ask you to generate a code in Java, try to provide the reasons for each line, since I&#39;m new to programming using Java.</pre><pre>Whenever I ask you to optimize my code, try to provide reasoning for each of your changes.</pre><p>This is the end of our topic and hope you got a clear idea about the prompt patterns. Try these by your self and you will figure out your own ways to write efficient prompts using prompt patterns.</p><p>If you enjoyed this small article, share your experiences or insights in the comments section. Also, share this with others who might find it valuable and click on the clap 👏 button to show your appreciation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d724e0fb966b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompt Engineering: Understand the Key Elements of a Prompt]]></title>
            <link>https://medium.com/@adheeshachamoddesilva/prompt-engineering-understand-the-key-elements-of-a-prompt-41c8742d7143?source=rss-5739435eddfc------2</link>
            <guid isPermaLink="false">https://medium.com/p/41c8742d7143</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Adheesha Chamod]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 20:07:08 GMT</pubDate>
            <atom:updated>2024-01-25T06:26:54.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mEohXNpxuqCfk6FQcZppDw.jpeg" /></figure><p><em>In these days, AI is a topic that we can’t avoid from talking about. Many people use AI in their day-to-day lives because It helps to make work easier. But their capabilities are limited. If we can use them effectively, we can get more from them. So, I thought it is best to cover, how to use AI effectively to do our work. But when it comes to this topic, it is pretty huge and I can’t cover all of them. Because of that I limited my scope to “Prompt Engineering”. So, this is the first part of the “Prompt Engineering” series.</em></p><p><em>This is specifically for you if you are someone related to the IT field.</em></p><p><strong>What is a prompt?</strong></p><p>According to Wikipedia,</p><p><em>“A prompt is a natural language text describing the task that an AI should perform.”</em></p><p>Let’s highlight key points.</p><p>First, a prompt is a natural language text, which means it is more human-readable, and human-friendly. It is not some kind of a programming language or something. Secondly, a prompt describes the task that an AI model should perform Which means it is a kind of thing that we use to communicate with AI to achieve something.</p><p>If you have experience in using ChatGPT, Bard or Microsoft Copilot, the prompt is the text that you type in the given input field from those platforms.</p><p><strong>What is prompt engineering?</strong></p><p>According to Wikipedia,</p><p><em>“Prompt engineering is the process of structuring text that can be interpreted and understood by a generative AI model”</em></p><p>Here text refers to prompts. So, prompt engineering is the process of crafting prompts for AI to understand and provide responses. This process involves choosing correct words and suitable phrasing. So, definitely, it needs skills. But this is not to discuss those. Here we are focusing on the key elements of a prompt since understanding the basics is a must.</p><p><em>(If you are interested, generative AIs are content creators based on the given prompts. They can create texts, images, videos and audio according to instructions they get)</em></p><p>So, with a kind of background knowledge, let’s start the topic.</p><p><strong>What are the key elements of a prompt?</strong></p><p>There is no specific standard for this. But based on many resources, I can say there are 5 elements.</p><ol><li>Role</li><li>Instruction / Task</li><li>Question</li><li>Context</li><li>Example</li></ol><p>To get the idea simply, assume these are like sections from a text. There is no specific order to place these elements in a prompt. Also, there is no need to have all the elements in a single prompt.</p><p>Now let’s focus on each of these elements one by one.</p><ol><li><strong>Role</strong></li></ol><p>Specifying a role in a prompt is a great technique that can be used to control the style of a response. This improves the AI’s accuracy when generating responses. Consider the following example prompts to get the idea.</p><p>Ex:</p><pre>Assume, you are a communication specialist. Draft an email to your client advising him/her about a delay in the delivery schedule due to logistical problems.</pre><pre>Assume, you are a marketing expert. Draft an email to a client advising him/her about a delay in the delivery schedule due to logistical problems.</pre><p>Try this by yourself, and you can see a clear difference between the 2 answers.</p><p><strong>2. Instruction / Task</strong></p><p>Consider the following prompt example.</p><p>Ex:</p><pre>Read the following paragraph from an essay and provide feedback based on the following criteria: grammar, clarity, coherence, argument quality, and use of evidence. Provide only the score from 1–10 for each attribute.<br><br>&quot;Despite the popular belief, there&#39;s no solid evidence supporting the idea that video games lead to violent behavior. Research on the topic is often contradictory and inconclusive. Some studies found a correlation, but correlation don&#39;t imply causation. So, it&#39;s premature to blame video games for violence in society.&quot;</pre><p>If you get the idea, you will understand the first paragraph holds the task and the instructions. Based on the instruction, a generative AI model will perform the task.</p><p><strong>3. Question</strong></p><p>In this context, the question is a thing that we ask from a generative AI. Consider the following examples.</p><p>Ex:</p><pre>What is the capital of France?</pre><pre>What is the tallest building in the world?</pre><p>If you see clearly, there is only one key element in the above prompts. Which is only the question, no task, no instructions and no role specified.</p><p><strong>4. Context</strong></p><p>Context is any relevant information that you want the AI model to use when generating responses.</p><p>Ex:</p><pre>January 1, 2000: Fractured right arm playing basketball. Treated with a cast.<br>February 15, 2010: Diagnosed with hypertension. Prescribed lisinopril.<br>September 10, 2015: Developed pneumonia. Treated with antibiotics and recovered fully.<br>March 1, 2022: Sustained a concussion in a car accident. Admitted to the hospital and monitored for 24 hours.<br><br>Assume you are a doctor. Read this medical history and predict risks for the patient.</pre><p>If you saw, there are 3 key elements in this prompt. Those are role, task and context.</p><p><em>Pro tip: Try to divide sections clearly in your prompts. It will help the AI model to get a clear idea without any other instructions.</em></p><p><strong>5. Example</strong></p><p>This is the section that most people don’t include in their prompts. Consider the following prompt example and I highly recommend to try it by yourself.</p><p>Ex:</p><pre>Beginning: &quot;Once upon a time, in a kingdom far away, there was a brave knight named Arthur.&quot;<br>Ending: &quot;After many battles, Arthur defeated the dragon and saved the kingdom.&quot;<br><br>Beginning: &quot;In the dense forests of the north, a cunning fox named Ray lived.&quot;<br>Ending: &quot;Using his wit, Ray outsmarted the wolf and proved that brains could win over brawn.&quot;<br><br>Beginning: &quot;In the heart of bustling New York, lived a timid pigeon named Pete.&quot;<br>Ending:</pre><p>If you tried the above prompt by yourself, you will understand that without any instruction or task, it will give us a suitable response. Like this example, sometimes examples help us to tell things easily to AI models and also it lead us to get more effective responses.</p><p>This is the end of our topic and hope you got some kind of idea about the key elements of a prompt. Try these by your self and you will figure out your own ways to write efficient prompts.</p><p>If you enjoyed this small article, share your experiences or insights in the comments section. Also, share this with others who might find it valuable and click on the clap 👏 button to show your appreciation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41c8742d7143" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>