<?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 Sparsh Agarwal on Medium]]></title>
        <description><![CDATA[Stories by Sparsh Agarwal on Medium]]></description>
        <link>https://medium.com/@sparsh_aggarwal?source=rss-fc809be53545------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KzppQEHEVdGcxPg2T8axCw.png</url>
            <title>Stories by Sparsh Agarwal on Medium</title>
            <link>https://medium.com/@sparsh_aggarwal?source=rss-fc809be53545------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 22:56:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sparsh_aggarwal/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[Unicode Demystified: From Code Points to Emoji, Endianness, and Attacks]]></title>
            <link>https://medium.com/@sparsh_aggarwal/unicode-demystified-from-code-points-to-emoji-endianness-and-attacks-dab52407d496?source=rss-fc809be53545------2</link>
            <guid isPermaLink="false">https://medium.com/p/dab52407d496</guid>
            <category><![CDATA[utf16]]></category>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[unicode]]></category>
            <category><![CDATA[utf-8]]></category>
            <dc:creator><![CDATA[Sparsh Agarwal]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 09:08:14 GMT</pubDate>
            <atom:updated>2026-09-05T09:08:14.442Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Unicode Demystified: From Code Points to Emoji, Endianness, and Attacks</strong></p><figure><img alt="unicode" src="https://cdn-images-1.medium.com/max/1024/0*gvQowM3I-_2vwarv" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Why should you care?</strong></p><p>Every string you’ve ever typed, stored, or sent over a network is text. And text is one of those things that <em>looks</em> simple until it isn’t. Why does an emoji sometimes count as 2 characters? Why does café sometimes not match café in search? Why does apple.com in your address bar sometimes hide a phishing site?</p><p>The answers all live in one place: <strong>Unicode</strong> and how it gets <strong>encoded</strong> into bytes. Let’s build the whole picture from the ground up.</p><ol><li><strong>Unicode: a giant lookup table</strong></li></ol><p>Start with the simplest mental model.</p><p><strong>Unicode is a standard that gives every character a unique number.</strong> That’s it. A letter, a symbol, a Chinese ideograph, an emoji — each gets one number called a <strong>code point</strong>, written as U+ followed by hexadecimal.</p><pre>&#39;A&#39; → U+0041<br>&#39;é&#39; → U+00E9<br>&#39;京&#39; → U+4EAC<br>&#39;😀&#39; → U+1F600</pre><p>Unicode does <strong>not</strong> say anything about bytes, storage, or memory. It’s purely a <strong>character → number</strong> dictionary.</p><p><strong>How big is the dictionary?</strong></p><pre>Code space: U+0000 ──────────────► U+10FFFF<br><br>= 1,114,112 possible code points (17 “planes” of 65,536)<br><br>Actually assigned so far: ~150,000 characters (~15% used)</pre><p><strong>Deep dive:</strong> The first plane (U+0000–U+FFFF) is the <strong>Basic Multilingual Plane (BMP)</strong> — it holds almost every character in modern common use. Everything above U+FFFF (emoji, historic scripts, rare CJK) lives in the <strong>supplementary planes</strong>. This BMP-vs-supplementary split matters a lot later when we hit UTF-16.</p><p><strong>2. Encoding: turning numbers into bytes</strong></p><p>Unicode gives you a number. But computers store <strong>bytes</strong>. An <strong>encoding</strong> is the rule for converting a code point into a sequence of bytes (and back).</p><p>The same code point can be encoded different ways depending on the scheme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKKDuRZ_6qgV_aaPrF9GpQ.png" /></figure><p>So <strong>Unicode = the character set</strong>, <strong>UTF-8/16/32 = ways to serialize it into bytes.</strong> Keep those two ideas separate; conflating them is the #1 source of confusion.</p><p><strong>3. UTF-8: the clever variable-length scheme</strong></p><p>UTF-8 uses <strong>1 to 4 bytes</strong>, and the code point’s value decides how many:</p><pre>U+0000 — U+007F → 1 byte (ASCII)<br><br>U+0080 — U+07FF → 2 bytes<br><br>U+0800 — U+FFFF → 3 bytes<br><br>U+10000 — U+10FFFF → 4 bytes</pre><blockquote><strong>The killer feature: ASCII compatibility</strong></blockquote><p>For the 128 ASCII characters, UTF-8 uses a <strong>single byte identical to the original ASCII byte</strong>. A pure-ASCII file is <em>byte-for-byte identical</em> whether you call it ASCII or UTF-8. Decades of existing text and every HTML tag were instantly valid UTF-8 — zero migration cost.</p><blockquote><strong>How the bytes know their role (the “train” model)</strong></blockquote><p>Here’s the elegant part. Each byte carries a label in its leading bits:</p><pre>🚂 ENGINE (start byte) 🚃 CAR (continuation)<br><br>0xxxxxxx → solo character (ASCII, 1 byte)<br><br>110xxxxx → engine: “my train is 2 bytes”<br><br>1110xxxx → engine: “my train is 3 bytes”<br><br>11110xxx → engine: “my train is 4 bytes”<br><br>10xxxxxx → car: “I follow the engine before me”</pre><p><strong>The rule:</strong> count the leading 1s in the first byte → that’s the length. Continuation bytes <em>always</em> start with 10.</p><p>Example — é (U+00E9) as 2 bytes:</p><pre>11000011 10101001<br>└┬┘      └┬┘<br><br>“110” = engine, “10” = car<br><br>2-byte train (part of the same character)<br><br>→ strip the label bits, concatenate the payload → U+00E9 → é</pre><p><strong><em>Deep dive — why this design is genius:</em></strong></p><p><em>— </em><strong><em>Self-synchronizing:</em></strong><em> land anywhere in a byte stream, and you can find the next character boundary by skipping bytes that start with </em><em>10. No need to read from the start.</em></p><p><em>— </em><strong><em>Error detection:</em></strong><em> a lone </em><em>10xxxxxx with no engine, or an engine missing its cars, signals corruption immediately.</em></p><p><em>— </em><strong><em>No wasted space</em></strong><em> for common (ASCII) content.</em></p><p><strong>4. UTF-16 and surrogate pairs</strong></p><p>UTF-16 uses <strong>2 bytes</strong> for everything in the BMP (U+0000–U+FFFF). But it can’t fit code points above U+FFFF in 2 bytes — so for those it uses <strong>4 bytes</strong> via a <strong>surrogate pair</strong>: two 2-byte units that are meaningless alone but combine into one big code point.</p><pre>😀 U+1F600 → [ D83D ]   [ DE00 ]<br>              high       low<br>              surrogate  surrogate<br>             └──── one character ─┘</pre><p>This is exactly why emoji “count as 2” in many languages (more on that in point 8).</p><p><strong>Deep dive:</strong> The range U+D800–U+DFFF is permanently reserved for surrogates and can <em>never</em> be a real character. That’s how a decoder knows a 2-byte unit is half of a pair versus a standalone BMP character.</p><p><strong>5. Endianness and the BOM</strong></p><p>When your unit is bigger than one byte (UTF-16’s 2-byte units), which byte goes first?</p><pre>U+0041 (&#39;A&#39;) in UTF-16:<br>Big-endian: 00 41 (most significant byte first)<br>Little-endian: 41 00 (least significant first)</pre><p>Different CPUs default to different orders. Read it the wrong way → garbage. So files can start with a <strong>Byte Order Mark (BOM) </strong>— the character U+FEFF — as a flag:</p><pre>FE FF → big-endian<br>FF FE → little-endian</pre><p><strong>Why UTF-8 doesn’t need a BOM</strong></p><p>This is a subtle point worth nailing:</p><p><strong>Endianness only matters when a single unit spans multiple reorderable bytes.</strong></p><p>UTF-8’s unit is <strong>one byte</strong>, and the byte s<em>equence</em> is fixed by the spec (engine, then cars, in a mandated order). There’s no “which end first” decision to make. A byte can’t be reversed — it’s the smallest piece.</p><p>So UTF-8 has <strong>no endianness</strong>. Some tools (notably on Windows) still prepend `EF BB BF` as a <em>*”this is UTF-8&quot;*</em> signal — but it’s not a byte-order mark in any real sense, and it can trip up parsers that don’t expect it.</p><pre>UTF-16: one 2-byte NUMBER → CPU picks [00][41] or [41][00] → ambiguity → BOM helps<br>UTF-8: a STREAM of bytes → order fixed by spec → no ambiguity</pre><p><strong>6. Graphemes: what humans call “a character”</strong></p><p>Here’s where “character” gets slippery. A <strong>grapheme</strong> (or grapheme cluster) is <strong>one thing a human perceives on screen</strong> — but it can be built from <em>*multiple*</em> code points.</p><pre>bytes ⊂ code points ⊂ graphemes (what humans see)</pre><p><strong>Example 1 — two ways to write `é`:</strong></p><pre>Precomposed: U+00E9 → 1 code point<br>Decomposed: U+0065 + U+0301 → 2 code points (&quot;e&quot; + combining accent)</pre><p>Both render identically: `é`. One grapheme, but different code point counts.</p><p><strong>Example 2 — emoji with skin tone:</strong></p><pre>👍 = U+1F44D<br>👍🏽 = U+1F44D + U+1F3FD (thumbs up + skin tone modifier)</pre><p><strong>Example 3 — family emoji glued by ZWJ:</strong></p><pre>👨‍👩‍👧‍👦 = 👨 + ZWJ + 👩 + ZWJ + 👧 + ZWJ + 👦 = 7 code points, 1 grapheme</pre><p>That invisible glue (`U+200D`, the <strong>Zero Width Joiner</strong>) fuses adjacent code points into a single rendered glyph.</p><p><strong>7. Normalization: making “equal” actually equal</strong></p><p>Since `é` has two byte representations, a naive comparison says they’re <strong>different </strong>— breaking search, deduplication, and login checks.</p><p><strong>Normalization</strong> converts text into one canonical form so look-alike text has identical bytes. Unicode defines four forms:</p><pre>NFC → compose (e + ´ → é) ← most common; use for storage &amp; the web<br>NFD → decompose (é → e + ´)<br>NFKC → compose + fold compatibility look-alikes (ﬁ → fi, ② → 2)<br>NFKD → decompose + fold compatibility</pre><p><strong>Rule of thumb:</strong> normalize (usually to <strong>NFC</strong>) before you compare, search, index, or store user-provided text.</p><p><strong>Deep dive: </strong>The “K” forms are <strong>lossy</strong> — they collapse formatting distinctions (ligatures, superscripts, full-width characters). Great for search relevance, dangerous if you need to preserve the original exactly.</p><p><strong>8. Why <em>String.length</em> lies</strong></p><p>Ask “how long is this string?” and the answer depends on the layer you count:</p><pre>&quot;a&quot;.length // 1 ✓<br>&quot;👍&quot;.length // 2 ✗ one emoji, but a surrogate pair (2 UTF-16 units)<br>&quot;👍🏽&quot;.length // 4 ✗ thumbs-up + skin tone, two surrogate pairs<br>&quot;👨‍👩‍👧‍👦&quot;.length // 11 ✗ multiple emoji + ZWJ glue</pre><p>JavaScript’s <em>.length</em> counts <strong>UTF-16 code units </strong>— not code points, and definitely not graphemes. Three layers we’ve covered collide here:</p><p>1. <strong>Surrogate pairs</strong>→ supplementary characters count as 2.</p><p>2. <strong>Combining marks / normalization</strong> → `e + ´` counts as 2.</p><p>3. <strong>Grapheme clusters</strong> → ZWJ + modifiers pack many code points into one glyph.</p><p><strong>Real bugs this causes: </strong>“max 100 characters” limits that reject short-but-emoji-rich text; truncation that slices a surrogate pair in half and prints `�`; backspace deleting only part of an emoji.</p><p><strong>The fix — count the layer you actually mean:</strong></p><pre>Array.from(str).length // code points (handles surrogates)<br>const seg = new Intl.Segmenter(&#39;en&#39;, { granularity: &#39;grapheme&#39; });<br>[…seg.segment(str)].length // graphemes (what humans see)</pre><p><strong>9. The replacement character `�`</strong></p><p>Ever seen `�`? That’s `U+FFFD`, the <strong>replacement character</strong>. A decoder inserts it at read time when it hits bytes it <em>can’t</em> interpret:</p><p>- <strong>Wrong encoding assumed</strong> — e.g., Windows-1252 bytes read as UTF-8.</p><p>- <strong>Corrupted/truncated data</strong> — an engine byte promising 3 bytes but the cars are missing.</p><p>- <strong>Invalid byte sequences</strong> — a lone continuation byte with no engine.</p><p>Valid: 11100010 10000010 10101100 → € (decodes fine)</p><p>Broken: 11100010 01000001 → 2nd byte isn’t “10…” → decoder gives up → �</p><p><strong>Key insight: </strong>`�` is never in the original data — it’s the decoder saying “encoding mismatch or corruption.” The fix is almost always <strong>declaring your encoding explicitly</strong> (HTTP <em>charset=utf-8</em>, correct file handling) so readers don’t guess wrong.</p><p><strong>10. Homograph attacks: when look-alikes bite</strong></p><p>Unicode contains <strong>confusables</strong> — characters from different scripts that look identical:</p><pre>Latin &quot;a&quot; = U+0061<br>Cyrillic &quot;а&quot; = U+0430 ← visually identical, different code point</pre><p><strong>The attack:</strong> register a domain like аpple.com (Cyrillic а). It <em>reads</em> as “<a href="http://apple.com/">apple.com</a>” but is a completely different domain the attacker controls → phishing. This is the <strong>IDN homograph attack</strong> (IDN = Internationalized Domain Name, the system allowing non-ASCII domains).</p><p><strong>Also dangerous in:</strong> usernames (impersonating admin with a Cyrillic а), email addresses, and even <strong>source code</strong>(the “Trojan Source” attack uses invisible bidirectional control characters to make code <em>read</em> differently than it <em>runs</em>).</p><p><strong>Defenses:</strong></p><ul><li>Browsers display <strong>punycode</strong> (see point 11) for suspicious mixed-script domains.</li><li>Restrict identifiers to a single script; run confusable detection.</li><li>Registrars block mixing scripts within one label.</li></ul><p><strong><em>Deep dive:</em></strong><em> whenever text represents an </em><strong><em>identity</em></strong><em> (domain, username, email, API key label), “looks the same” ≠ “is the same.” Normalize </em>and<em> validate script/confusables before trusting it.</em></p><p><strong>11. Punycode: fitting Unicode into DNS</strong></p><p>DNS only understands ASCII (a-z, 0–9, -). But people want domains like münchen.de or 日本.jp. <strong>Punycode</strong>is a reversible transform from Unicode into an ASCII-safe string DNS can handle:</p><pre>münchen → xn — mnchen-3ya<br>café → xn - caf-dma</pre><p>The xn — prefix means “decode me as punycode.”</p><pre>You type: münchen.de<br>Browser encodes: xn - mnchen-3ya.de → goes to DNS<br>Browser displays: münchen.de → decoded for you</pre><p>It’s purely an <strong>encoding</strong>, not a security feature — but browsers <em>weaponize it defensively</em> by showing the raw xn — …form when a domain looks like a homograph, exposing the trick.</p><p><strong>12. Why UTF-8 won the web (~98% of sites)</strong></p><p>Everything above explains the outcome:</p><ol><li><strong>ASCII backward compatibility</strong> — the entire legacy web was already valid UTF-8. Free migration.</li><li><strong>Space efficiency</strong> — HTML markup, URLs, and English are 1 byte/char (UTF-16 wastes 2).</li><li><strong>No endianness, no BOM headaches</strong> — fixed byte stream, portable everywhere.</li><li><strong>Self-synchronizing &amp; robust</strong> — recover cleanly from corruption.</li><li><strong>Universal</strong> — represents all 1.1M code points; one encoding for every language and emoji.</li><li><strong>”Just works”</strong> — ASCII-era programs often handle UTF-8 unmodified.</li></ol><p>Compatible with the past, compact for typical content, portable, resilient, universal. That combination is why standards bodies now effectively mandate it.</p><p><strong>Summary</strong></p><ul><li><strong>Unicode</strong> = numbers for characters. <strong>UTF-8/16/32</strong> = bytes for those numbers. Never conflate them.</li><li><strong>UTF-8</strong>: variable 1–4 bytes, ASCII-compatible, self-synchronizing, no endianness. The web’s default.</li><li><strong>UTF-16</strong>: 2 or 4 bytes; supplementary characters need <strong>surrogate pairs</strong>. Why emoji “count as 2.”</li><li><strong>BOM/endianness</strong>: only matters for multi-byte units (UTF-16/32). UTF-8 is orderless.</li><li><strong>Grapheme ≠ code point ≠ byte.</strong> String.length counts code <em>units</em> — normalize and segment when humans care.</li><li><strong>Normalization (NFC)</strong> before comparing/storing user text.</li><li><strong>Confusables → homograph attacks</strong>; <strong>punycode</strong> encodes Unicode for DNS and doubles as a defense display.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dab52407d496" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to Switch statements & Switch expressions (Java 21)]]></title>
            <link>https://medium.com/@sparsh_aggarwal/guide-to-switch-statements-switch-expressions-java-21-3276891ecbc4?source=rss-fc809be53545------2</link>
            <guid isPermaLink="false">https://medium.com/p/3276891ecbc4</guid>
            <category><![CDATA[java21]]></category>
            <category><![CDATA[switch]]></category>
            <category><![CDATA[switch-statement]]></category>
            <category><![CDATA[switch-expression]]></category>
            <dc:creator><![CDATA[Sparsh Agarwal]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 15:17:52 GMT</pubDate>
            <atom:updated>2025-03-18T15:17:52.374Z</atom:updated>
            <content:encoded><![CDATA[<p>Just like we use an if/else block, switch is again a decision making tool to evaluate a value and redirect the flow to one or more code blocks. The reason why i say one or more code blocks, will become clear in a while. Knowingly or unknowingly we have always worked with Switch statements until Java 11, switch expressions were introduced in Java 12 and after that enhancements were done in later versions.</p><h4>Switch Statements</h4><p>Below code shows the structure of a switch statement, which decides which branch will be executed based on the variable and case constants. Mentioning break is important here otherwise, after the constant value matches, code will be executed for all the branches after it.</p><pre>switch (variableToTest){<br>  case expression1:<br>        break;<br>  case expression2, expression3:<br>        break;<br>  default: //Optional default <br>        System.out.println(&quot;Default Executed&quot;);<br>}</pre><p>Instead of colons, using an arrow would have meant the same thing. The below still remains a valid switch statement. Either use colons or arrow operator but not a mix of them, otherwise the compiler will complain saying “Different case kinds used in the switch”.</p><pre>switch (variableToTest){<br>  case expression1 -&gt; {<br>        System.out.println(&quot;Hello&quot;);<br>        break; }<br>  case expression2, expression3 -&gt; {<br>        System.out.println(&quot;Hello&quot;);<br>        break; }<br>  default-&gt;{ // Will not compile<br>        System.out.println(&quot;Default Executed&quot;);}<br>}</pre><h4>Switch Expressions</h4><p>Below code shows the structure of a switch expression, which returns a String value in this example. Break is not needed with expressions because it matches a single code branch at runtime.</p><pre>public String testSwitchExpression(){<br>String hello = switch (variableToTest){<br>  case expression1 -&gt; &quot;Hello&quot;; // expression must be a compile time constant<br>  case expression2 -&gt; {<br>                        yield &quot;World&quot;;<br>                      }<br>  default --&gt; &quot;Hello World&quot;; // Required if all possible values are not handled<br>};<br>return hello;<br>}</pre><blockquote>Except boolean ,long, float and double all the types, be it primitives or corresponding wrapper classes or Enums or object types (with pattern matching) are supported by Switch.</blockquote><p>The difference between switch statements and expressions lies in the fact, how expressions and statements are defined. An expression will evaluate to a value and that’s the difference i.e., switch expression must return a value while switch statement does not. This is not just one difference but yes a conceptual one, the syntax for both of them is also different.</p><p>I have knowingly used two different syntax in the example for switch expression i.e., for case expression 1 , it uses case expression while in the second case it uses a case block. It introduces the “yield” keyword here which is telling the case block to return “World” in this scenario. Using return would have given the control flow back to the original method from where this method was called. Only exception to this behaviour of returning a value is, when an exception is thrown then you do not need to return the value.</p><p>Again in the above example of switch expression, we said default is required if all possible values are not handled. Remember, switch expression needs to return a value, think of what will happen if default is not there and case expression 1 and 2 both are not matched. This results in unambiguous behaviour so Java says, switch expression has to be exhaustive. Switch statements on the other hand, need to be exhaustive only in 1 scenario when Pattern matching is used.</p><p>By exhaustive, it means is it should cover all possible values. There are a couple of ways to make a switch exhaustive.</p><p>a. Add a default clause (just like we did in above example)<br>b. Mention all enum values if enum is used. (Think of a scenario, if another developer introduces a new enum value)<br>c. All possible types of switch variable should be covered if pattern matching is used. Let’s look at Pattern Matching with switch, this was introduced in Java 21.</p><p><strong><em>Pattern Matching with switch expressions or statements</em></strong></p><pre>public void patternMatchingWIthSwitch(){<br>  Shape shape = new Square();<br>  String hello = switch(shape){<br>      case Square s -&gt; &quot;I am square&quot;; // s is the pattern matching variable<br>      case Rectangle r -&gt; &quot;I am rectangle&quot;;<br>      case Shape sh -&gt; &quot;I am just a shape&quot;; <br>  };<br>  System.out.println(hello); // Prints &quot;I am square&quot;<br>}</pre><p>This is an example of pattern matching with switch expressions. In the last case, the type matches the reference type of the switch variable hence it is exhaustive and the default clause is not needed. Pattern matching can also be used with switch statements but it will not return a value.</p><p>With Pattern matching, be it switch statement or expression the order of the case clause will matter. If in the above example, I move the case clause with Shape reference type to the first position, the code will not compile, simply because the other two statements become redundant. The compiler will complain saying “the case label is dominated by a preceding case label”.</p><pre>public void patternMatchingWIthSwitch(Shape shape){<br>  String hello = switch(shape){<br>      case Shape sh -&gt; &quot;I am just a shape&quot;;<br>      case Square s -&gt; &quot;I am square&quot;; // s is the pattern matching variable<br>      case Rectangle r -&gt; &quot;I am rectangle&quot;;<br>  };<br>}</pre><p>With Pattern matching we have been talking about object types and with objects discussion is never over until and unless we discuss a case with null.</p><pre>public void patternMatchingWIthSwitch(){<br>Shape shape = null;<br>  String hello = switch(shape){<br>      case Square s -&gt; &quot;I am square&quot;; // s is the pattern matching variable<br>      case Rectangle r -&gt; &quot;I am rectangle&quot;;<br>      case Shape sh -&gt; &quot;I am just a shape&quot;;<br>  };<br>}</pre><p>Although all the possible cases are handled, this will give a NullPointerException. With Java 21, switch actually supports case expression being null. Let’s make this work.</p><pre>public void patternMatchingWIthSwitch(){<br>Shape shape = null;<br>  String hello = switch(shape){<br>      case Shape sh -&gt; &quot;I am just a shape&quot;;<br>      case Square s -&gt; &quot;I am square&quot;; // s is the pattern matching variable<br>      case null -&gt; &quot;I am null&quot;;<br>      case Rectangle r -&gt; &quot;I am rectangle&quot;;<br>  };<br>  System.out.println(hello); // Prints &quot;I am null&quot;<br>}</pre><p>That’s all about Switch statements and expressions. Please leave any question in comments, so that i can come back to it.</p><p>Happy Learning!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3276891ecbc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about Date and Time in Java 21]]></title>
            <link>https://medium.com/@sparsh_aggarwal/all-about-date-and-time-in-java-21-e56721868b6b?source=rss-fc809be53545------2</link>
            <guid isPermaLink="false">https://medium.com/p/e56721868b6b</guid>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[instant]]></category>
            <category><![CDATA[periodandduration]]></category>
            <category><![CDATA[localdatetime]]></category>
            <category><![CDATA[java21]]></category>
            <dc:creator><![CDATA[Sparsh Agarwal]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 16:01:48 GMT</pubDate>
            <atom:updated>2025-03-16T16:15:27.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bdSEZ42InhUVdfHW" /><figcaption>Photo by <a href="https://unsplash.com/@karlp?utm_source=medium&amp;utm_medium=referral">Karl Pawlowicz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Date and Time manipulation has not been that easy, let’s see how it works now with newer versions of Java. While working with Java, in order to use a feature, the first question that pops up, is do I need a specific package to be imported otherwise the compiler will complain. To work with modern date and time classes, you will need to add the below import.</p><pre>import java.time.*; // import time classes</pre><h3>Creating and Manipulating dates and times</h3><p>When working with dates, the first thing that we need to ask is how much information is required. Do we need just the date or just the time or both or date, time and zone as well. Let’s break this into two parts, first let’s see how do we create date and time instances and then we will see how to manipulate them.</p><p>LocalDate — Contains just a date, no time or time zone information.<br>LocalTime — Contains just time, no date or time zone information.<br>LocalDateTime — Contain date as well as time but not the zone information.<br>ZonedDateTime — Contains everything i.e., date, time and zone information.</p><p>All of the four classes mentioned above, have a static method called now(), which gives the required information. Obviously the output of the method will depend where this is run from (time zone).</p><pre>System.out.println(LocalDate.now());<br>System.out.println(LocalTime.now());<br>System.out.println(LocalDateTime.now());<br>System.out.println(ZonedDateTime.now());</pre><p>If you want to create custom object with date or time information, the below statements will create it. The date and time classes have private constructors and use factory pattern i.e., static methods returning instances. We can also combine the date and time time info using a LocalDateTime object.</p><pre>var date1 = LocalDate.of(2025, Month.MARCH, 16);<br>var date2 = LocalDate.of(2025, 3, 16);<br>var time1 = LocalTime.of(9,0); //hour and minute<br>var time2 = LocalTime.of(9,8,7); //hour, minute and seconds<br>var dateTime1 = LocalDateTime.of(2025, Month.MARCH, 16, 9, 0, 5);<br>var date3 = new LocalDate(); // COMPILATION ERROR</pre><p>Now, let’s manipulate these instances. These classes are immutable i.e., return a new instance everytime instead of changing the existing instance and hence after manipulation the result will need to be stored otherwise would be lost, just like it happens with String class.</p><pre>var date1 = LocalDate.of(2025, Month.MARCH, 16);<br>System.out.println(date1); // Prints 2025-03-16<br>date1 = date1.plusDays(3);<br>System.out.println(date1); // Prints 2025-03-19<br>date1 = date1.plusWeeks(1);<br>System.out.println(date1); // Prints 2025-03-26<br>var dateTime1 = LocalDateTime.of(2025, Month.MARCH, 16, 9, 10); <br>System.out.println(dateTime1); //Prints 2025-03-16T9:10<br>dateTime1 = dateTime1.minusHours(2);<br>System.out.println(dateTime1); // Prints 2025-03-16T7:10</pre><p>Simple trick to remember is, you can add/subtract days, weeks, months or years to LocalDate but not time i.e., you cannot add hours, minutes, seconds to it and vice-versa. You can call both kinds on methods on LocalDateTime or ZonedDateTime, obviously because they both have date and time.</p><p><strong><em>Curious Question </em>— <em>Can I convert LocalDate instance to LocalDateTime instance or LocalTime instance to LocalDateTime ?</em><br></strong>Answer is yes, we can add time information to LocalDate instance or date information to a LocalTime instance through methods provided in the classes.</p><pre>var date1 = LocalDate.of(2025, Month.MARCH, 16);<br>var dateWithTime = date1.atTime(9, 25);<br>System.out.println(dateWithTime); // Prints 2025-03-16T9:25</pre><p>So far so good, do you see a problem in a scenario when we add/subtract time/days to particular instances ? Problem is we cannot make generic methods. Let’s look at the below code and you will understand the problem.</p><pre>public static void main(String[] args){<br>  var date1 = LocalDate.of(2025, Month.MARCH, 16);<br>  printAfterSomeDays(date1,1);  //Prints 2025-03-17<br>  printAfterSomeDays(date1,-2); //Prints 2205-03-14<br>}<br>private static void printAfterSomeDays(LocalDate date, Integer timeInt){<br>  //some processing<br>  date = date.plusDays(timeInt);<br>  System.out.println(date);<br>}</pre><p>Reusability becomes a problem for this private method when we have to add/subtract weeks or months instead of days. We are talking about weeks or months because we are talking about LocalDate and not LocalTime but same problem will come up with seconds or minutes in case of LocalTime.</p><p><strong><em>Solution</em></strong> is to use <strong>Period class </strong>(in case of date) and <strong>Duration class</strong>(in case of time).</p><pre>var date1 = LocalDate.of(2025, Month.MARCH, 16);<br>var daysPeriod = Period.ofDays(1);             // 1 day forward<br>var weeksPeriod = Period.ofWeeks(-2);          // 2 weeks backwards<br>var hoursDuration = Duration.ofHours(2);       // 2 hours forward<br>var minutesDuration = Duration.ofMinutes(-30); // 30 minutes backwards<br>System.out.println(date1.plus(daysPeriod));    // Prints 2025-03-17T09:25<br>System.out.println(date1.plus(weeksPeriod));   // Prints 2025-03-02T09:25<br>System.out.println(date1.plus(hoursDuration)); // Prints 2025-03-16T11:25<br>System.out.println(date1.plus(minutesDuration));//Prints 2025-03-16T08:55</pre><p><strong><em>Period vs Duration</em></strong></p><p>We can mention 48 hrs in Duration to make it two days but then that is what Period class is for. When we are working with<em> a </em>LocalDate instance we need to use LocalDate. Duration has time units in it, even if it is not obvious and they are meant only for time instances. Look at the below code to understand the difference.</p><pre>var date1 = LocalDate.of(2025, Month.MARCH, 16);<br>var period = Peiod.ofDays(1);<br>var duration = Duration.ofDays(1);<br>System.out.println(date1.plus(period));   // Prints 2025-03-17<br>System.out.println(date1.plus(duration)); // Throws Runtime Exception <br>                                          // (Unsupported Unit: Seconds)</pre><p><strong><em>Instants</em></strong></p><blockquote>As per the Java docs, this class models a single instantaneous point on the time-line. This might be used to record event time-stamps in the application.</blockquote><pre>var now = Instant.now();<br>System.out.println(now); //Prints 2025-03-16T15:45:40.237166500Z</pre><p>In fact a ZonedDateTime can be converted to an Instant but LocalDateTime cannot because Instant is a point in time. For ZonedDateTime, the Instant removes the time zone and converts it into an Instant in GMT. Understand it this way, LocalDateTime will not have the zone information and hence Instant which is in GMT cannot be calculated.</p><p>Happy Learning!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e56721868b6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>