<?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 Maheshkumar Srinivasan on Medium]]></title>
        <description><![CDATA[Stories by Maheshkumar Srinivasan on Medium]]></description>
        <link>https://medium.com/@maheshmaahi151098?source=rss-3019a213a021------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sJGDlF_TLfzac8FQVyAGhA.jpeg</url>
            <title>Stories by Maheshkumar Srinivasan on Medium</title>
            <link>https://medium.com/@maheshmaahi151098?source=rss-3019a213a021------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 21:37:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maheshmaahi151098/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[ Day 2: Sort a HashMap by Keys and Values in Java]]></title>
            <link>https://medium.com/@maheshmaahi151098/day-2-sort-a-hashmap-by-keys-and-values-in-java-9500ed5eca7d?source=rss-3019a213a021------2</link>
            <guid isPermaLink="false">https://medium.com/p/9500ed5eca7d</guid>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[hashmap-in-java]]></category>
            <dc:creator><![CDATA[Maheshkumar Srinivasan]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 10:50:37 GMT</pubDate>
            <atom:updated>2025-06-17T10:50:37.439Z</atom:updated>
            <content:encoded><![CDATA[<h4>Program 1: Sort HashMap by Keys (Ascending)</h4><pre>package interview_question;<br><br>import java.util.HashMap;<br>import java.util.Map;<br>import java.util.TreeMap;<br><br>public class SortHashmapByKey {<br>    public static void main(String[] args) {<br>        Map&lt;Integer,String&gt; map=new HashMap&lt;&gt;();<br>        map.put(101,&quot;Ravanan&quot;);<br>        map.put(102,&quot;Mani&quot;);<br>        map.put(105,&quot;mahesh&quot;);<br>        map.put(106,&quot;Dhil&quot;);<br>        Map&lt;Integer, String &gt; sorted=new TreeMap&lt;&gt;(map);<br><br>        for (Map.Entry&lt;Integer,String&gt; entries: sorted.entrySet()){<br>            System.out.println(&quot;Id= &quot;+entries.getKey()+&quot; Name= &quot;+entries.getValue());<br>        }<br>    }<br>}<br>//Output:<br>//Id= 101 Name= Ravanan<br>//Id= 102 Name= Mani<br>//Id= 105 Name= mahesh<br>//Id= 106 Name= Dhil</pre><h4>Program 2: Sort HashMap by Values (Ascending)</h4><pre>package interview_question;<br><br>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.List;<br>import java.util.Map;<br><br>public class SortHashmapByValue {<br>    public static void main(String[] args) {<br>        Map&lt;Integer,String&gt; map=new HashMap&lt;&gt;();<br>        //Intialize the values<br>        map.put(101,&quot;Ravanan&quot;);<br>        map.put(102,&quot;Mani&quot;);<br>        map.put(105,&quot;Mahesh&quot;);<br>        map.put(106,&quot;Dhil&quot;);<br>        //create a List for sorting<br>        List&lt;Map.Entry&lt;Integer,String&gt;&gt; entries=new ArrayList&lt;&gt;(map.entrySet());<br>        entries.sort(Map.Entry.comparingByValue());//Sorting the list values<br>        Map&lt;Integer,String&gt; result=new HashMap&lt;&gt;();<br>        //Printing the data<br>        for (Map.Entry&lt;Integer,String&gt; entry:entries){<br>            System.out.println(&quot;Id= &quot;+entry.getKey()+&quot; Name= &quot;+entry.getValue());<br>        }<br>    }<br>}</pre><p>Return as linkedlist So we added some lines to converting into Map.</p><pre>package interview_question;<br><br>import java.util.ArrayList;<br>import java.util.HashMap;<br>import java.util.List;<br>import java.util.Map;<br><br>public class SortHashmapByValue {<br>    public static void main(String[] args) {<br>        Map&lt;Integer,String&gt; map=new HashMap&lt;&gt;();<br>        //Intialize the values<br>        map.put(101,&quot;Ravanan&quot;);<br>        map.put(102,&quot;Mani&quot;);<br>        map.put(105,&quot;Mahesh&quot;);<br>        map.put(106,&quot;Dhil&quot;);<br>        //create a List for sorting<br>        List&lt;Map.Entry&lt;Integer,String&gt;&gt; entries=new ArrayList&lt;&gt;(map.entrySet());<br>        entries.sort(Map.Entry.comparingByValue());//Sorting the list values<br>        Map&lt;Integer,String&gt; result=new HashMap&lt;&gt;();<br>        //Load into result(map)<br>        for (Map.Entry&lt;Integer,String&gt; entry:entries){<br>            result.put(entry.getKey(),entry.getValue());<br>        }<br>        //Printing the value<br>        for (Map.Entry&lt;Integer,String&gt; entries1: result.entrySet()){<br>            System.out.println(&quot;Id= &quot;+entries1.getKey()+&quot; Name= &quot;+entries1.getValue());<br>        }<br>    }<br>}</pre><h4>Explanation:</h4><p>TreeMap automatically sorts by <strong>keys</strong> in natural order.</p><p>To sort by <strong>values</strong>, you:</p><ul><li>Convert HashMap to a List of entries</li><li>Use Collections.sort() or List.sort() with Map.Entry.comparingByValue()</li><li>Optionally, put the sorted entries into a LinkedHashMap to preserve order.</li></ul><h3>✅ Why We Use Map.Entry in Java</h3><h4>🔹 1. What is Map.Entry?</h4><p>Map.Entry is a <strong>nested interface</strong> inside the Map interface.<br> It represents <strong>one key-value pair</strong> (entry) in a map.</p><h4>🔹 2. Why We Use It?</h4><p>Because a Map doesn’t directly store elements like a List or Set.<br> You need to access each key-value <strong>pair</strong> using entrySet() and Map.Entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*0E7JcQfXqQMO15gTqQpbXw.png" /></figure><p>If any Queries, Mistake Leave the comments Thats Useful to correct Me.</p><p><strong>Thanks!!</strong></p><p>Happy Reading!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9500ed5eca7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Day 1: Remove Duplicates from a List (Case-Insensitive)]]></title>
            <link>https://medium.com/@maheshmaahi151098/day-1-remove-duplicates-from-a-list-case-insensitive-7d997b4d33ef?source=rss-3019a213a021------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d997b4d33ef</guid>
            <category><![CDATA[remove-duplicates]]></category>
            <dc:creator><![CDATA[Maheshkumar Srinivasan]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 12:29:28 GMT</pubDate>
            <atom:updated>2025-06-16T12:29:28.879Z</atom:updated>
            <content:encoded><![CDATA[<h4>1.Simple program for removing duplicate</h4><pre>import java.util.*;<br>import java.util.stream.Collectors;<br><br>//Remove duplicates from a list<br>public class RemoveDuplicatesFromList {<br>    public static void main(String[] args) {<br>        //Simple remove duplicate values<br>        List&lt;String&gt; list1= Arrays.asList(&quot;Mahesh&quot;,&quot;Anbu&quot;,&quot;babu&quot;,&quot;anbu&quot;,&quot;a&quot;);<br>        //Converting into Set automatically removes the dupliacte values<br>        // using hash set for maintain inserton order.<br>        Set&lt;String&gt; unique1 = new LinkedHashSet&lt;&gt;(list1);<br>        System.out.println(unique1);<br>        //output: [Mahesh, Anbu, babu, anbu, a]<br>   }<br>}</pre><p>Its is the simple program for removing duplicate value like sting, char, intergers and its drawback is If two values have same name with different case its doesn’t remove.</p><h4>2.Remove duplicate values using converting all into lowercase using streams</h4><pre>import java.util.*;<br>import java.util.stream.Collectors;<br><br>//Remove duplicates from a list<br>public class RemoveDuplicatesFromList {<br>    public static void main(String[] args) { <br>        List&lt;String&gt; list2= Arrays.asList(&quot;Mahesh&quot;,&quot;Anbu&quot;,&quot;babu&quot;,&quot;anbu&quot;,&quot;a&quot;);<br>        List&lt;String&gt; Unames= list2.stream()<br>                                  .map(String::toLowerCase)<br>                                  .collect(Collectors.toList());<br>        Set&lt;String&gt; unique2 = new LinkedHashSet&lt;&gt;(Unames);<br>        System.out.println(unique2);<br>        //output: [mahesh, anbu, babu, a]<br>     }<br>}</pre><p>Its Removes the duplicates but converted the Uppercase into smaller case.</p><h4>3.Remove Duplicates from a List (Case-Insensitive).</h4><pre>import java.util.*;<br>import java.util.stream.Collectors;<br><br>//Remove duplicates from a list<br>public class RemoveDuplicatesFromList {<br> List&lt;String&gt; list3= Arrays.asList(&quot;Mahesh&quot;,&quot;Anbu&quot;,&quot;babu&quot;,&quot;anbu&quot;,&quot;a&quot;);<br>        Set&lt;String&gt; set=new HashSet&lt;&gt;(); // creating for removing duplicate<br>        List&lt;String&gt; uniqueNames=new ArrayList&lt;&gt;();// creating for save unique<br><br>        for(String name:list3){<br>            String lower=name.toLowerCase(); //convert values into lowercase<br>            if(!set.contains(lower)){  // check the value is in set<br>                set.add(lower);      //save the value for removing duplicated<br>                uniqueNames.add(name); // add the Unique name in the new list<br>            }<br>        }<br>        System.out.println(uniqueNames);<br>        //output: [Mahesh, Anbu, babu, a]<br>    }<br>}</pre><p>Here’s a <strong>simple explanation</strong> of the program that removes <strong>case-insensitive duplicates</strong> from a List&lt;String&gt; while <strong>keeping the first occurrence</strong> and <strong>original casing</strong>.</p><p>If any Queries, Mistake Leave the comments Thats Useful to correct Me.</p><p><strong>Thanks!!</strong></p><p>Happy Reading!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBOuMJcYwmUdjwwjjMIS3w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d997b4d33ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparable vs Comparator]]></title>
            <link>https://medium.com/@maheshmaahi151098/comparable-vs-comparator-ce914b550052?source=rss-3019a213a021------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce914b550052</guid>
            <category><![CDATA[comparable]]></category>
            <category><![CDATA[comparator]]></category>
            <category><![CDATA[comparable-vs-comparator]]></category>
            <dc:creator><![CDATA[Maheshkumar Srinivasan]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 10:48:56 GMT</pubDate>
            <atom:updated>2025-06-16T10:48:56.244Z</atom:updated>
            <content:encoded><![CDATA[<p>Both Comparable and Comparator are used to compare objects in Java — especially when you are sorting or ordering collections of objects like List&lt;Student&gt;.</p><p>If you are sorting:</p><ul><li>Just once in one way → use <strong>Comparable</strong></li><li>In multiple ways (by name, age, marks, etc.) → use <strong>Comparator</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/0*npy0o8s_kxI08JTy" /></figure><h3>Comparable</h3><p>(We explain how to Compare with other)</p><ul><li><strong>Interface</strong>: java.lang.Comparable&lt;T&gt;</li><li><strong>Method</strong>: compareTo(T o)</li><li><strong>Usage</strong>: Used <strong>within the class</strong> (the class itself defines how objects should be compared).</li><li><strong>Example Use Case</strong>: Sorting a list of students by name.</li></ul><pre>// Need to Implements the Comparable interface for Comparing<br>class Student implements Comparable&lt;Student&gt; {<br>    String name;<br>    int age;<br><br>    public int compareTo(Student other) {<br>        return this.name.compareTo(other.name); // name-wise sorting<br>    }<br>}</pre><p><strong>Note</strong>: Only <strong>one way</strong> of sorting per class (unless you change the class code).</p><h3>Comparator</h3><p>(Otherperson Explain How to compare with others)</p><ul><li><strong>Interface</strong>: java.util.Comparator&lt;T&gt;</li><li><strong>Method</strong>: compare(T o1, T o2)</li><li><strong>Usage</strong>: Used <strong>outside the class</strong> (can define multiple ways to compare).</li><li><strong>Example Use Case</strong>: Sorting students by age, marks, etc.</li></ul><pre>class Student {<br>    String name;<br>    int age;<br>}<br><br>// Age comparator<br>class AgeComparator implements Comparator&lt;Student&gt; {<br>    public int compare(Student s1, Student s2) {<br>        return s1.age - s2.age;<br>    }<br>}</pre><h3>In Simple Words:</h3><ul><li><strong>Comparable</strong> = Class says: “I know how to compare myself!”</li><li><strong>Comparator</strong> = Outsider says: “I’ll tell you how to compare these objects!”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13vrNc1d31NnUEhU4f5zFg.png" /></figure><p>If any Queries, Mistake Leave the comments Thats Useful to correct Me.</p><p><strong>Thanks!!</strong></p><p>Happy Reading!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce914b550052" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[equals() and hashCode()in Java — Simple Explanation]]></title>
            <link>https://medium.com/@maheshmaahi151098/equals-and-hashcode-in-java-simple-explanation-5f4a41e34e07?source=rss-3019a213a021------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f4a41e34e07</guid>
            <category><![CDATA[hashcode-java]]></category>
            <category><![CDATA[equals-method-java]]></category>
            <dc:creator><![CDATA[Maheshkumar Srinivasan]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 17:46:19 GMT</pubDate>
            <atom:updated>2025-06-12T17:46:19.698Z</atom:updated>
            <content:encoded><![CDATA[<h3>equals() and hashCode()in Java — Simple Explanation</h3><h3>equals() → <strong>Check if two objects have same values</strong></h3><p>equals() used to check the two object values are same or not.</p><ul><li>Used to compare two objects <strong>logically</strong>.</li><li>Example:</li></ul><pre>Student s1 = new Student(1, &quot;Ram&quot;);<br>Student s2 = new Student(1, &quot;Ram&quot;);<br><br>s1.equals(s2); // true – because id and name are same</pre><h3>hashCode()→ <strong>Used in collections like HashMap, HashSet</strong></h3><ul><li>Generates a <strong>number (int)</strong> for each object.</li><li>Collections use this number to <strong>quickly find or store objects</strong>.</li><li>If equals() is true, then hashCode() <strong>must be same</strong>.</li><li>Example:</li></ul><pre>HashSet&lt;Student&gt; set = new HashSet&lt;&gt;();<br>set.add(s1);<br>set.contains(s2); // Will work only if hashCode and equals are correctly overridden</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6WygVZq5B9PvG9Y3MsAXOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/0*xXtnAk_e96lMynGG" /></figure><p>If any Queries, Mistake Leave the comments Thats Useful to correct Me.</p><p><strong>Thanks For Reading</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f4a41e34e07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand Design Patterns: Singleton, Factory, Abstract factory and Saga]]></title>
            <link>https://medium.com/@maheshmaahi151098/understand-design-patterns-singleton-factory-abstract-factory-and-saga-728d05eeb884?source=rss-3019a213a021------2</link>
            <guid isPermaLink="false">https://medium.com/p/728d05eeb884</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <dc:creator><![CDATA[Maheshkumar Srinivasan]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 04:40:36 GMT</pubDate>
            <atom:updated>2025-06-12T04:40:36.992Z</atom:updated>
            <content:encoded><![CDATA[<p>Design patterns is a blueprint and its represents a best practices followed by the experienced senior developer,</p><p>Its used for solving the typical problems in software development</p><p>We go DesignPatterns for improves readability, resusability, improve scalability and easier to change.</p><p>Three Main Types of Design Patterns:</p><ol><li><strong>Creational Patterns</strong> — Deal with object creation</li><li><strong>Structural Patterns</strong> — Deal with object composition</li><li><strong>Behavioral Patterns</strong> — Deal with communication between objects</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/0*cmVbwp4WXLSdEWHp" /></figure><p>Lets see some of the <strong>design patterns</strong> in <strong>Creational</strong> with example,</p><h3>1. <strong>Singleton Pattern</strong></h3><p>Create only one instance for a class.</p><p>If we want the common things from the object then go to Single design pattern</p><p>If every obj has specific things, don’t go to SDP</p><blockquote><strong>Advantages:</strong></blockquote><blockquote>Saves memory, Performance improvement, use object in everytime.</blockquote><blockquote><strong>Rules:</strong></blockquote><blockquote>Create object as static</blockquote><blockquote>Create constructor as private</blockquote><blockquote>Create getInstance() method as static.</blockquote><pre>//Eager Creation<br>public class Mentorbridge{<br>    private static Mentorbridge instance = new Mentorbridge();<br>    private Mentorbridge() {}<br>    public static Mentorbridge getInstance() {<br>        return instance;<br>    }<br>}</pre><pre>//Lazy Creation is not thread safe<br>public class Mentorbridge {<br>    private static Mentorbridge instance;<br><br>    private Mentorbridge() {}<br><br>    public static Mentorbridge getInstance() {<br>        if (instance == null) {<br>            instance = new Mentorbridge();<br>        }<br>        return instance;<br>    }<br>}<br><br>// Usage<br>public class Main {<br>    public static void main(String[] args) {<br>        Singleton obj = Singleton.getInstance();<br>        obj.showMessage();<br>    }<br>}</pre><p>Lazy creation is not thread safe So, go to synchronized or Double-checked locking</p><p>Solution 1: Synchronized getInstance() (Simple but Slower)</p><pre>//Synchronized getInstance for avoid multiple access in resources at a time<br>public class Mentorbridge {<br>    private static Mentorbridge instance;<br><br>    private Mentorbridge() {}<br><br>    public static Mentorbridge getInstance() {<br>        if (instance == null) {<br>            instance = new Mentorbridge();<br>        }<br>        return instance;<br>    }<br>}<br><br>// Usage<br>public class Main {<br>    public static void main(String[] args) {<br>        Mentorbridge obj = Mentorbridge.getInstance();<br>        obj.showMessage();<br>    }<br>}</pre><p>Solution 2: Double-Checked Locking (Recommended)</p><pre>public class Mentorbridge {<br>    private static volatile Mentorbridge instance;<br><br>    private Mentorbridge() {}<br><br>    public static Mentorbridge getInstance() {<br>        if (instance == null) { // 1st check (no locking)<br>            synchronized (Mentorbridge.class) {<br>                if (instance == null) { // 2nd check (with lock)<br>                    instance = new Mentorbridge();<br>                }<br>            }<br>        }<br>        return instance;<br>    }<br>}<br><br>// Usage<br>public class Main {<br>    public static void main(String[] args) {<br>        Mentorbridge obj = Mentorbridge.getInstance();<br>        obj.showMessage();<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*I8rPrQjxJUolxElJIYvTXA.png" /></figure><h3>2.Factory Method</h3><p>The <strong>Factory Pattern</strong> is used to <strong>create objects</strong> without exposing the creation logic to the client.</p><blockquote>In Factory Method Pattern, the <strong>superclass defines a method</strong> to create an object,<br> but <strong>subclasses decide</strong> <strong>which object</strong> to create.</blockquote><blockquote>So, the object creation logic is <strong>abstracted in the parent class</strong>, and <strong>implemented in the child class</strong>.</blockquote><p>Step 1: Common interface</p><pre>interface Shape {<br>    void draw();<br>}</pre><p>Step 2: Create concrete classes (Different shapes)</p><pre>class Circle implements Shape {<br>    public void draw() {<br>        System.out.println(&quot;Drawing Circle&quot;);<br>    }<br>}<br><br>class Square implements Shape {<br>    public void draw() {<br>        System.out.println(&quot;Drawing Square&quot;);<br>    }<br>}</pre><p>Step 3: Factory to give shape</p><pre>class ShapeFactory {<br>    public Shape getShape(String type) {<br>        if (type.equalsIgnoreCase(&quot;circle&quot;)) {<br>            return new Circle();<br>        } else if (type.equalsIgnoreCase(&quot;square&quot;)) {<br>            return new Square();<br>        } else {<br>            return null;<br>        }<br>    }<br>}</pre><p>Step 4: Use the factory</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        ShapeFactory factory = new ShapeFactory();<br><br>        Shape s1 = factory.getShape(&quot;circle&quot;);<br>        s1.draw();  // Output: Drawing Circle<br><br>        Shape s2 = factory.getShape(&quot;square&quot;);<br>        s2.draw();  // Output: Drawing Square<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*FQ5dB7MwMt9oRaf40J-NIw.png" /></figure><p>Simple Explanation,</p><p>Factory Method one object create — but <strong>subclass decides</strong> which one.</p><ul><li>One product type (example: Food)</li><li>Subclass decides whether to give <strong>Pizza or Burger</strong></li><li>Factory method use to create <strong>only one type of object</strong></li></ul><h3>3.Abstract Factory Pattern</h3><p>Abstract Factory is a <strong>Factory of Factories,</strong><br> It creates <strong>related group of objects</strong> together.</p><blockquote><strong>Abstract Factory</strong> is a design pattern that helps you create a <strong>group of related objects</strong> without telling your code the exact class names.</blockquote><blockquote><em>In short:<br> ➡️ </em><strong><em>One factory</em></strong><em> gives you </em><strong><em>many related objects</em></strong><em>.</em></blockquote><p><strong>For e.g., let’s building a UI toolkit.</strong></p><p>You need:</p><p>A <strong>Button</strong></p><p>A <strong>Checkbox</strong></p><p>Now you have 2 styles:</p><p><strong>Windows style, Mac style</strong></p><p>You don’t want to write separate code every time. So, you use <strong>Abstract Factory</strong>.</p><p><strong>Step 1: Common Interfaces</strong></p><pre>interface Button {<br>    void paint();<br>}<br><br>interface Checkbox {<br>    void paint();<br>}</pre><p><strong>Step 2: Windows versions</strong></p><pre>class WindowsButton implements Button {<br>    public void paint() {<br>        System.out.println(&quot;Windows Button&quot;);<br>    }<br>}<br><br>class WindowsCheckbox implements Checkbox {<br>    public void paint() {<br>        System.out.println(&quot;Windows Checkbox&quot;);<br>    }<br>}</pre><p><strong>Step 3: Mac versions</strong></p><pre>class MacButton implements Button {<br>    public void paint() {<br>        System.out.println(&quot;Mac Button&quot;);<br>    }<br>}<br><br>class MacCheckbox implements Checkbox {<br>    public void paint() {<br>        System.out.println(&quot;Mac Checkbox&quot;);<br>    }<br>}</pre><p><strong>Step 4: Abstract Factory</strong></p><pre>interface GUIFactory {<br>    Button createButton();<br>    Checkbox createCheckbox();<br>}</pre><p><strong>Step 5: Concrete Factories</strong></p><pre>class WindowsFactory implements GUIFactory {<br>    public Button createButton() {<br>        return new WindowsButton();<br>    }<br>    public Checkbox createCheckbox() {<br>        return new WindowsCheckbox();<br>    }<br>}<br><br>class MacFactory implements GUIFactory {<br>    public Button createButton() {<br>        return new MacButton();<br>    }<br>    public Checkbox createCheckbox() {<br>        return new MacCheckbox();<br>    }<br>}</pre><p><strong>Step 6: Client Code</strong></p><pre>class Application {<br>    private Button button;<br>    private Checkbox checkbox;<br><br>    public Application(GUIFactory factory) {<br>        button = factory.createButton();<br>        checkbox = factory.createCheckbox();<br>    }<br><br>    public void paintUI() {<br>        button.paint();<br>        checkbox.paint();<br>    }<br>}</pre><p>Usage:</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        GUIFactory factory = new WindowsFactory();  // or MacFactory<br>        Application app = new Application(factory);<br>        app.paintUI();<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*JqX_zMroccG0REcnSaA98Q.png" /></figure><h3>4.Saga Design Pattern</h3><p><em>A </em><strong><em>Saga</em></strong><em> is a design pattern to </em><strong><em>manage transactions</em></strong><em> in </em><strong><em>microservices</em></strong><em>, especially when there’s no database transaction across services.</em></p><p>When one service does something, other services may also do something — if one fails, we must <strong>undo</strong> the previous steps.</p><h4>Scenario: Online Order System</h4><p>Steps:</p><ol><li>Create Order</li><li>Make Payment</li><li>Ship Product</li></ol><p>If any step fails, we undo the previous one.</p><h4>Services:</h4><ul><li>OrderService</li><li>PaymentService</li><li>ShippingService</li></ul><h4>Step-by-Step (Orchestration Style — Central Control)</h4><ol><li>The Saga Orchestrator</li></ol><pre>public class OrderSagaOrchestrator {<br><br>    public void startOrderSaga() {<br>        try {<br>            OrderService.createOrder();<br>            PaymentService.makePayment();<br>            ShippingService.shipOrder();<br>            System.out.println(&quot;Order completed successfully.&quot;);<br>        } catch (Exception e) {<br>            compensate();<br>        }<br>    }<br><br>    private void compensate() {<br>        System.out.println(&quot;Something failed! Starting compensation...&quot;);<br>        ShippingService.cancelShipping();  // if already shipped<br>        PaymentService.refundPayment();    // refund if paid<br>        OrderService.cancelOrder();        // cancel order<br>    }<br>}</pre><p>2. OrderService</p><pre>public class OrderService {<br>    static void createOrder() {<br>        System.out.println(&quot;Order created&quot;);<br>    }<br><br>    static void cancelOrder() {<br>        System.out.println(&quot;Order cancelled&quot;);<br>    }<br>}</pre><p>3. PaymentService</p><pre>public class PaymentService {<br>    static void makePayment() {<br>        System.out.println(&quot;Payment done&quot;);<br>        // throw new RuntimeException(&quot;Payment failed&quot;); // Uncomment to test failure<br>    }<br><br>    static void refundPayment() {<br>        System.out.println(&quot;Payment refunded&quot;);<br>    }<br>}</pre><p>4. ShippingService</p><pre>public class ShippingService {<br>    static void shipOrder() {<br>        System.out.println(&quot;Order shipped&quot;);<br>    }<br><br>    static void cancelShipping() {<br>        System.out.println(&quot;Shipping cancelled&quot;);<br>    }<br>}</pre><p>Running Main</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        OrderSagaOrchestrator saga = new OrderSagaOrchestrator();<br>        saga.startOrderSaga();<br>    }<br>}</pre><p>Output (Success):</p><pre>Order created  <br>Payment done  <br>Order shipped  <br>Order completed successfully.</pre><p>Output (If payment fails):</p><pre>Order created  <br>Something failed! Starting compensation...  <br>Shipping cancelled  <br>Payment refunded  <br>Order cancelled</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*GlBXzNK8H5IXc7SyEN1o_A.png" /></figure><p>This is Design Patterns when i use while working, Just comment in which one you used,</p><p>If any Queries, Mistake Leave the comments Thats Useful to correct Me.</p><p><strong>Thanks For Reading</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=728d05eeb884" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[== vs .equals() in Java – Know the Real Difference]]></title>
            <link>https://medium.com/@maheshmaahi151098/vs-equals-in-java-know-the-real-difference-1a3dff1bc179?source=rss-3019a213a021------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a3dff1bc179</guid>
            <category><![CDATA[equals-method-java]]></category>
            <dc:creator><![CDATA[Maheshkumar Srinivasan]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 08:50:59 GMT</pubDate>
            <atom:updated>2025-06-10T08:50:59.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>== vs .equals() in Java – Know the Real Difference</h3><p>When comparing objects in Java, We are all confusing between using == and .equals()</p><p>So lets see the difference between this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*s6EFz7XOWyxfgYYmGZyOaA.jpeg" /></figure><p>Let’s break it down in simple terms.</p><h4>What is == in Java?</h4><p>The == operator checks “whether two values are same or not” and “Checks whether the memory address of the object are same or not”.</p><p>If we compare two strings using ==, Java checks the <strong>memory address</strong>, not the content.<br>This is because String is <strong>not a primitive data type</strong>, it is a <strong>class</strong> (i.e., an object in Java).</p><pre>int a = 5;<br>int b = 5;<br>System.out.println(a == b); // true (same value)<br><br>String s1 = new String(&quot;Java&quot;);<br>String s2 = new String(&quot;Java&quot;);<br>System.out.println(s1 == s2); // false (different memory)<br><br>String s3 = &quot;Java&quot;;<br>String s4 = &quot;Java&quot;;<br>System.out.println(s3 == s4); // true (same string pool reference)</pre><h4>What is .equals() in Java?</h4><p>The .equals() method checks whether the contents (data/values) of two objects are the same.</p><p>.equals() returns true if the actual string values are equal, even if the objects are in different memory locations.</p><pre>String name1 = new String(&quot;Mahesh&quot;);<br>String name2 = new String(&quot;Mahesh&quot;);<br><br>System.out.println(name1 == name2);      // false<br>System.out.println(name1.equals(name2)); // true</pre><p>The String class in Java <strong>overrides</strong> the .equals() method from the Object class. That’s why it compares <strong>contents</strong> instead of memory.</p><pre>@Override<br>public boolean equals(Object anObject) {<br>    if (this == anObject) {<br>        return true;<br>    }<br>    if (anObject instanceof String) {<br>        String anotherString = (String) anObject;<br>        return this.value.equals(anotherString.value); // value is character array<br>    }<br>    return false;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a3dff1bc179" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Java Strings: String vs StringBuilder vs StringBuffer]]></title>
            <link>https://medium.com/@maheshmaahi151098/mastering-java-strings-string-vs-stringbuilder-vs-stringbuffer-2c659b61ff1d?source=rss-3019a213a021------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c659b61ff1d</guid>
            <category><![CDATA[string-vs-stringbuilder]]></category>
            <category><![CDATA[stringbuffer]]></category>
            <category><![CDATA[string]]></category>
            <dc:creator><![CDATA[Maheshkumar Srinivasan]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 08:14:58 GMT</pubDate>
            <atom:updated>2025-06-10T08:14:58.325Z</atom:updated>
            <content:encoded><![CDATA[<p>Till today, we knew that String is a <strong>non-primitive data type</strong> in Java. But technically, String is a <strong>class</strong> in Java used to store text data.</p><p>Java provides three main classes to handle strings:</p><ul><li><strong>java.lang.String</strong> – Immutable string class (once created, cannot be changed)</li><li><strong>java.lang.StringBuilder</strong> – Mutable string class (not thread-safe, faster)</li><li><strong>java.lang.StringBuffer</strong> – Mutable and thread-safe string class (synchronized)</li></ul><pre>String str = &quot;Hello&quot;; // Uses java.lang.String<br>StringBuilder sb = new StringBuilder(&quot;Hello&quot;); // Uses StringBuilder<br>StringBuffer sf = new StringBuffer(&quot;Hello&quot;);   // Uses StringBuffer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*BwazSqZ9fS20d1J1" /></figure><h4>String Class:</h4><ol><li>The String class belongs to the <strong>java.lang</strong> package.</li><li>Since java.lang is automatically imported by the JVM, <strong>you don’t need to explicitly import</strong> the String class.</li><li>String is a <strong>public(</strong>Accessible from any class) and <strong>final(</strong>Cannot be extended (inherited)).</li><li>The String class is used to <strong>store and manipulate sequences of characters (text)</strong>.</li><li>String class extends java.lang.Object.</li><li>String class implements Comparable, serialization, char sequence</li></ol><blockquote>Declaration of string class:</blockquote><blockquote>public final class String extends Object implements Serializable, Comparable&lt;String&gt;, CharSequence</blockquote><h3>Diff b/w String, StringBuilder and StringBuffer.</h3><h3>String:</h3><h4><strong>1. Immutable</strong></h4><ul><li>Once a String object is created, <strong>its value cannot be changed</strong>.</li></ul><pre>String str = &quot;Hello&quot;;<br>str.concat(&quot; World&quot;); // Returns new string, original is unchanged<br>System.out.println(str); // Output: Hello</pre><h4>2. <strong>Stored in String Constant Pool</strong></h4><ul><li>String literals are stored in a <strong>special memory area</strong> called the <strong>String Constant Pool</strong>.</li><li>Helps save memory by <strong>reusing</strong> identical string literals.</li></ul><h4>3.Performance: Relatively Slower</h4><ul><li>Because String is <strong>immutable</strong>, every change creates a <strong>new object</strong>.</li><li>For many modifications (like in loops), StringBuilder is preferred for <strong>better performance</strong>.</li></ul><h4>4.Public and Final</h4><p>String class is:</p><ul><li>public → accessible everywhere.</li><li>final → <strong>cannot be extended/inherited</strong>.</li></ul><pre>public final class String { ... }</pre><h3>StringBuilder:</h3><h4>1. Mutable</h4><p>Unlike String, StringBuilder objects <strong>can be changed</strong> after creation.</p><pre>StringBuilder sb = new StringBuilder(&quot;Hello&quot;);<br>sb.append(&quot; World&quot;);<br>System.out.println(sb); // Output: Hello World</pre><h4>2.Stored in Heap</h4><ul><li>Objects of StringBuilder are stored in the <strong>heap</strong>, not in the String Constant Pool.</li><li>Because they are mutable and created using new.</li></ul><h4>3.Perfomance Fast</h4><p>StringBuilder is <strong>faster</strong> than String and StringBuffer when used in <strong>single-threaded</strong> environments.</p><h4>4. <strong>Not Synchronized</strong></h4><p>It is not thread safe and all methods are not synchronized, B’coz multiple thread can access at a time.</p><h4>5.Not Safe for Multithreading</h4><p>Avoid in Multithreaded scenarios.</p><h3>StringBuffer</h3><h4>1. Mutable</h4><ul><li>Like StringBuilder, StringBuffer allows you to <strong>modify string content</strong> without creating new objects.</li></ul><pre>StringBuffer sb = new StringBuffer(&quot;Hello&quot;);<br>sb.append(&quot; World&quot;);<br>System.out.println(sb); // Output: Hello Worldjava<br></pre><h4>2. Stored in Heap Memory</h4><ul><li>StringBuffer objects are created using new, so they are stored in the <strong>heap memory</strong>, not in the String Constant Pool.</li></ul><h4>3. Thread-Safe (Synchronized)</h4><ul><li>All methods in StringBuffer are <strong>synchronized</strong>.</li><li>That means only one thread can modify it at a time → <strong>Safe in multithreaded environments</strong>.</li></ul><h4>4. Performance: Slower than StringBuilder</h4><ul><li>Due to synchronization, StringBuffer is <strong>slightly slower</strong> than StringBuilder.</li><li>Best used <strong>only when multiple threads</strong> are accessing the same object.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c659b61ff1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java 8: The Turning Point in Java Programming]]></title>
            <link>https://medium.com/@maheshmaahi151098/java-8-the-turning-point-in-java-programming-a3e463a3268b?source=rss-3019a213a021------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3e463a3268b</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[java-8-feature]]></category>
            <dc:creator><![CDATA[Maheshkumar Srinivasan]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 01:31:02 GMT</pubDate>
            <atom:updated>2025-06-08T01:31:02.828Z</atom:updated>
            <content:encoded><![CDATA[<p>What is Java 8?</p><p>Java 8 is a big update to the Java programming language released by Oracle. It added new features like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V5qQ3PgJFaV52uOT.png" /></figure><ol><li><strong>Functional interfaces</strong></li><li><strong>Streams API</strong></li><li><strong>lambda expressions</strong></li><li><strong>ForEach() method</strong></li><li><strong>String joiner</strong></li><li><strong>Optional class</strong></li><li><strong>Method reference</strong></li><li><strong>default methods</strong></li><li><strong>Nashorn JavaScript Engine</strong></li><li><strong>new date and time API.</strong></li></ol><p>These features make Java code Shorter, Easier, Faster to run and reduce the lines of code and it helps developers write modern and clean code.</p><h3><strong>Functional interfaces</strong></h3><blockquote>A <strong>functional interface</strong> is an interface that has <strong>only one abstract method</strong>.<br> It is used mainly with <strong>lambda expressions</strong> in Java 8.</blockquote><pre>@FunctionalInterface<br>interface MyInterface {<br>    void show();  // Only one abstract method<br>}</pre><p>This interface can be used with a lambda:</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        MyInterface m = () -&gt; System.out.println(&quot;Hello from show!&quot;);<br>        m.show();<br>    }<br>}</pre><h3><strong>Streams API</strong></h3><blockquote>Stream API is a feature in Java 8.<br>It is used to work with collections like List or Set.<br>It helps to write less code and do things like filtering, sorting, and looping easily.</blockquote><h4>Stream Operations:</h4><h4>1. Intermediate Operations (do something, return new stream):</h4><ul><li>filter() – keep matching items</li><li>map() – change each item</li><li>sorted() – sort items</li><li>distinct() – remove duplicates</li></ul><h4>2. Terminal Operations (ends the stream):</h4><ul><li>forEach() – do something with each item</li><li>collect() – get a result like a list</li><li>count() – count items</li><li>reduce() – combine items into one</li></ul><pre>import java.util.*;<br>import java.util.stream.*;<br><br>public class Main {<br>    public static void main(String[] args) {<br>        List&lt;String&gt; names = Arrays.asList(&quot;John&quot;, &quot;Alice&quot;, &quot;Bob&quot;, &quot;David&quot;);<br><br>        // Print names with more than 3 letters in uppercase<br>        names.stream()<br>             .filter(name -&gt; name.length() &gt; 3)<br>             .map(String::toUpperCase)<br>             .forEach(System.out::println);<br>    }<br>}</pre><h3><strong>lambda expressions</strong></h3><blockquote><strong>Lambda expression</strong> is a short way to write code for a method.<br> It helps you write less code and makes your code easier to read.</blockquote><blockquote>Lambda expressions can only be used with <strong>functional interfaces</strong> — interfaces that have exactly one abstract method.<br> If an interface has more than one abstract method, you cannot use a lambda expression with it.</blockquote><pre>//Syntax of Lambda<br>(parameter) -&gt; { code }</pre><pre>//Before using lambda<br>MyInterface msg = new MyInterface() {<br>    public void myAbstractMethod() {<br>        System.out.println(&quot;Hello!&quot;);<br>    }<br>};</pre><pre>//After using lambda<br>MyInterface msg = () -&gt; System.out.println(&quot;Hello!&quot;);<br>msg.myAbstractMethod();</pre><p>Lambda is used in Stream Api, Runnable, Event Listeners, Functional Interfaces.</p><h3><strong>forEach( ) method</strong></h3><blockquote>The <strong>forEach()</strong> method is a simple way to do something for each item in a collection like a list or set.</blockquote><blockquote>It makes your code shorter and easier compared to traditional loops.</blockquote><pre>//without using forEach<br>List&lt;String&gt; names = Arrays.asList(&quot;John&quot;, &quot;Alice&quot;, &quot;Bob&quot;);<br><br>for (String name : names) {<br>    System.out.println(name);<br>}</pre><pre>//using forEach<br>names.forEach(name -&gt; System.out.println(name));</pre><p>It works with Lists, Sets, Maps, Streams.</p><h3><strong>String joiner</strong></h3><blockquote><strong>StringJoiner</strong> is a new class in Java 8 that helps you join multiple strings easily using a <strong>delimiter</strong> like a comma.<br>It can also add a prefix and suffix around the joined string.</blockquote><p>A <strong>delimiter</strong> is a character or symbol that is used to separate or divide items in a list.</p><p>For example, in a list of words separated by commas, the <strong>comma (“,”)</strong> is the delimiter.</p><pre>import java.util.StringJoiner;<br><br>public class Main {<br>    public static void main(String[] args) {<br>        StringJoiner joiner = new StringJoiner(&quot;, &quot;); // delimiter is comma and space<br>        joiner.add(&quot;Apple&quot;);<br>        joiner.add(&quot;Banana&quot;);<br>        joiner.add(&quot;Cherry&quot;);<br><br>        System.out.println(joiner.toString());  // Output: Apple, Banana, Cherry<br>    }<br>}</pre><pre>StringJoiner joiner = new StringJoiner(&quot;, &quot;, &quot;[&quot;, &quot;]&quot;);<br>joiner.add(&quot;Red&quot;);<br>joiner.add(&quot;Green&quot;);<br>joiner.add(&quot;Blue&quot;);<br><br>System.out.println(joiner.toString());  // Output: [Red, Green, Blue]</pre><h3><strong>Optional class</strong></h3><blockquote><strong>Optional</strong> is a container object which may or may not contain a value.<br>It helps to avoid problems with <strong>null</strong> values and reduces the chance of getting a <strong>NullPointerException</strong>.</blockquote><p>Why use Optional? — Instead of returning or using null, you use Optional to clearly show that a value might be missing.</p><pre>Optional&lt;String&gt; name = Optional.ofNullable(null);<br><br>if (name.isPresent()) {<br>    System.out.println(name.get());<br>} else {<br>    System.out.println(&quot;No value found&quot;);<br>}</pre><ul><li>Optional.of(value)-if value is not null.</li><li>Optional.ofNullable(value)- if value might be null.</li><li>isPresent()- to check if a value exists.</li><li>get()- to get the value safely.</li></ul><h3><strong>Method reference</strong></h3><blockquote><strong>Method reference</strong> is a short and clean way to call a method using :: instead of writing a full lambda expression.</blockquote><blockquote>It makes your code even <strong>simpler</strong> when you are just calling an existing method.</blockquote><pre>//Syntax<br>ClassName::methodName</pre><pre>//without using method reference<br>list.forEach(name -&gt; System.out.println(name));</pre><pre>//with using method reference<br>list.forEach(System.out::println);</pre><p>Types of Method References:</p><ol><li><strong>Static method: </strong>ClassName::staticMethod<br> Example: Integer::parseInt</li><li><strong>Instance method (object): </strong>object::instanceMethod<br> Example: str::toUpperCase</li><li><strong>Instance method (class): </strong>ClassName::instanceMethod<br> Example: String::toLowerCase</li><li><strong>Constructor reference: </strong>ClassName::new<br> Example: ArrayList::new</li></ol><h3><strong>default methods</strong></h3><blockquote><strong>Default methods</strong> let you add <strong>method implementations</strong> inside <strong>interfaces</strong>.</blockquote><blockquote>Before Java 8, interfaces could only have <strong>abstract methods</strong> (no body).<br> But from Java 8, you can write methods <strong>with body</strong> using the default keyword.</blockquote><blockquote>Main purpose is <strong>add new methods to interfaces</strong> without breaking the existing classes that use them.</blockquote><pre>interface MyInterface {<br>    default void show() {<br>        System.out.println(&quot;This is a default method.&quot;);<br>    }<br><br>    void display(); // abstract method<br>}<br><br>class MyClass implements MyInterface {<br>    public void display() {<br>        System.out.println(&quot;Display method in MyClass.&quot;);<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        MyClass obj = new MyClass();<br>        obj.show();     // Default method<br>        obj.display();  // Implemented method<br>    }<br>}</pre><h3><strong>Nashorn JavaScript Engine</strong></h3><blockquote><strong>Nashorn</strong> is a <strong>JavaScript engine</strong> introduced in <strong>Java 8</strong>. It allows you to <strong>run JavaScript code inside Java programs</strong>.</blockquote><blockquote>It’s <strong>faster</strong> and <strong>more modern</strong> than the old JavaScript engine (Rhino)</blockquote><p>But Nashorn was <strong>removed in Java 15</strong> — it’s still good to know for Java 8!</p><pre>import javax.script.*;<br><br>public class Main {<br>    public static void main(String[] args) throws Exception {<br>        // Create Nashorn engine<br>        ScriptEngine engine = new ScriptEngineManager().getEngineByName(&quot;nashorn&quot;);<br><br>        // Run JavaScript code<br>        engine.eval(&quot;print(&#39;Hello from JavaScript!&#39;);&quot;);<br>    }<br>}</pre><h3><strong>New date and time API.</strong></h3><p>Before Java 8, developers used java.util.Date and java.util.Calendar, but they had <strong>many problems</strong>: Complicated to use, <strong>Not thread-safe, </strong>Hard to format and parse</p><p>Java 8 introduced a brand-new <strong>Date and Time API</strong> in the package java.time.</p><pre>import java.time.LocalDate;<br>import java.time.LocalTime;<br>import java.time.LocalDateTime;<br>import java.time.format.DateTimeFormatter;<br><br>public class DateTimeExample {<br>    public static void main(String[] args) {<br>        LocalDate date = LocalDate.now();             // Get current date<br>        LocalTime time = LocalTime.now();             // Get current time<br>        LocalDateTime dateTime = LocalDateTime.now(); // Get date + time<br><br>        // Format date and time<br>        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd HH:mm:ss&quot;);<br>        String formatted = dateTime.format(formatter);<br><br>        System.out.println(&quot;Date: &quot; + date);<br>        System.out.println(&quot;Time: &quot; + time);<br>        System.out.println(&quot;Formatted DateTime: &quot; + formatted);<br>    }<br>}</pre><p>Key Classes in Java 8 Date/Time API:</p><p>LocalDate — For date only (e.g., 2025-06-08)</p><p>LocalTime — For time only (e.g., 14:30:00)</p><p>LocalDateTime — For both date and time</p><p>DateTimeFormatter — For formatting date/time</p><p>Period / Duration — For difference between dates or times</p><p>ZonedDateTime — For date/time with time zone</p><h3>Conclusion:</h3><p>Java 8 was a turning point for the Java programming language. By using its powerful features, you can write cleaner code and avoid many common coding problems.</p><p><strong>Thanks for reading! If this helped you, give it a 👏 or drop a comment — I’d love to hear which Java 8 feature you use the most. If you spot anything wrong in the blog, feel free to comment. Otherwise, don’t forget to share it with others!</strong> 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3e463a3268b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Map Showdown: HashMap vs Hashtable vs Synchronized Map vs Concurrent HashMap]]></title>
            <link>https://medium.com/@maheshmaahi151098/java-map-showdown-hashmap-vs-hashtable-vs-synchronized-map-vs-concurrent-hashmap-f25c3fe246f1?source=rss-3019a213a021------2</link>
            <guid isPermaLink="false">https://medium.com/p/f25c3fe246f1</guid>
            <dc:creator><![CDATA[Maheshkumar Srinivasan]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 02:40:30 GMT</pubDate>
            <atom:updated>2025-06-07T02:40:30.248Z</atom:updated>
            <content:encoded><![CDATA[<p>In Java, when we work with Key-value Pairs, We often use Map implementations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYkQknw_2EKYSE9PgVyaIg.png" /></figure><p>Before Know the difference, we need to understand this First,</p><p><strong>Synchronization</strong>: Only one thread has allowed to access the resources, because at a time two or more thread If it&#39;s accessed the sane resources it will ambiguous.</p><p><strong>Lock:</strong> usually refers to a mechanism that prevents multiple threads from accessing shared data simultaneously.</p><p><strong>Fail-Fast: </strong>One thread iteration is happening when another thread do some operation that time exception will occur.</p><p><strong>Fail-safe: One</strong> thread iteration is happening when another thread do some operation that time Does not throw any exception.</p><p>Lets Dive into the topic,</p><h3>HashMap</h3><ol><li><strong>Not Synchronized</strong> — Not thread-safe by default.</li><li><strong>No Lock</strong> — No internal locking mechanism.</li><li><strong>Not Thread-Safe</strong> — Unsafe in multi-threaded environments without external synchronization.</li><li><strong>Fail-Fast</strong> — Throws ConcurrentModificationException if modified while iterating.</li><li>Allows One null key multiple null value.</li><li><strong>Good for Single-Threaded Environment</strong> — Fast and efficient when used with one thread.</li></ol><pre>//Unsafe Example<br>Map&lt;String, String&gt; map = new HashMap&lt;&gt;();<br>Thread t1 = () -&gt; map.put(&quot;A&quot;, &quot;Apple&quot;);<br>Thread t2 = () -&gt; map.put(&quot;B&quot;, &quot;Banana&quot;);<br>t1.start();<br>t2.start();</pre><h3>Hashtable</h3><ol><li><strong>All Operations are Synchronized</strong> — Thread-safe.</li><li><strong>Object-Level Lock</strong> — Entire object is locked for every operation.</li><li><strong>Supports One Thread at a Time</strong></li><li>Does not allow null key and null value.</li><li><strong>Fail-Fast</strong> — Throws ConcurrentModificationException if modified while iterating.</li><li>It is a legacy class &amp; not recommended to use.</li></ol><pre>Hashtable&lt;String, String&gt; table = new Hashtable&lt;&gt;();<br>table.put(null, &quot;value&quot;); //Throws NullPointerException</pre><h3>Synchronized Map</h3><ol><li><strong>All Operations are Synchronized</strong> — Thread-safe.</li><li><strong>Object-Level Lock</strong> — Entire object is locked for every operation.</li><li><strong>Supports Multiple Threads</strong>, but <strong>only one thread can access it at a time</strong> due to global locking.</li><li>Allows One null key multiple null value, Because Hashmap internally.</li><li><strong>Fail-Fast</strong> — Throws ConcurrentModificationException if modified while iterating.</li><li><strong>Works in Multithreaded Environments</strong>, but <strong>less efficient</strong> than ConcurrentHashMap.</li></ol><pre>import java.util.Collections;<br>import java.util.HashMap;<br>import java.util.Map;<br><br>public class SynchronizedMapExample {<br>    public static void main(String[] args) {<br>        // Create a synchronized map wrapping a HashMap<br>        Map&lt;String, String&gt; syncMap = Collections.synchronizedMap(new HashMap&lt;&gt;());<br><br>        // Add some key-value pairs<br>        syncMap.put(&quot;A&quot;, &quot;Apple&quot;);<br>        syncMap.put(&quot;B&quot;, &quot;Banana&quot;);<br>        syncMap.put(&quot;C&quot;, &quot;Cherry&quot;);<br><br>        System.out.println(&quot;Contents of synchronized map: &quot; + syncMap);<br><br>        // Safe iteration over synchronizedMap<br>        synchronized (syncMap) {<br>            for (String key : syncMap.keySet()) {<br>                System.out.println(key + &quot; =&gt; &quot; + syncMap.get(key));<br>            }<br>        }<br>    }<br>}</pre><h3>Concurrent HashMap</h3><ol><li><strong>Only write operations are synchronized</strong> — reads are mostly lock-free, improving concurrency.</li><li><strong>Segment level locking</strong></li></ol><ul><li><strong>Java 7 and earlier:</strong><br> The map is divided into 16 parts called <strong>segments</strong>.<br> Each segment has its own lock.<br> So, up to 16 threads can write at the same time, each working on a different segment.</li><li><strong>Java 8 and later:</strong><br> Instead of segments, it uses <strong>small locks on individual buckets (bins)</strong>.<br> This means locking is more precise and allows even better concurrency.</li></ul><p>3.<strong>Supports multiple threads for updates and reads simultaneously</strong> — e.g., 16 threads can update, multiple threads can read concurrently.</p><p>4.Does not allow null key and null value.</p><p>5.Fail-safe-Does not throw ConcurrentModificationException during iteration.</p><p>6.Works in Multithreaded Environments.</p><pre>import java.util.concurrent.ConcurrentHashMap;<br><br>public class ConcurrentHashMapDemo {<br>    public static void main(String[] args) {<br>        ConcurrentHashMap&lt;String, Integer&gt; map = new ConcurrentHashMap&lt;&gt;();<br><br>        // Thread 1 adds &quot;apple&quot;<br>        Thread t1 = new Thread(() -&gt; {<br>            map.put(&quot;apple&quot;, 1);<br>            System.out.println(&quot;Thread 1 added apple&quot;);<br>        });<br><br>        // Thread 2 adds &quot;banana&quot;<br>        Thread t2 = new Thread(() -&gt; {<br>            map.put(&quot;banana&quot;, 2);<br>            System.out.println(&quot;Thread 2 added banana&quot;);<br>        });<br><br>        t1.start();<br>        t2.start();<br><br>        // Wait for both threads to finish<br>        try {<br>            t1.join();<br>            t2.join();<br>        } catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br><br>        // Print the contents of the map<br>        System.out.println(&quot;Map contents: &quot; + map);<br>    }<br>}</pre><ul><li>Two threads put values into the map at the same time.</li><li>ConcurrentHashMap handles the synchronization internally.</li><li>No locking of the entire map, so better concurrency.</li><li>You won’t get errors like ConcurrentModificationException while iterating (fail-safe).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f25c3fe246f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write code for tomorrow, not just for today: SOLID Principles]]></title>
            <link>https://medium.com/@maheshmaahi151098/write-code-for-tomorrow-not-just-for-today-solid-principles-d37bf3cd1dce?source=rss-3019a213a021------2</link>
            <guid isPermaLink="false">https://medium.com/p/d37bf3cd1dce</guid>
            <dc:creator><![CDATA[Maheshkumar Srinivasan]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 16:38:32 GMT</pubDate>
            <atom:updated>2025-06-01T16:38:32.478Z</atom:updated>
            <content:encoded><![CDATA[<p>This Principle Written for making our code Easily readable, Maintainable, avoid messy codes, Flexible to change and reusable.</p><h3>The SOLID principles are five design principles</h3><ol><li><strong>S</strong> — <strong>Single Responsibility Principle (SRP)</strong></li></ol><p>2. <strong>O</strong> — <strong>Open/Closed Principle (OCP)</strong></p><p>3. <strong>L</strong> — <strong>Liskov Substitution Principle (LSP)</strong></p><p>4. <strong>I</strong> — <strong>Interface Segregation Principle (ISP)</strong></p><p>5. <strong>D</strong> — <strong>Dependency Inversion Principle (DIP)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*M7WpPkLUXTk8Y6wt" /></figure><h3><strong>S</strong> — <strong>Single Responsibility Principle (SRP)</strong></h3><p>Each Class and module in a program should focus on a single task.</p><p>Implementation of many functionalities in one class the code is mashup, if any changes in the Functionality whole class may affect the whole class so we go to SRP.</p><h3>❌ Wrong:</h3><pre>public class Student{<br>    public void printDetails(){<br>        System.out.println(&quot;StudentDetails&quot;);<br>    }<br>    public void percentage(){<br>        System.out.println(&quot;Percentage&quot;);<br>    }<br>    public void addStudent(){<br>        System.out.println(&quot;addStudent&quot;);<br>    }</pre><h3>✅ Right:</h3><pre>public class StudentDetails{<br>    public void printDetails(){<br>        System.out.println(&quot;StudentDetails&quot;);<br>    }<br>}<br>public class StudentPercentage{<br>public void percentage(){<br>        System.out.println(&quot;Percentage&quot;);<br>    }<br>}<br>public class AddStudent{<br>public void addStudent(){<br>        System.out.println(&quot;addStudent&quot;);<br>    }<br>}</pre><h3><strong>O</strong> — <strong>Open/Closed Principle (OCP)</strong></h3><p>The Module open for extension Closed for modification.</p><p>If we change existing code, it may create bugs. So, to avoid this, we follow the Open/Closed Principle (OCP).</p><h3>❌ Wrong:</h3><pre>class NotificationService {<br>    void sendNotification(String type, String message) {<br>        if (type.equals(&quot;email&quot;)) {<br>            // send email<br>            System.out.println(&quot;Sending Email: &quot; + message);<br>        } else if (type.equals(&quot;sms&quot;)) {<br>            // send sms<br>            System.out.println(&quot;Sending SMS: &quot; + message);<br>        }<br>        // Every time new notification type added, modify this method!<br>    }<br>}</pre><h3>✅ Right:</h3><pre>interface Notification {<br>    void send(String message);<br>}<br><br>class EmailNotification implements Notification {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending Email: &quot; + message);<br>    }<br>}<br><br>class SmsNotification implements Notification {<br>    public void send(String message) {<br>        System.out.println(&quot;Sending SMS: &quot; + message);<br>    }<br>}<br><br>class NotificationService {<br>    void sendNotification(Notification notification, String message) {<br>        notification.send(message);<br>    }<br>}</pre><h3><strong>L</strong> — <strong>Liskov Substitution Principle (LSP)</strong></h3><p>Sub class methods act as a superclass method as long as no problem occur.</p><h3>❌ Wrong:</h3><pre>class Bird {<br>    void fly() {<br>        System.out.println(&quot;Bird is flying&quot;);<br>    }<br>}<br><br>class Penguin extends Bird {<br>    @Override<br>    void fly() {<br>        throw new UnsupportedOperationException(&quot;Penguin can&#39;t fly!&quot;);<br>    }<br>}</pre><pre>Bird b = new Penguin();<br>b.fly(); // </pre><h3>✅ Right:</h3><pre>//SuperClass<br>class Bird {<br>    void eat() {<br>        System.out.println(&quot;Bird is eating&quot;);<br>    }<br>}<br><br>interface Flyable {<br>    void fly();<br>}</pre><pre>//SubClass<br>class Parrot extends Bird implements Flyable {<br>    public void fly() {<br>        System.out.println(&quot;Parrot is flying&quot;);<br>    }<br>}<br><br>class Penguin extends Bird {<br>    // Penguin doesn&#39;t fly, so not implementing Flyable<br>}</pre><pre>//Now we can use safely<br>Flyable f = new Parrot(); // OK<br>f.fly(); // Output: Parrot is flying<br><br>Bird b = new Penguin();  // OK<br>b.eat(); // Output: Bird is eating</pre><h3><strong>I</strong> — <strong>Interface Segregation Principle (ISP)</strong></h3><p>Don’t give too many methods to one class. Give only what it needs.</p><p>If a class is forced to implement methods it doesn’t use,<br> that’s bad design.</p><p>So, we have write big interfaces(Have many methods)into small small interface.</p><pre>//Interface having many metho<br>interface Printer {<br>    void print();<br>    void scan();<br>    void fax();<br>}</pre><pre>//We didn&#39;t use last two methods<br>class BasicPrinter implements Printer {<br>    public void print() { /* ok */ }<br>    public void scan() { /* not needed */ } // ❌<br>    public void fax() { /* not needed */ }  // ❌<br>}</pre><pre>//Correct way<br>interface Printable {<br>    void print();<br>}<br><br>interface Scannable {<br>    void scan();<br>}<br><br>class BasicPrinter implements Printable {<br>    public void print() {<br>        System.out.println(&quot;Printing...&quot;);<br>    }<br>}</pre><h3><strong>D</strong> — <strong>Dependency Inversion Principle (DIP)</strong></h3><p>High-level classes should not depend on low-level classes, both should depend on abstractions (like interfaces).</p><h3>❌ Wrong:</h3><pre>class LightBulb {<br>    void turnOn() {<br>        System.out.println(&quot;Light is ON&quot;);<br>    }<br>}<br><br>class Switch {<br>    LightBulb bulb;<br><br>    Switch(LightBulb bulb) {<br>        this.bulb = bulb;<br>    }<br><br>    void press() {<br>        bulb.turnOn();<br>    }<br>}</pre><h3>✅ Right:</h3><pre>interface Switchable {<br>    void turnOn();<br>}<br><br>class LightBulb implements Switchable {<br>    public void turnOn() {<br>        System.out.println(&quot;Light is ON&quot;);<br>    }<br>}<br><br>class Fan implements Switchable {<br>    public void turnOn() {<br>        System.out.println(&quot;Fan is ON&quot;);<br>    }<br>}<br><br>class Switch {<br>    Switchable device;<br><br>    Switch(Switchable device) {<br>        this.device = device;<br>    }<br><br>    void press() {<br>        device.turnOn();<br>    }<br>}</pre><p>Code should depend on interface, not on direct object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d37bf3cd1dce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>