<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Anjan Baradwaj - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Anjan Baradwaj - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 22 May 2026 17:39:11 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/anjanbaradwaj/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use the Java Collections Framework – A Guide for Developers ]]>
                </title>
                <description>
                    <![CDATA[ In your Java applications, you’ll typically work with various types of objects. And you might want to perform operations like sorting, searching, and iterating on these objects. Prior to the introduction of the Collections framework in JDK 1.2, you w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/java-collections-framework-reference-guide/</link>
                <guid isPermaLink="false">6798fd38ac05f27ed5691abd</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Collection Framework ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Anjan Baradwaj ]]>
                </dc:creator>
                <pubDate>Tue, 28 Jan 2025 15:52:24 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738077724002/cfbf6a90-f9c2-4853-b1c3-c33774f078c1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In your Java applications, you’ll typically work with various types of objects. And you might want to perform operations like sorting, searching, and iterating on these objects.</p>
<p>Prior to the introduction of the Collections framework in JDK 1.2, you would’ve used Arrays and Vectors to store and manage a group of objects. But they had their own share of drawbacks.</p>
<p>The Java Collections Framework aims to overcome these issues by providing high-performance implementations of common data structures. These allow you to focus on writing the application logic instead of focusing on low-level operations.</p>
<p>Then, the introduction of Generics in JDK 1.5 significantly improved the Java Collections Framework. Generics let you enforce type safety for objects stored in a collection, which enhances the robustness of your applications. You can read more about Java Generics <a target="_blank" href="https://www.freecodecamp.org/news/generics-in-java/">here</a>.</p>
<p>In this article, I will guide you through how to use the Java Collections Framework. We’ll discuss the different types of collections, such as Lists, Sets, Queues, and Maps. I’ll also provide a brief explanation of their key characteristics such as:</p>
<ul>
<li><p>Internal mechanisms</p>
</li>
<li><p>Handling of duplicates</p>
</li>
<li><p>Support for null values</p>
</li>
<li><p>Ordering</p>
</li>
<li><p>Synchronization</p>
</li>
<li><p>Performance</p>
</li>
<li><p>Key methods</p>
</li>
<li><p>Common implementations</p>
</li>
</ul>
<p>We’ll also walk through some code examples for better understanding, and I’ll touch on the Collections utility class and its usage.</p>
<h2 id="heading-table-of-contents">Table of Contents:</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-understanding-the-java-collections-framework">Understanding the Java Collections Framework</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-collection-interfaces">Collection Interfaces</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-decoding-the-java-collections-framework-hierarchy">Decoding the Java Collections Framework Hierarchy</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-closer-look-at-collection-interfaces">A Closer Look at Collection Interfaces</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-java-collection-interfaces">Java Collection Interfaces</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-lists">Lists</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-sets">Sets</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-queues">Queues</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-maps">Maps</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-collections-utility-class">Collections Utility Class</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-understanding-the-java-collections-framework"><strong>Understanding the Java Collections Framework</strong></h2>
<p>According to the Java <a target="_blank" href="https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html">documentation</a>, “<em>A collection is an object that represents a group of objects. A collections framework is a unified architecture for representing and manipulating collections</em>.”</p>
<p>In simple terms, the Java Collections Framework helps you manage a group of objects and perform operations on them efficiently and in an organized way. It makes it easier to develop applications by offering various methods to handle groups of objects. You can add, remove, search, and sort objects effectively using the Java Collections Framework.</p>
<h3 id="heading-collection-interfaces">Collection Interfaces</h3>
<p>In Java, an interface specifies a contract that must be fulfilled by any class that implements it. This means the implementing class must provide concrete implementations for all the methods declared in the interface.</p>
<p>In the Java Collections Framework, various collection interfaces like <code>Set</code>, <code>List</code>, and <code>Queue</code> extend the <code>Collection</code> interface, and they must adhere to the contract defined by the <code>Collection</code> interface.</p>
<h3 id="heading-decoding-the-java-collections-framework-hierarchy">Decoding the Java Collections Framework Hierarchy</h3>
<p>Check out this neat diagram from this <a target="_blank" href="https://medium.com/@mbanaee61/mastering-the-java-collections-framework-hierarchy-with-java-code-and-junit-testing-ab2eb87746ed">article</a> that illustrates the Java Collection Hierarchy:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1736532451482/6ef571c1-afe0-4314-9038-b472b06f4065.webp" alt="Diagram showing the Java Collection Framework hierarchy. It includes interfaces like Iterable, Collection, List, Queue, Set, Map, and SortedMap, with classes such as ArrayList, LinkedList, Vector, Stack, PriorityQueue, Deque, HashSet, LinkedHashSet, SortedSet, TreeSet, Hashtable, LinkedHashMap, HashMap, and TreeMap. Arrows indicate implementation and extension relationships." class="image--center mx-auto" width="822" height="576" loading="lazy"></p>
<p>We’ll start from the top and work down so you can understand what this diagram is showing:</p>
<ol>
<li><p>At the root of the Java Collections Framework is the <code>Iterable</code> interface, which lets you iterate over the elements of a collection.</p>
</li>
<li><p>The <code>Collection</code> interface extends the <code>Iterable</code> interface. This means it inherits the properties and behavior of the <code>Iterable</code> interface and adds its own behavior for adding, removing, and retrieving elements.</p>
</li>
<li><p>Specific interfaces such as <code>List</code>, <code>Set</code>, and <code>Queue</code> further extend the <code>Collection</code> interface. Each of these interfaces has other classes implementing their methods. For example, <code>ArrayList</code> is a popular implementation of the <code>List</code> interface, <code>HashSet</code> implements the <code>Set</code> interface, and so on.</p>
</li>
<li><p>The <code>Map</code> interface is part of the Java Collections Framework, but it does not extend the <code>Collection</code> interface, unlike the others mentioned above.</p>
</li>
<li><p>All the interfaces and classes in this framework are part of the <code>java.util</code> package.</p>
</li>
</ol>
<p>Note: A common source of confusion in the Java Collections Framework revolves around the difference between <code>Collection</code> and <code>Collections</code>. <code>Collection</code> is an interface in the framework, while <code>Collections</code> is a utility class. The <code>Collections</code> class provides static methods that perform operations on the elements of a collection.</p>
<h2 id="heading-java-collection-interfaces">Java Collection Interfaces</h2>
<p>By now, you’re familiar with the different types of collections that form the foundation of the collections framework. Now we’ll take a closer look at the <code>List</code>, <code>Set</code>, <code>Queue</code>, and <code>Map</code> interfaces.</p>
<p>In this section, we'll discuss each of these interfaces while exploring their internal mechanisms. We'll examine how they handle duplicate elements and whether they support the insertion of null values. We'll also understand the ordering of elements during insertion and their support for synchronization, which deals with the concept of thread safety. Then we’ll walk through a few key methods of these interfaces and conclude by reviewing common implementations and their performance for various operations.</p>
<p>Before we begin, let's talk briefly about Synchronization and Performance.</p>
<ul>
<li><p>Synchronization controls access to shared objects by multiple threads, ensuring their integrity and preventing conflicts. This is crucial for maintaining thread safety.</p>
</li>
<li><p>When choosing a collection type, one important factor is its performance during common operations like insertion, deletion, and retrieval. Performance is usually expressed using Big-O notation. You can learn more about it <a target="_blank" href="https://www.freecodecamp.org/news/big-o-notation-why-it-matters-and-why-it-doesnt-1674cfa8a23c/">here</a>.</p>
</li>
</ul>
<h3 id="heading-lists">Lists</h3>
<p>A <code>List</code> is an ordered or sequential collection of elements. It follows zero-based indexing, allowing the elements to be inserted, removed, or accessed using their index position.</p>
<ol>
<li><p><strong>Internal mechanism</strong>: A <code>List</code> is internally supported by either an array or a linked list, depending on the type of implementation. For example, an <code>ArrayList</code> uses an array, while a <code>LinkedList</code> uses a linked list internally. You can read more about <code>LinkedList</code> <a target="_blank" href="https://www.freecodecamp.org/news/how-linked-lists-work/">here</a>. A <code>List</code> dynamically resizes itself upon the addition or removal of elements. The indexing-based retrieval makes it a very efficient type of collection.</p>
</li>
<li><p><strong>Duplicates</strong>: Duplicate elements are allowed in a <code>List</code>, which means there can be more than one element in a <code>List</code> with the same value. Any value can be retrieved based on the index at which it is stored.</p>
</li>
<li><p><strong>Null</strong>: Null values are also allowed in a <code>List</code>. Since duplicates are permitted, you can also have multiple null elements.</p>
</li>
<li><p><strong>Ordering</strong>: A <code>List</code> maintains insertion order, meaning the elements are stored in the same order they are added. This is helpful when you want to retrieve elements in the exact order they were inserted.</p>
</li>
<li><p><strong>Synchronization</strong>: A <code>List</code> is not synchronized by default, which means it doesn't have a built-in way to handle access by multiple threads at the same time.</p>
</li>
<li><p><strong>Key methods</strong>: Here are some key methods of a <code>List</code> interface: <code>add(E element)</code>, <code>get(int index)</code>, <code>set(int index, E element)</code>, <code>remove(int index)</code>, and <code>size()</code>. Let's look at how to use these methods with an example program.</p>
<pre><code class="lang-java"> <span class="hljs-keyword">import</span> java.util.ArrayList;
 <span class="hljs-keyword">import</span> java.util.List;

 <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ListExample</span> </span>{
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
         <span class="hljs-comment">// Create a list</span>
         List&lt;String&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

         <span class="hljs-comment">// add(E element)</span>
         list.add(<span class="hljs-string">"Apple"</span>);
         list.add(<span class="hljs-string">"Banana"</span>);
         list.add(<span class="hljs-string">"Cherry"</span>);

         <span class="hljs-comment">// get(int index)</span>
         String secondElement = list.get(<span class="hljs-number">1</span>); <span class="hljs-comment">// "Banana"</span>

         <span class="hljs-comment">// set(int index, E element)</span>
         list.set(<span class="hljs-number">1</span>, <span class="hljs-string">"Blueberry"</span>);

         <span class="hljs-comment">// remove(int index)</span>
         list.remove(<span class="hljs-number">0</span>); <span class="hljs-comment">// Removes "Apple"</span>

         <span class="hljs-comment">// size()</span>
         <span class="hljs-keyword">int</span> size = list.size(); <span class="hljs-comment">// 2</span>

         <span class="hljs-comment">// Print the list</span>
         System.out.println(list); <span class="hljs-comment">// Output: [Blueberry, Cherry]</span>

         <span class="hljs-comment">// Print the size of the list</span>
         System.out.println(size); <span class="hljs-comment">// Output: 2</span>
     }
 }
</code></pre>
</li>
<li><p><strong>Common implementations</strong>: <code>ArrayList</code>, <code>LinkedList</code>, <code>Vector</code>, <code>Stack</code></p>
</li>
<li><p><strong>Performance</strong>: Typically, insert and delete operations are fast in both <code>ArrayList</code> and <code>LinkedList</code>. But fetching elements can be slow because you have to traverse through the nodes.</p>
</li>
</ol>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Operation</strong></td><td><strong>ArrayList</strong></td><td><strong>LinkedList</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Insertion</td><td>Fast at the end - O(1) amortized, slow at the beginning or middle- O(n)</td><td>Fast at the beginning or middle - O(1), slow at the end - O(n)</td></tr>
<tr>
<td>Deletion</td><td>Fast at the end - O(1) amortized, slow at the beginning or middle- O(n)</td><td>Fast - O(1) if position is known</td></tr>
<tr>
<td>Retrieval</td><td>Fast - O(1) for random access</td><td>Slow - O(n) for random access, as it involves traversing</td></tr>
</tbody>
</table>
</div><h3 id="heading-sets">Sets</h3>
<p>A <code>Set</code> is a type of collection that does not allow duplicate elements and represents the concept of a mathematical set.</p>
<ol>
<li><p><strong>Internal mechanism</strong>: A <code>Set</code> is internally backed by a <code>HashMap</code>. Depending on the implementation type, it is supported by either a <code>HashMap</code>, <code>LinkedHashMap</code>, or a <code>TreeMap</code>. I have written a detailed article about how <code>HashMap</code> works internally <a target="_blank" href="https://www.freecodecamp.org/news/how-java-hashmaps-work-internal-mechanics-explained">here</a>. Be sure to check it out.</p>
</li>
<li><p><strong>Duplicates</strong>: Since a <code>Set</code> represents the concept of a mathematical set, duplicate elements are not allowed. This ensures that all elements are unique, maintaining the integrity of the collection.</p>
</li>
<li><p><strong>Null</strong>: A maximum of one null value is allowed in a <code>Set</code> because duplicates are not permitted. But this does not apply to the <code>TreeSet</code> implementation, where null values are not allowed at all.</p>
</li>
<li><p><strong>Ordering</strong>: Ordering of elements in a <code>Set</code> depends on the type of implementation.</p>
<ul>
<li><p><code>HashSet</code>: Order is not guaranteed, and elements can be placed in any position.</p>
</li>
<li><p><code>LinkedHashSet</code>: This implementation maintains the insertion order, so you can retrieve the elements in the same order they were inserted.</p>
</li>
<li><p><code>TreeSet</code>: Elements are inserted based on their natural order. Alternatively, you can control the insertion order by specifying a custom comparator.</p>
</li>
</ul>
</li>
<li><p><strong>Synchronization</strong>: A <code>Set</code> is not synchronized, meaning you might encounter concurrency issues, like race conditions, which can affect data integrity if two or more threads try to access a <code>Set</code> object simultaneously</p>
</li>
<li><p><strong>Key methods</strong>: Here are some key methods of a <code>Set</code> interface: <code>add(E element)</code>, <code>remove(Object o)</code>, <code>contains(Object o)</code>, and <code>size()</code>. Let's look at how to use these methods with an example program.</p>
<pre><code class="lang-java"> <span class="hljs-keyword">import</span> java.util.HashSet;
 <span class="hljs-keyword">import</span> java.util.Set;

 <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SetExample</span> </span>{
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
         <span class="hljs-comment">// Create a set</span>
         Set&lt;String&gt; set = <span class="hljs-keyword">new</span> HashSet&lt;&gt;();

         <span class="hljs-comment">// Add elements to the set</span>
         set.add(<span class="hljs-string">"Apple"</span>);
         set.add(<span class="hljs-string">"Banana"</span>);
         set.add(<span class="hljs-string">"Cherry"</span>);

         <span class="hljs-comment">// Remove an element from the set</span>
         set.remove(<span class="hljs-string">"Banana"</span>);

         <span class="hljs-comment">// Check if the set contains an element</span>
         <span class="hljs-keyword">boolean</span> containsApple = set.contains(<span class="hljs-string">"Apple"</span>);
         System.out.println(<span class="hljs-string">"Contains Apple: "</span> + containsApple);

         <span class="hljs-comment">// Get the size of the set</span>
         <span class="hljs-keyword">int</span> size = set.size();
         System.out.println(<span class="hljs-string">"Size of the set: "</span> + size);
     }
 }
</code></pre>
</li>
<li><p><strong>Common implementations</strong>: <code>HashSet</code>, <code>LinkedHashSet</code>, <code>TreeSet</code></p>
</li>
<li><p><strong>Performance</strong>: <code>Set</code> implementations offer fast performance for basic operations, except for a <code>TreeSet</code>, where the performance can be relatively slower because the internal data structure involves sorting the elements during these operations.</p>
</li>
</ol>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Operation</strong></td><td><strong>HashSet</strong></td><td><strong>LinkedHashSet</strong></td><td><strong>TreeSet</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Insertion</td><td>Fast - O(1)</td><td>Fast - O(1)</td><td>Slower - O(log n)</td></tr>
<tr>
<td>Deletion</td><td>Fast - O(1)</td><td>Fast - O(1)</td><td>Slower - O(log n)</td></tr>
<tr>
<td>Retrieval</td><td>Fast - O(1)</td><td>Fast - O(1)</td><td>Slower - O(log n)</td></tr>
</tbody>
</table>
</div><h3 id="heading-queues">Queues</h3>
<p>A <code>Queue</code> is a linear collection of elements used to hold multiple items before processing, usually following the FIFO (first-in-first-out) order. This means elements are added at one end and removed from the other, so the first element added to the queue is the first one removed.</p>
<ol>
<li><p><strong>Internal mechanism</strong>: The internal workings of a <code>Queue</code> can differ based on its specific implementation.</p>
<ul>
<li><p><code>LinkedList</code> – uses a doubly-linked list to store elements, which means you can traverse both forward and backward, allowing for flexible operations.</p>
</li>
<li><p><code>PriorityQueue</code> – is internally backed by a binary heap, which is very efficient for retrieval operations.</p>
</li>
<li><p><code>ArrayDeque</code> – is implemented using an array that expands or shrinks as elements are added or removed. Here, elements can be added or removed from both ends of the queue.</p>
</li>
</ul>
</li>
<li><p><strong>Duplicates</strong>: In a <code>Queue</code>, duplicate elements are permitted, allowing multiple instances of the same value to be inserted</p>
</li>
<li><p><strong>Null</strong>: You cannot insert a null value into a <code>Queue</code> because, by design, some methods of a <code>Queue</code> return null to indicate that it is empty. To avoid confusion, null values are not allowed.</p>
</li>
<li><p><strong>Ordering</strong>: Elements are inserted based on their natural order. Alternatively, you can control the insertion order by specifying a custom comparator.</p>
</li>
<li><p><strong>Synchronization</strong>: A <code>Queue</code> is not synchronized by default. But, you can use a <code>ConcurrentLinkedQueue</code> or a <code>BlockingQueue</code> implementation for achieving thread safety.</p>
</li>
<li><p><strong>Key methods</strong>: Here are some key methods of a <code>Queue</code> interface: <code>add(E element)</code>, <code>offer(E element)</code>, <code>poll()</code>, and <code>peek()</code>. Let's look at how to use these methods with an example program.</p>
<pre><code class="lang-java"> <span class="hljs-keyword">import</span> java.util.LinkedList;
 <span class="hljs-keyword">import</span> java.util.Queue;

 <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">QueueExample</span> </span>{
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
         <span class="hljs-comment">// Create a queue using LinkedList</span>
         Queue&lt;String&gt; queue = <span class="hljs-keyword">new</span> LinkedList&lt;&gt;();

         <span class="hljs-comment">// Use add method to insert elements, throws exception if insertion fails</span>
         queue.add(<span class="hljs-string">"Element1"</span>);
         queue.add(<span class="hljs-string">"Element2"</span>);
         queue.add(<span class="hljs-string">"Element3"</span>);

         <span class="hljs-comment">// Use offer method to insert elements, returns false if insertion fails</span>
         queue.offer(<span class="hljs-string">"Element4"</span>);

         <span class="hljs-comment">// Display queue</span>
         System.out.println(<span class="hljs-string">"Queue: "</span> + queue);

         <span class="hljs-comment">// Peek at the first element (does not remove it)</span>
         String firstElement = queue.peek();
         System.out.println(<span class="hljs-string">"Peek: "</span> + firstElement); <span class="hljs-comment">// outputs "Element1"</span>

         <span class="hljs-comment">// Poll the first element (retrieves and removes it)</span>
         String polledElement = queue.poll();
         System.out.println(<span class="hljs-string">"Poll: "</span> + polledElement); <span class="hljs-comment">// outputs "Element1"</span>

         <span class="hljs-comment">// Display queue after poll</span>
         System.out.println(<span class="hljs-string">"Queue after poll: "</span> + queue);
     }
 }
</code></pre>
</li>
<li><p><strong>Common implementations</strong>: <code>LinkedList</code>, <code>PriorityQueue</code>, <code>ArrayDeque</code></p>
</li>
<li><p><strong>Performance</strong>: Implementations like <code>LinkedList</code> and <code>ArrayDeque</code> are usually quick for adding and removing items. The <code>PriorityQueue</code> is a bit slower because it inserts items based on the set priority order.</p>
</li>
</ol>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Operation</strong></td><td><strong>LinkedList</strong></td><td><strong>PriorityQueue</strong></td><td><strong>ArrayDeque</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Insertion</td><td>Fast at the beginning or middle - O(1), slow at the end - O(n)</td><td>Slower - O(log n)</td><td>Fast - O(1), Slow - O(n), if it involves resizing of the internal array</td></tr>
<tr>
<td>Deletion</td><td>Fast - O(1) if position is known</td><td>Slower - O(log n)</td><td>Fast - O(1), Slow - O(n), if it involves resizing of the internal array</td></tr>
<tr>
<td>Retrieval</td><td>Slow - O(n) for random access, as it involves traversing</td><td>Fast - O(1)</td><td>Fast - O(1)</td></tr>
</tbody>
</table>
</div><h3 id="heading-maps">Maps</h3>
<p>A <code>Map</code> represents a collection of key-value pairs, with each key mapping to a single value. Although <code>Map</code> is part of the Java Collection framework, it does not extend the <code>java.util.Collection</code> interface.</p>
<ol>
<li><p><strong>Internal mechanism</strong>: A <code>Map</code> works internally using a <code>HashTable</code> based on the concept of hashing. I have written a detailed <a target="_blank" href="https://www.freecodecamp.org/news/how-java-hashmaps-work-internal-mechanics-explained">article</a> on this topic, so give it a read for a deeper understanding.</p>
</li>
<li><p><strong>Duplicates</strong>: A <code>Map</code> stores data as key-value pairs. Here, each key is unique, so duplicate keys are not allowed. But duplicate values are permitted.</p>
</li>
<li><p><strong>Null</strong>: Since duplicate keys are not allowed, a <code>Map</code> can have only one null key. As duplicate values are permitted, it can have multiple null values. In the <code>TreeMap</code> implementation, keys cannot be null because it sorts the elements based on the keys. However, null values are allowed.</p>
</li>
<li><p><strong>Ordering</strong>: Insertion order of a <code>Map</code> varies on the implementation:</p>
<ul>
<li><p><code>HashMap</code> – the insertion order is not guaranteed as they are determined based on the concept of hashing.</p>
</li>
<li><p><code>LinkedHashMap</code> – the insertion order is preserved and you can retrieve the elements back in the same order that they were added into the collection.</p>
</li>
<li><p><code>TreeMap</code> – Elements are inserted based on their natural order. Alternatively, you can control the insertion order by specifying a custom comparator.</p>
</li>
</ul>
</li>
<li><p><strong>Synchronization</strong>: A <code>Map</code> is not synchronized by default. But you can use <code>Collections.synchronizedMap()</code> or <code>ConcurrentHashMap</code> implementations for achieving thread safety.</p>
</li>
<li><p><strong>Key methods</strong>: Here are some key methods of a <code>Map</code> interface: <code>put(K key, V value)</code>, <code>get(Object key)</code>, <code>remove(Object key)</code>, <code>containsKey(Object key)</code>, and <code>keySet()</code>. Let's look at how to use these methods with an example program.</p>
<pre><code class="lang-java"> <span class="hljs-keyword">import</span> java.util.HashMap;
 <span class="hljs-keyword">import</span> java.util.Map;
 <span class="hljs-keyword">import</span> java.util.Set;

 <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MapMethodsExample</span> </span>{
     <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
         <span class="hljs-comment">// Create a new HashMap</span>
         Map&lt;String, Integer&gt; map = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

         <span class="hljs-comment">// put(K key, V value) - Inserts key-value pairs into the map</span>
         map.put(<span class="hljs-string">"Apple"</span>, <span class="hljs-number">1</span>);
         map.put(<span class="hljs-string">"Banana"</span>, <span class="hljs-number">2</span>);
         map.put(<span class="hljs-string">"Orange"</span>, <span class="hljs-number">3</span>);

         <span class="hljs-comment">// get(Object key) - Returns the value associated with the key</span>
         Integer value = map.get(<span class="hljs-string">"Banana"</span>);
         System.out.println(<span class="hljs-string">"Value for 'Banana': "</span> + value);

         <span class="hljs-comment">// remove(Object key) - Removes the key-value pair for the specified key</span>
         map.remove(<span class="hljs-string">"Orange"</span>);

         <span class="hljs-comment">// containsKey(Object key) - Checks if the map contains the specified key</span>
         <span class="hljs-keyword">boolean</span> hasApple = map.containsKey(<span class="hljs-string">"Apple"</span>);
         System.out.println(<span class="hljs-string">"Contains 'Apple': "</span> + hasApple);

         <span class="hljs-comment">// keySet() - Returns a set view of the keys contained in the map</span>
         Set&lt;String&gt; keys = map.keySet();
         System.out.println(<span class="hljs-string">"Keys in map: "</span> + keys);
     }
 }
</code></pre>
</li>
<li><p><strong>Common implementations</strong>: <code>HashMap</code>, <code>LinkedHashMap</code>, <code>TreeMap</code>, <code>Hashtable</code>, <code>ConcurrentHashMap</code></p>
</li>
<li><p><strong>Performance</strong>: <code>HashMap</code> implementation is widely used mainly due to its efficient performance characteristics depicted in the below table.</p>
</li>
</ol>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Operation</strong></td><td><strong>HashMap</strong></td><td><strong>LinkedHashMap</strong></td><td><strong>TreeMap</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Insertion</td><td>Fast - O(1)</td><td>Fast - O(1)</td><td>Slower - O(log n)</td></tr>
<tr>
<td>Deletion</td><td>Fast - O(1)</td><td>Fast - O(1)</td><td>Slower - O(log n)</td></tr>
<tr>
<td>Retrieval</td><td>Fast - O(1)</td><td>Fast - O(1)</td><td>Slower - O(log n)</td></tr>
</tbody>
</table>
</div><h2 id="heading-collections-utility-class">Collections Utility Class</h2>
<p>As highlighted at the beginning of this article, the <code>Collections</code> utility class has several useful static methods that let you perform commonly used operations on the elements of a collection. These methods help you reduce the boilerplate code in your application and lets you focus on the business logic.</p>
<p>Here are some key features and methods, along with what they do, listed briefly:</p>
<ol>
<li><p><strong>Sorting:</strong> <code>Collections.sort(List&lt;T&gt;)</code> – this method is used to sort the elements of a list in ascending order.</p>
</li>
<li><p><strong>Searching:</strong> <code>Collections.binarySearch(List&lt;T&gt;, key)</code> – this method is used to search for a specific element in a sorted list and return its index.</p>
</li>
<li><p><strong>Reverse order:</strong> <code>Collections.reverse(List&lt;T&gt;)</code> – this method is used to reverse the order of elements in a list.</p>
</li>
<li><p><strong>Min/Max Operations:</strong> <code>Collections.min(Collection&lt;T&gt;)</code> and <code>Collections.max(Collection&lt;T&gt;)</code> – these methods are used to find the minimum and maximum elements in a collection, respectively.</p>
</li>
<li><p><strong>Synchronization:</strong> <code>Collections.synchronizedList(List&lt;T&gt;)</code> – this method is used to make a list thread-safe by synchronizing it.</p>
</li>
<li><p><strong>Unmodifiable Collections:</strong> <code>Collections.unmodifiableList(List&lt;T&gt;)</code> – this method is used to create a read-only view of a list, preventing modifications.</p>
</li>
</ol>
<p>Here's a sample Java program that demonstrates various functionalities of the <code>Collections</code> utility class:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Collections;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CollectionsExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        List&lt;Integer&gt; numbers = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
        numbers.add(<span class="hljs-number">5</span>);
        numbers.add(<span class="hljs-number">3</span>);
        numbers.add(<span class="hljs-number">8</span>);
        numbers.add(<span class="hljs-number">1</span>);

        <span class="hljs-comment">// Sorting</span>
        Collections.sort(numbers);
        System.out.println(<span class="hljs-string">"Sorted List: "</span> + numbers);

        <span class="hljs-comment">// Searching</span>
        <span class="hljs-keyword">int</span> index = Collections.binarySearch(numbers, <span class="hljs-number">3</span>);
        System.out.println(<span class="hljs-string">"Index of 3: "</span> + index);

        <span class="hljs-comment">// Reverse Order</span>
        Collections.reverse(numbers);
        System.out.println(<span class="hljs-string">"Reversed List: "</span> + numbers);

        <span class="hljs-comment">// Min/Max Operations</span>
        <span class="hljs-keyword">int</span> min = Collections.min(numbers);
        <span class="hljs-keyword">int</span> max = Collections.max(numbers);
        System.out.println(<span class="hljs-string">"Min: "</span> + min + <span class="hljs-string">", Max: "</span> + max);

        <span class="hljs-comment">// Synchronization</span>
        List&lt;Integer&gt; synchronizedList = Collections.synchronizedList(numbers);
        System.out.println(<span class="hljs-string">"Synchronized List: "</span> + synchronizedList);

        <span class="hljs-comment">// Unmodifiable Collections</span>
        List&lt;Integer&gt; unmodifiableList = Collections.unmodifiableList(numbers);
        System.out.println(<span class="hljs-string">"Unmodifiable List: "</span> + unmodifiableList);
    }
}
</code></pre>
<p>This program demonstrates sorting, searching, reversing, finding minimum and maximum values, synchronizing, and creating an unmodifiable list using the <code>Collections</code> utility class.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you’ve learned about the Java Collections Framework and how it helps manage groups of objects in Java applications. We explored various collection types like Lists, Sets, Queues, and Maps and gained insight into some of the key characteristics and how each of these types supports them.</p>
<p>You learned about performance, synchronization, and key methods, gaining valuable insights into choosing the right data structures for your needs.</p>
<p>By understanding these concepts, you can fully utilize the Java Collections Framework, allowing you to write more efficient code and build robust applications.</p>
<p>If you found this article interesting, feel free to check out my other articles on <a target="_blank" href="https://www.freecodecamp.org/news/author/anjanbaradwaj/">freeCodeCamp</a> and connect with me on <a target="_blank" href="https://www.linkedin.com/in/abaradwaj/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Design and Develop Web APIs: Essential Guidelines for Developers ]]>
                </title>
                <description>
                    <![CDATA[ Software applications have made our lives easier and better in many ways. We use them almost daily, and some people find themselves using applications more frequently than they interact with other people. But how do applications interact with each ot... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-design-and-develop-web-apis-essential-guidelines/</link>
                <guid isPermaLink="false">6703e6a86c864c89cd8c507c</guid>
                
                    <category>
                        <![CDATA[ APIs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ API basics  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Anjan Baradwaj ]]>
                </dc:creator>
                <pubDate>Mon, 07 Oct 2024 13:48:24 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/ZM55FiQB8ig/upload/709f2a6f6de426904c95b785196f8736.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Software applications have made our lives easier and better in many ways. We use them almost daily, and some people find themselves using applications more frequently than they interact with other people.</p>
<p>But how do applications interact with each other? Well, they do it through APIs – Application Programming Interfaces. In this article, you’ll learn what APIs are. We’ll specifically focus on Web APIs and their design and development.</p>
<h2 id="heading-what-is-a-web-api">What is a Web API?</h2>
<p>Web APIs are a type of API designed to be used over the web. In other words, web-based software applications, systems, and services use Web APIs to exchange information over the internet. They send requests and receive responses, typically in formats such as JSON or XML.</p>
<p>Web APIs play a crucial role in modern software development for the following reasons:</p>
<ol>
<li><p><strong>Interoperability</strong>: APIs are technology-agnostic, meaning they allow different software systems to communicate with each other regardless of the technology stack. This enables developers to integrate various applications seamlessly.</p>
</li>
<li><p><strong>Scalability</strong>: Web APIs support modular development, enabling different components of an application to be built, debugged, and scaled independently. This greatly improves the system's scalability.</p>
</li>
<li><p><strong>Flexibility and Extensibility</strong>: By following standard practices and well-defined rules, Web APIs help applications extend their functionality. They are also flexible enough to allow developers to create dynamic applications.</p>
</li>
</ol>
<h2 id="heading-approaches-to-developing-web-apis">Approaches to Developing Web APIs</h2>
<p>Web APIs can be developed using various methods based on the requirements. Here are some commonly followed approaches:</p>
<ul>
<li><p><strong>REST</strong> – Representational State Transfer (REST) APIs use the HTTP protocol to perform operations. They operate in a stateless manner, meaning each request must include all the necessary information for the receiver to process and respond.</p>
</li>
<li><p><strong>SOAP</strong> – Simple Object Access Protocol uses XML to exchange information in a structured way.</p>
</li>
<li><p><strong>GraphQL</strong> – used for querying and manipulating APIs.</p>
</li>
<li><p><strong>gRPC</strong> – a Remote Procedure Call framework that uses HTTP/2 for transporting information.</p>
</li>
</ul>
<p>In the upcoming sections, we will explore the design and development of APIs, focusing on REST APIs as the protocol central to our discussion.</p>
<h2 id="heading-understanding-the-requirements-and-objectives">Understanding the Requirements and Objectives</h2>
<p>In any software development process, it's crucial to understand the requirements and intended use-case before starting. This helps you plan and estimate the cost, time, and other resources you’ll need for the project.</p>
<p>The same applies when building RESTful APIs. You need to determine if the applications will exchange information in a stateless manner, if the entities involved can be represented as resources, and if the services are flexible enough to work with different data formats.</p>
<h2 id="heading-defining-the-resources-and-endpoints">Defining the Resources and Endpoints</h2>
<p>REST APIs revolve around <em>resources</em>, which are entities representing the data or objects in the system. Each resource is identified by a unique URI called a <em>resource identifier</em>. These resources can be accessed and manipulated via <em>endpoints</em>, which are specific URLs that receive and process requests from the client.</p>
<p>Best practices suggest using nouns for resources in the endpoints instead of verbs that might indicate an operation on the resource.</p>
<p>Consider the following example: <code>https://api.example.com/products</code></p>
<p>The endpoint follows the best practice of using a noun for the resource (in this case, <code>products</code>). Notice how I used the plural form - products? It is also advisable to use plurals if you are working with a collection of objects.</p>
<p>However, the following endpoint <code>https://api.example.com/add-product</code> is not recommended because it uses a verb and tries to describe an action on the resource. This approach can become complicated for more complex operations.</p>
<p>Another important aspect of standard endpoint naming convention is using a hierarchical structure. This helps to clearly represent the relationship between resources.</p>
<p>For example: <code>https://api.example.com/categories/{categoryId}/products/{productId}</code>.<br>Here, we define an endpoint that maintains a clear hierarchy between the <code>category</code> and <code>product</code> resources.</p>
<h2 id="heading-using-http-methods-and-status-codes">Using HTTP Methods and Status Codes</h2>
<p>In REST APIs, <a target="_blank" href="https://www.cloudflare.com/learning/ddos/glossary/hypertext-transfer-protocol-http/">HTTP</a> is used for communication between the client and the server. HTTP has standard methods that are primarily used to perform operations on resources. Below is a list of these methods along with their purposes:</p>
<ul>
<li><p>GET – Fetch the details of the resource. These details are returned by the server in the response message body.</p>
</li>
<li><p>POST – Create a new resource. The details of the resource to be created are sent in the request message body.</p>
</li>
<li><p>PUT – Create or update a resource, depending on its availability. The details of the resource to be created or updated are sent in the request message body.</p>
</li>
<li><p>DELETE – Remove a resource.</p>
</li>
<li><p>PATCH – Partially update a resource. The changes to be made to the resource are sent in the request message body.</p>
</li>
</ul>
<p>The recommended approach to developing a well-defined REST API is to use these HTTP methods correctly for performing the corresponding CRUD (Create, Read, Update, Delete) operations on the resource. Also, you should make sure that the API responds back to the client with an appropriate HTTP status code in the response message body.</p>
<p>Status codes reflect the end result of a request. Below are some of the common HTTP status codes you can use:</p>
<ul>
<li><p>200 OK</p>
</li>
<li><p>201 Created</p>
</li>
<li><p>204 No Content</p>
</li>
<li><p>400 Bad Request</p>
</li>
<li><p>401 Unauthorized</p>
</li>
<li><p>403 Forbidden</p>
</li>
<li><p>404 Not Found</p>
</li>
<li><p>500 Internal Server Error</p>
</li>
<li><p>503 Service Unavailable</p>
</li>
<li><p>504 Gateway Timeout</p>
</li>
</ul>
<p>Use a suitable HTTP status code that accurately represents the outcome of the request your API endpoint is processing. You can also implement custom HTTP status code to describe application-specific behavior.</p>
<h2 id="heading-versioning-strategies">Versioning Strategies</h2>
<p>Over time, the API you develop will evolve, and you will make changes to it. This is where versioning strategies become important. You must ensure that the clients already using your APIs are not affected by the changes you make.</p>
<p>Maintaining different versions will make your APIs backward compatible and allow clients to use the preferred version of the API based on their needs. An excerpt from this <a target="_blank" href="https://www.postman.com/api-platform/api-versioning/">informative blog on the Postman website</a> explains when it is ideal to version your APIs:</p>
<blockquote>
<p>“You should version your API whenever you make a change that will require consumers to modify their codebase in order to continue using the API. This type of change is known as a “breaking change,” and it can be made to an API's input and output data structures, success and error feedback, and security mechanisms.“</p>
</blockquote>
<p>API versioning can be done in different ways. Here are some methods:</p>
<ul>
<li><p><strong>URI Versioning</strong>: Include the version number in the URL path. For example, <a target="_blank" href="https://api.example.com/v1/products"><code>https://api.example.com/v1/products</code></a>.</p>
</li>
<li><p><strong>Query Parameter Versioning</strong>: Specify the version number as a query parameter in the URL. For example, <a target="_blank" href="https://api.example.com/products?version=1"><code>https://api.example.com/products?version=1</code></a>.</p>
</li>
<li><p><strong>Header Versioning</strong>: Include the version number in the HTTP headers of the request. For example, using a custom header like <code>X-API-Version: 1</code>.</p>
</li>
<li><p><strong>Content Negotiation</strong>: Specify the version in the <code>Accept</code> header of the request, often using media types. For example, <code>Accept: application/vnd.example.v1+json</code>.</p>
</li>
<li><p><strong>Embedded Versioning</strong>: Embed the version number within the media type of the response. For example, <code>application/vnd.example.product-v1+json</code>.</p>
</li>
</ul>
<h2 id="heading-security-considerations">Security Considerations</h2>
<p>Another important aspect to consider when developing an API is security. Here are some key points to remember:</p>
<ol>
<li><p>Implement HTTPS to encrypt the information exchanged between the client and the server.</p>
</li>
<li><p>Implement authentication and authorization to ensure that only users with the right privileges can perform operations on the resources. Common methods include Basic authentication, Bearer or Token authentication, JWT, and OAuth 2.0. Also, implement role-based access control to manage resource access.</p>
</li>
<li><p>Implement input validation and sanitization to prevent vulnerability attacks like SQL injection and Cross-Site Scripting (XSS).</p>
</li>
<li><p>Implement rate limiting and throttling to control the number of requests a client can make to the server within a specific time frame. This helps prevent excessive load on the server.</p>
</li>
</ol>
<h2 id="heading-documentation">Documentation</h2>
<p>One key but often overlooked aspect of API development is documentation. It is crucial to document your API so users understand its features and functionalities.</p>
<p>The documentation must be comprehensive, easy to understand, and follow standard practices. Include examples of request and response bodies, HTTP status codes used, and more. You can follow the <a target="_blank" href="https://www.openapis.org/">Open API specification</a> for describing your RESTful APIs.</p>
<h2 id="heading-sorting-filtering-and-pagination-strategies">Sorting, Filtering and Pagination Strategies</h2>
<p>The API you develop might cause performance issues if it returns too many records. It's inefficient to retrieve large amounts of data and then sort or filter it.</p>
<p>To address this, you should enable sorting and filtering of records. You should also implement pagination to break down the number of records being fetched and set a limit for easier navigation and processing.</p>
<h2 id="heading-monitoring-usage-logging-and-health">Monitoring Usage, Logging, and Health</h2>
<p>It’s a good idea to log your API requests and responses to help with debugging. Monitoring API usage will help you understand the overall performance and behavior of the application. Performing regular health checks can help you take necessary action if there are any issues. All these steps will make the API more robust and reliable.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>APIs, specifically Web APIs, are essential for software applications to communicate over the internet.</p>
<p>This article explained what Web APIs are, why they’re important, and different approaches for developing them, focusing on REST APIs. You also learned about key topics like defining resources and endpoints, using standard HTTP methods and status codes, versioning strategies, security considerations, documentation, and more.</p>
<p>If you found this article interesting, feel free to check out my other articles on freeCodeCamp and connect with me on <a target="_blank" href="https://www.linkedin.com/in/abaradwaj/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Java HashMaps Work – Internal Mechanics Explained ]]>
                </title>
                <description>
                    <![CDATA[ A HashMap is one of the most commonly used data structures in Java, and it's known for its efficiency. Data in a HashMap is stored in the form of key-value pairs. In this article, I will introduce you to HashMaps in Java. We will explore the common o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-java-hashmaps-work-internal-mechanics-explained/</link>
                <guid isPermaLink="false">66b677afa502c749ffbb5c36</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hashmap ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Collection Framework ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Anjan Baradwaj ]]>
                </dc:creator>
                <pubDate>Fri, 09 Aug 2024 20:10:23 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Or_Fa550XaQ/upload/f4d40f1c8e94855d53776a3bb6179673.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A <code>HashMap</code> is one of the most commonly used data structures in Java, and it's known for its efficiency. Data in a <code>HashMap</code> is stored in the form of key-value pairs.</p>
<p>In this article, I will introduce you to <code>HashMap</code>s in Java. We will explore the common operations of <code>HashMap</code> and then delve into how it operates internally. You will gain an understanding of the hash function and how index calculation takes place. Finally, we will look at the time complexities of the operations and touch upon the behavior in a concurrent environment.</p>
<h2 id="heading-what-is-a-hashmap-in-java"><strong>What is a</strong> <code>HashMap</code> in Java?</h2>
<p>A <code>HashMap</code> implements the <code>Map</code> interface, which is part of the Java collection framework. It's based on the concept of Hashing.</p>
<p>Hashing is a technique that transforms an input of arbitrary size into a fixed-size output using a hash function. The generated output is called the hash code and is represented by an integer value in Java. Hash codes are used for efficient lookup and storage operations in a <code>HashMap</code>.</p>
<h2 id="heading-common-operations"><strong>Common Operations</strong></h2>
<p>Like we discussed above, data in a <code>HashMap</code> is stored in the form of key-value pairs. The key is a unique identifier, and each key is associated with a value.</p>
<p>Below are some common operations supported by a <code>HashMap</code>. Let's understand what these methods do with some simple code examples:</p>
<h3 id="heading-insertion"><strong>Insertion</strong></h3>
<ul>
<li><p>This method inserts a new key-value pair to the <code>HashMap</code>.</p>
</li>
<li><p>The insertion order of the key-value pairs is not maintained.</p>
</li>
<li><p>During insertion, if a key is already present, the existing value will be replaced with the new value that is passed.</p>
</li>
<li><p>You can insert only one null key into the <code>HashMap</code>, but you can have multiple null values.</p>
</li>
</ul>
<p>The method signature for this operation is given below, followed by an example:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> V <span class="hljs-title">put</span><span class="hljs-params">(K key, V value)</span></span>
</code></pre>
<pre><code class="lang-java">Map&lt;String, Integer&gt; map = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();
map.put(<span class="hljs-string">"apple"</span>, <span class="hljs-number">1</span>);
map.put(<span class="hljs-string">"banana"</span>, <span class="hljs-number">2</span>);
</code></pre>
<p>In the code above, we have a HashMap example where we add a key of type String and value of type Integer.</p>
<h3 id="heading-retrieval"><strong>Retrieval:</strong></h3>
<ul>
<li><p>Fetches the value associated with a given key.</p>
</li>
<li><p>Returns <code>null</code> if the key does not exist in the <code>HashMap</code>.</p>
</li>
</ul>
<p>The method signature for this operation is given below, followed by an example:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> V <span class="hljs-title">get</span><span class="hljs-params">(Object key)</span></span>
</code></pre>
<pre><code class="lang-java">Integer value = map.get(<span class="hljs-string">"apple"</span>); <span class="hljs-comment">// returns 1</span>
</code></pre>
<p>In the code above, we're retrieving the value associated with the key <code>apple</code>.</p>
<p>Other common operations include:</p>
<ul>
<li><p><code>remove</code>: Removes the key-value pair for the specified key. It returns <code>null</code> if the key is not found.</p>
</li>
<li><p><code>containsKey</code>: Checks if a specific key is present in the <code>HashMap</code>.</p>
</li>
<li><p><code>containsValue</code>: Checks if the specified value is present in the <code>HashMap</code>.</p>
</li>
</ul>
<h2 id="heading-internal-structure-of-a-hashmap"><strong>Internal Structure of a</strong> <code>HashMap</code></h2>
<p>Internally, a <code>HashMap</code> uses an array of buckets or bins. Each bucket is a linked list of type <code>Node</code>, which is used to represent the key-value pair of the <code>HashMap</code>.</p>
<pre><code class="lang-java"><span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span>&lt;<span class="hljs-title">K</span>, <span class="hljs-title">V</span>&gt; </span>{
    <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> hash;
    <span class="hljs-keyword">final</span> K key;
    V value;
    Node&lt;K, V&gt; next;

    Node(<span class="hljs-keyword">int</span> hash, K key, V value, Node&lt;K, V&gt; next) {
        <span class="hljs-keyword">this</span>.hash = hash;
        <span class="hljs-keyword">this</span>.key = key;
        <span class="hljs-keyword">this</span>.value = value;
        <span class="hljs-keyword">this</span>.next = next;
    }
}
</code></pre>
<p>Above, you can see the structure of the <code>Node</code> class which is used to store the key-value pairs of the <code>HashMap</code>.</p>
<p>The <code>Node</code> class has the following fields:</p>
<ul>
<li><p><code>hash</code>: Refers to the <code>hashCode</code> of the key.</p>
</li>
<li><p><code>key</code>: Refers to the key of the key-value pair.</p>
</li>
<li><p><code>value</code>: Refers to the value associated with the key.</p>
</li>
<li><p><code>next</code>: Acts as a reference to the next node.</p>
</li>
</ul>
<p>The <code>HashMap</code> is fundamentally based on a hash table implementation, and its performance depends on two key parameters: initial capacity and load factor. The <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html">original javadocs</a> of the Hash table class define these two parameters as follows:</p>
<ul>
<li><p>The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.</p>
</li>
<li><p>The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.</p>
</li>
</ul>
<p>Let's now try and understand how the basic operations, <code>put</code> and <code>get</code>, work in a <code>HashMap</code>.</p>
<h3 id="heading-hash-function"><strong>Hash Function</strong></h3>
<p>During the insertion (<code>put</code>) of a key-value pair, the <code>HashMap</code> first calculates the hash code of the key. The hash function then computes an integer for the key. Classes can use the <code>hashCode</code> method of the <code>Object</code> class or override this method and provide their own implementation. (Read about the hash code contract <a target="_blank" href="https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()">here</a>). The hash code is then XORed (eXclusive OR) with its upper 16 bits (h &gt;&gt;&gt; 16) to achieve a more uniform distribution.</p>
<p>XOR is a bitwise operation that compares two bits, resulting in 1 if the bits are different and 0 if they are the same. In this context, performing a bitwise XOR operation between the hash code and its upper 16 bits (obtained using the unsigned right shift <code>&gt;&gt;&gt;</code> operator) helps to mix the bits, leading to a more evenly distributed hash code.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">hash</span><span class="hljs-params">(Object key)</span> </span>{
    <span class="hljs-keyword">int</span> h;
    <span class="hljs-keyword">return</span> (key == <span class="hljs-keyword">null</span>) ? <span class="hljs-number">0</span> : (h = key.hashCode()) ^ (h &gt;&gt;&gt; <span class="hljs-number">16</span>);
}
</code></pre>
<p>Above, you can see the static hash method of the <code>HashMap</code> class.</p>
<p>The idea is to have a unique hash code for each key, but the hash function could produce the same hash code for different keys. This leads to a situation known as a collision. We will see how to handle collisions in the next section.</p>
<h3 id="heading-index-calculation"><strong>Index Calculation</strong></h3>
<p>Once the hash code for a key is generated, the <code>HashMap</code> calculates an index within the array of buckets to determine where the key-value pair will be stored. This is done using a bitwise AND operation, which is an efficient way to calculate the modulo when the array length is a power of two.</p>
<pre><code class="lang-java"><span class="hljs-keyword">int</span> index = (n - <span class="hljs-number">1</span>) &amp; hash;
</code></pre>
<p>Here, we're calculating the index where n is the length of the bucket array.</p>
<p>Once the index is calculated, the key is then stored at that index in the bucket array. However, if multiple keys end up having the same index, it causes a collision. In such a scenario, the <code>HashMap</code> handles it in one of two ways:</p>
<ul>
<li><p>Chaining/Linking: Each bucket in the array is a linked list of nodes. If a key already exists at a particular index and another key gets hashed to the same index, it gets appended to the list.</p>
</li>
<li><p>Treeify: If the number of nodes exceeds a certain threshold, the linked list is converted into a tree (This was introduced in Java 8).</p>
</li>
</ul>
<pre><code class="lang-java"><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> TREEIFY_THRESHOLD = <span class="hljs-number">8</span>;
</code></pre>
<p>This is the threshold that determines treeification.</p>
<p>Therefore, it is essential to have a good hash function that uniformly distributes the keys across the buckets and minimizes the chances of collisions.</p>
<p>The retrieval (<code>get</code>) and deletion (<code>remove</code>) operations work similarly to the insertion (<code>put</code>) operation. Here's how:</p>
<ul>
<li><p>Retrieval (<code>get</code>): Computes the hash code using the hash function -&gt; calculates the index using the hash code -&gt; traverses the linked list or tree to find the node with the matching key.</p>
</li>
<li><p>Deletion (<code>remove</code>): Computes the hash code using the hash function -&gt; calculates the index using the hash code -&gt; removes the node from the linked list or tree.</p>
</li>
</ul>
<h3 id="heading-time-complexity"><strong>Time Complexity</strong></h3>
<p>The basic operations of a <code>HashMap</code>, such as <code>put</code>, <code>get</code>, and <code>remove</code>, generally offer constant time performance of O(1), assuming that the keys are uniformly distributed. In cases where there is poor key distribution and many collisions occur, these operations might degrade to a linear time complexity of O(n).</p>
<p>Under treeification, where long chains of collisions are converted into balanced trees, lookup operations can improve to a more efficient logarithmic time complexity of O(log n).</p>
<h3 id="heading-synchronization"><strong>Synchronization</strong></h3>
<p>The <code>HashMap</code> implementation is not synchronized. If multiple threads access a HashMap instance concurrently and iterate over the map, and if any one of the threads performs a structural modification (such as adding or removing a key-value mapping) on the map, it leads to a <code>ConcurrentModificationException</code>.</p>
<p>To prevent this, you can create a thread-safe instance using the <code>Collections.synchronizedMap</code> method.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>In summary, understanding the internal workings of a <code>HashMap</code> is crucial for developers to make informed decisions. Knowing how a key is mapped, how collisions happen, and how they can be avoided helps you use the <code>HashMap</code> efficiently and effectively.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Creational Design Patterns in Java? Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ Design Patterns provide you with an idea or a strategy for solving commonly occurring problems. They are proven solutions that follow the best practices and help you make your code flexible, reusable, and maintainable. The design patterns are classif... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/creational-design-patterns-in-java/</link>
                <guid isPermaLink="false">66ba1ab806a331cb39bc1aa6</guid>
                
                <dc:creator>
                    <![CDATA[ Anjan Baradwaj ]]>
                </dc:creator>
                <pubDate>Fri, 26 Jul 2024 13:04:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/Creational.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Design Patterns provide you with an idea or a strategy for solving commonly occurring problems. They are proven solutions that follow the best practices and help you make your code flexible, reusable, and maintainable.</p>
<p>The design patterns are classified into three categories based on their purpose:</p>
<ul>
<li>Creational</li>
<li>Structural</li>
<li>Behavioral</li>
</ul>
<p>In this article, I will walk you through what creational design patterns are, take a look at the different types, and explore some of them using Java code examples.</p>
<p>##Creational Design Patterns</p>
<p>As the name suggests, creational design patterns deal with object creation. They provide different ways for you to create objects. Following these design patterns will ensure that the object instantiation process is flexible and highly efficient. This is achieved by making the system independent of the creation, composition, and representation of the object.</p>
<p>There are five different types of creational design patterns:</p>
<ol>
<li>Singleton</li>
<li>Factory Method</li>
<li>Abstract Factory</li>
<li>Builder</li>
<li>Prototype</li>
</ol>
<p>In the following sections, we'll talk about these design patterns by defining them, providing code examples, and explaining their potential use cases.</p>
<p>##Singleton Design Pattern</p>
<p>A singleton design pattern ensures that there is only one instance of a class throughout your application. You're allowed to create only one object of the singleton class, and any subsequent call to create another object of the same class will return the existing object reference.</p>
<p>This allows you to have a single point of access to the object across your application. Let's take a look at the code for implementing the singleton pattern:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Singleton</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Singleton instance;

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Singleton</span><span class="hljs-params">()</span> </span>{

    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Singleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
            instance = <span class="hljs-keyword">new</span> Singleton();
        }
        <span class="hljs-keyword">return</span> instance;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayMessage</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Hello, I am a Singleton instance!"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Singleton singleton = Singleton.getInstance();

        singleton.displayMessage();
    }
}
</code></pre>
<p>In the above example, you'll notice the three crucial aspects you must remember when implementing a singleton class:</p>
<ul>
<li>A private static instance</li>
<li>A private constructor</li>
<li>A public static method</li>
</ul>
<p>The private static instance is of the same type as the class itself, and it is marked static as it needs to be accessed only through the class reference and not by creating an object.</p>
<p>The constructor of the class is marked private to prevent objects of the class from being created.</p>
<p>We also have a public static method named <code>getInstance</code>, which first checks if the instance is null. If it is, then it allows a new instance of the class to be created. Otherwise, it returns the existing instance reference.</p>
<p>We created an instance of the <code>Singleton</code> class by calling the static <code>getInstance</code> method.</p>
<p>###Use Cases</p>
<p>Here are a few cases where you might use the singleton design pattern:</p>
<ul>
<li>Database connections: These operations are expensive, so to avoid the overhead of repeatedly opening and closing the connections, you can implement the singleton design pattern to reuse existing connections from the pool.</li>
<li>Logging: You can have a single instance of the logger to log the messages in your application to promote efficiency and consistency.</li>
<li>Configuration: You can have a single, centralized configuration manager for loading the settings from any source and use it across the application</li>
</ul>
<p>Note: There are a few other variations of implementing a singleton class, but we will not be exploring those in this article. Additionally, what we have seen above is a simple implementation in a single-threaded application. There are chances that you may encounter some challenges with this in a multi-threaded environment and addressing that is also beyond the scope of this article.</p>
<p>##Factory Method Design Pattern</p>
<p>In the book "<a target="_blank" href="https://www.oreilly.com/library/view/design-patterns-elements/0201633612/">Design Patterns: Elements of Reusable Object-Oriented Software</a>" the authors (referred to as the Gang of Four or GoF) define the factory method as follows:</p>
<blockquote>
<p>defines an interface for creating an object, but let subclasses decide which class to instantiate</p>
</blockquote>
<p>As the definition shows, in the factory method design pattern, an interface is provided for creating objects. Various classes implement this interface and return instances of their respective types. A factory then determines which type of object should be returned based on predefined conditions. </p>
<p>This design pattern encapsulates the instantiation logic, decouples the object creation process, making your code more flexible, and promotes extensibility. Let us take a look at the code example for better understanding:</p>
<ol>
<li>We define an interface <code>Shape</code>:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Shape</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">draw</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<ol start="2">
<li>We create concrete implementions of the <code>Shape</code> class named <code>Square</code> and <code>Circle</code>:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Square</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Shape</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">draw</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Drawing a Square"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Shape</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">draw</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Drawing a Circle"</span>);
    }
}
</code></pre>
<ol start="3">
<li>We define a <code>ShapeFactory</code> interface for creating the objects of type <code>Shape</code>:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ShapeFactory</span> </span>{
    <span class="hljs-function">Shape <span class="hljs-title">createShape</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<ol start="4">
<li>Finally, we implement concrete factories:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SquareFactory</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ShapeFactory</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> Shape <span class="hljs-title">createShape</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Square();
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CircleFactory</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">ShapeFactory</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> Shape <span class="hljs-title">createShape</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Circle();
    }
}
</code></pre>
<ol start="5">
<li>The client uses the factory to create objects of different shapes:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        ShapeFactory squareFactory = <span class="hljs-keyword">new</span> SquareFactory();
        Shape square = squareFactory.createShape();
        square.draw();

        ShapeFactory circleFactory = <span class="hljs-keyword">new</span> CircleFactory();
        Shape circle = circleFactory.createShape();
        circle.draw();
    }
}
</code></pre>
<p>This way, we can ensure that the client code is decoupled from the specific classes, as it does not need to instantiate those objects directly. This makes it easier to add new shapes.</p>
<p>###Use Cases:</p>
<ul>
<li>Database Connections: You can set up a <code>DatabaseConnectionFactory</code> in your application to connect to different types of databases (for example: MySQL, PostgreSQL, Oracle)</li>
<li>User Authentication: You can set up an <code>AuthenticationFactory</code> that supports different authentication methods (for example: OAuth, SAML, LDAP)</li>
</ul>
<p>##Abstract Factory Design Pattern</p>
<p>We will once again refer to the book "<a target="_blank" href="https://www.oreilly.com/library/view/design-patterns-elements/0201633612/">Design Patterns: Elements of Reusable Object-Oriented Software</a>" for the definition of abstract factory. It states:</p>
<blockquote>
<p>Abstract Factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.</p>
</blockquote>
<p>This means that you have a super-factory that allows you to create a group of related factories. You can think of the abstract factory design pattern as a factory of factories, providing an additional layer of abstraction over the factory method design pattern we discussed earlier. </p>
<p>Let us take an example of the abstract factory design pattern using the idea of a <code>CarFactory</code> to create different types of cars.</p>
<ol>
<li>We define a common interface for all cars named <code>Car</code>:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Car</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">drive</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<ol start="2">
<li>We create concrete implementations of the <code>Car</code> interface named <code>Sedan</code> and <code>SUV</code>:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Sedan</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Car</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">drive</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Driving a Sedan"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SUV</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Car</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">drive</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Driving an SUV"</span>);
    }
}
</code></pre>
<ol start="3">
<li>We define an interface for car factories named <code>CarFactory</code>:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">CarFactory</span> </span>{
    <span class="hljs-function">Car <span class="hljs-title">createCar</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<ol start="4">
<li>We define concrete factories named <code>SedanFactory</code> and <code>SUVFactory</code> that create <code>Sedan</code> and <code>SUV</code> cars respectively:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SedanFactory</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">CarFactory</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Car <span class="hljs-title">createCar</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Sedan();
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SUVFactory</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">CarFactory</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Car <span class="hljs-title">createCar</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> SUV();
    }
}
</code></pre>
<ol start="5">
<li>The <code>AbstractCarFactory</code> class defines an abstract class for creating different car factories:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AbstractCarFactory</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> CarFactory <span class="hljs-title">getCarFactory</span><span class="hljs-params">(String type)</span></span>;
}
</code></pre>
<ol start="6">
<li>The <code>ConcreteCarFactory</code> class implements the <code>AbstractCarFactory</code> to return the appropriate factory based on the type of the car:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConcreteCarFactory</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AbstractCarFactory</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> CarFactory <span class="hljs-title">getCarFactory</span><span class="hljs-params">(String type)</span> </span>{
        <span class="hljs-keyword">if</span> (type.equalsIgnoreCase(<span class="hljs-string">"Sedan"</span>)) {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> SedanFactory();
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (type.equalsIgnoreCase(<span class="hljs-string">"SUV"</span>)) {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> SUVFactory();
        }
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
    }
}
</code></pre>
<ol start="7">
<li>Finally, in the client code, we use the abstract factory design pattern to create <code>Sedan</code> and <code>SUV</code> cars without specifying their concrete classes:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        AbstractCarFactory carFactory = <span class="hljs-keyword">new</span> ConcreteCarFactory();

        CarFactory sedanFactory = carFactory.getCarFactory(<span class="hljs-string">"Sedan"</span>);
        Car sedan = sedanFactory.createCar();
        sedan.drive();  <span class="hljs-comment">// Output - Driving a Sedan</span>

        CarFactory suvFactory = carFactory.getCarFactory(<span class="hljs-string">"SUV"</span>);
        Car suv = suvFactory.createCar();
        suv.drive();  <span class="hljs-comment">// Output -  Driving an SUV</span>
    }
}
</code></pre>
<p>###Use Cases</p>
<ul>
<li>When you want to have a system that is independent of the creation, composition, and representation of its components.</li>
<li>When you want to configure a system with a family of related components.</li>
</ul>
<p>##Builder Design Pattern</p>
<p>The builder design pattern is another creational design pattern used to construct complex objects. You might encounter a class with many parameters required to create an instance. Some can be mandatory, while some can be optional. Using the builder design pattern, you can separate the process of creating such complex objects from their representation. </p>
<p>Let me give you an example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String firstName;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String lastName;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> age;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String address;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String phoneNumber;

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Person</span><span class="hljs-params">(PersonBuilder builder)</span> </span>{
        <span class="hljs-keyword">this</span>.firstName = builder.firstName;
        <span class="hljs-keyword">this</span>.lastName = builder.lastName;
        <span class="hljs-keyword">this</span>.age = builder.age;
        <span class="hljs-keyword">this</span>.address = builder.address;
        <span class="hljs-keyword">this</span>.phoneNumber = builder.phoneNumber;
    }

    <span class="hljs-comment">// Getters for all the parameters</span>

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Person{"</span> +
                <span class="hljs-string">"firstName='"</span> + firstName + <span class="hljs-string">'\''</span> +
                <span class="hljs-string">", lastName='"</span> + lastName + <span class="hljs-string">'\''</span> +
                <span class="hljs-string">", age="</span> + age +
                <span class="hljs-string">", address='"</span> + address + <span class="hljs-string">'\''</span> +
                <span class="hljs-string">", phoneNumber='"</span> + phoneNumber + <span class="hljs-string">'\''</span> +
                <span class="hljs-string">'}'</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PersonBuilder</span> </span>{

        <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String firstName;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String lastName;

        <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;
        <span class="hljs-keyword">private</span> String address;
        <span class="hljs-keyword">private</span> String phoneNumber;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PersonBuilder</span><span class="hljs-params">(String firstName, String lastName)</span> </span>{
            <span class="hljs-keyword">this</span>.firstName = firstName;
            <span class="hljs-keyword">this</span>.lastName = lastName;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> PersonBuilder <span class="hljs-title">age</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>{
            <span class="hljs-keyword">this</span>.age = age;
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> PersonBuilder <span class="hljs-title">address</span><span class="hljs-params">(String address)</span> </span>{
            <span class="hljs-keyword">this</span>.address = address;
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> PersonBuilder <span class="hljs-title">phoneNumber</span><span class="hljs-params">(String phoneNumber)</span> </span>{
            <span class="hljs-keyword">this</span>.phoneNumber = phoneNumber;
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> Person <span class="hljs-title">build</span><span class="hljs-params">()</span> </span>{
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Person(<span class="hljs-keyword">this</span>);
        }
    }
}
</code></pre>
<p>In the above example, we have a <code>Person</code> class that contains a few required parameters (<code>firstName</code> and <code>lastName</code>) and some optional parameters (<code>age</code>, <code>address</code>, <code>phoneNumber</code>). The constructor is also marked private so that only the <code>PersonBuilder</code> class associated with this is allowed to access it.</p>
<p>The <code>PersonBuilder</code> class has the same properties as the <code>Person</code> class. The required parameters are set via its constructor. It also has suitable methods for setting the optional parameters that return <code>this</code> and enable method chaining. </p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Person person = <span class="hljs-keyword">new</span> Person.PersonBuilder(<span class="hljs-string">"Mikel"</span>, <span class="hljs-string">"Arteta"</span>)
                .age(<span class="hljs-number">42</span>)
                .address(<span class="hljs-string">"1 North London"</span>)
                .phoneNumber(<span class="hljs-string">"111-1234"</span>)
                .build();

        System.out.println(person);
    }
}
</code></pre>
<p>To use this, we created a <code>PersonBuilder</code> instance with the required parameters. We set the optional parameters using method chaining. Finally, we called the <code>build()</code> method to create a <code>Person</code> object.</p>
<p>###Use Cases:</p>
<ul>
<li>You can use the builder design pattern when you want to construct a complex object of a class that has a combination of mandatory and optional properties.</li>
<li>You can use this when your class has many parameters and is inefficient to have different constructors for each combination of the parameters.</li>
<li>You can use it to provide different representations of the same object to the client.</li>
</ul>
<p>##Prototype Design Pattern</p>
<p>There could be a scenario where you want to create an object that is similar to an existing object. The prtotype design pattern allows you to achieve this. In this pattern, the existing object is known as the prototype, and the idea is that it is much more efficient to copy an existing object than to create a new one from scratch.</p>
<p>It might not be possible for you to create an exact copy of the prototype because some fields of that object might be marked as private. This can be overcome by using the clone method approach. We create a common interface that includes only a clone method, and all classes that support the cloning of their objects implement this interface. Let us take a look at the code example for this:</p>
<ol>
<li>We create a <code>Prototype</code> interface that defines a <code>clone</code> method that classes must implement:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Prototype</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Cloneable</span> </span>{
    <span class="hljs-function">Prototype <span class="hljs-title">clone</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<ol start="2">
<li>We create <code>Circle</code> and <code>Rectangle</code> which are concrete classes that implement the <code>Prototype</code> interface:</li>
</ol>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Prototype</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> radius;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Circle</span><span class="hljs-params">(<span class="hljs-keyword">int</span> radius)</span> </span>{
        <span class="hljs-keyword">this</span>.radius = radius;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getRadius</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> radius;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setRadius</span><span class="hljs-params">(<span class="hljs-keyword">int</span> radius)</span> </span>{
        <span class="hljs-keyword">this</span>.radius = radius;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Prototype <span class="hljs-title">clone</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Circle(<span class="hljs-keyword">this</span>.radius);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Circle with radius: "</span> + radius;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rectangle</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Prototype</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> width;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> height;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Rectangle</span><span class="hljs-params">(<span class="hljs-keyword">int</span> width, <span class="hljs-keyword">int</span> height)</span> </span>{
        <span class="hljs-keyword">this</span>.width = width;
        <span class="hljs-keyword">this</span>.height = height;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getWidth</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> width;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setWidth</span><span class="hljs-params">(<span class="hljs-keyword">int</span> width)</span> </span>{
        <span class="hljs-keyword">this</span>.width = width;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getHeight</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> height;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setHeight</span><span class="hljs-params">(<span class="hljs-keyword">int</span> height)</span> </span>{
        <span class="hljs-keyword">this</span>.height = height;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Prototype <span class="hljs-title">clone</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Rectangle(<span class="hljs-keyword">this</span>.width, <span class="hljs-keyword">this</span>.height);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Rectangle with width: "</span> + width + <span class="hljs-string">" and height: "</span> + height;
    }
}
</code></pre>
<ol start="3">
<li>In the client code, we create the original objects (<code>originalCircle</code> and <code>originalRectangle</code>) and then we clone them to create new instances (<code>clonedCircle</code> and <code>clonedRectangle</code>)</li>
</ol>
<p>Note that the cloned instances can be modified independently of the original objects.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Circle originalCircle = <span class="hljs-keyword">new</span> Circle(<span class="hljs-number">10</span>);
        Circle clonedCircle = (Circle) originalCircle.clone();
        clonedCircle.setRadius(<span class="hljs-number">20</span>);

        System.out.println(originalCircle);  
        System.out.println(clonedCircle);    

        Rectangle originalRectangle = <span class="hljs-keyword">new</span> Rectangle(<span class="hljs-number">15</span>, <span class="hljs-number">25</span>);
        Rectangle clonedRectangle = (Rectangle) originalRectangle.clone();
        clonedRectangle.setWidth(<span class="hljs-number">30</span>);
        clonedRectangle.setHeight(<span class="hljs-number">50</span>);

        System.out.println(originalRectangle);  
        System.out.println(clonedRectangle);    
    }
}
</code></pre>
<p>###Use Cases</p>
<ul>
<li>Follow the prototype design pattern when the object you want to create involves a complex construction process.</li>
<li>Use it when the object initialization is costly and involves a lot of expensive resources.</li>
</ul>
<p>##Conclusion</p>
<p>In this article, we explored the creational design patterns and delved into code examples and use cases. Understanding these patterns and their application will help you make your code more extensible and maintainable.</p>
<p>Connect with me on <a target="_blank" href="https://www.linkedin.com/in/abaradwaj/">LinkedIn</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Generics in Java – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ In your Java program, you might have encountered the dreaded ClassCastException at runtime while working with different types of objects such as Integer, String, and so on. This error is mostly caused by casting an object to the wrong data type.  In ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/generics-in-java/</link>
                <guid isPermaLink="false">66ba1abbf1ac6be9964fe743</guid>
                
                    <category>
                        <![CDATA[ generics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Anjan Baradwaj ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jul 2024 18:57:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/safety.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In your Java program, you might have encountered the dreaded <code>ClassCastException</code> at runtime while working with different types of objects such as Integer, String, and so on. This error is mostly caused by casting an object to the wrong data type. </p>
<p>In this article, you'll learn about generics and see how they can help address this problem.</p>
<p>##Why Do We Need Generics?</p>
<p>Let's begin with a simple example. We will first add different types of objects to an <code>ArrayList</code>. Next, we will try to retrieve them and print their values.</p>
<pre><code class="lang-java">List list = <span class="hljs-keyword">new</span> ArrayList();

list.add(<span class="hljs-string">"Hello"</span>);

String str = (String) list.get(<span class="hljs-number">0</span>);

System.out.println(<span class="hljs-string">"String: "</span> + str);
</code></pre>
<p>As you can see, we have added a <code>String</code> object to the <code>ArrayList</code>. Since we are the ones who have written the code, we know what type of object the element represents, but, the compiler does not know that. So, when we attempt to retrieve the value from the list, we get back an <code>Object</code> and we have to perform an explicit casting.</p>
<pre><code class="lang-java">list.add(<span class="hljs-number">123</span>);

String number = (String) list.get(<span class="hljs-number">1</span>);

System.out.println(<span class="hljs-string">"Number: "</span> + number);
</code></pre>
<p>If we add an <code>Integer</code> to the same list and try to fetch the value, we will get a <code>ClassCastException</code> because an Integer object cannot be cast to a String.</p>
<p>By using Generics, we can solve both problems discussed above. Let's see how.</p>
<p>First, we need to use the diamond operator and narrow the type of object held in this list. We need to mention the object type explicitly within the diamond operator. This will enforce a compile-time check, so you no longer have to perform explicit casting. You will also be able to eliminate the <code>ClassCastException</code>.</p>
<pre><code class="lang-java">List&lt;String&gt; list = <span class="hljs-keyword">new</span> ArrayList();

list.add(<span class="hljs-string">"Hello"</span>);

String str = list.get(<span class="hljs-number">0</span>); <span class="hljs-comment">// No need for explicit casting</span>

System.out.println(<span class="hljs-string">"String: "</span> + str);

list.add(<span class="hljs-number">123</span>); <span class="hljs-comment">// Throws compile-time error</span>
</code></pre>
<p>##Naming Conventions for Type Parameters</p>
<p>In the previous example, you saw that the use of <code>List&lt;String&gt;</code> narrowed the type of the object that the list could hold. Check out the following example of a <code>Box</code> class and how it works with different types of data.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Box</span>&lt;<span class="hljs-title">T</span>&gt; </span>{
    <span class="hljs-keyword">private</span> T value;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setValue</span><span class="hljs-params">(T value)</span> </span>{
        <span class="hljs-keyword">this</span>.value = value;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">getValue</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> value;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Box&lt;String&gt; stringBox = <span class="hljs-keyword">new</span> Box&lt;&gt;();
        stringBox.setValue(<span class="hljs-string">"Hello, world!"</span>);
        System.out.println(stringBox.getValue());

        Box&lt;Integer&gt; integerBox = <span class="hljs-keyword">new</span> Box&lt;&gt;();
        integerBox.setValue(<span class="hljs-number">123</span>);
        System.out.println(integerBox.getValue());
    }
}
</code></pre>
<p>Note how the <code>Box&lt;T&gt;</code> class is declared. Here, the <code>T</code> is a type parameter, indicating that the <code>Box</code> class can work with any object of that type. The same is illustrated in the main method where an instance of <code>Box&lt;String&gt;</code> and <code>Box&lt;Integer&gt;</code> are both allowed to be created, thus ensuring type safety.</p>
<p>As per the <a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/generics/types.html">official documentation</a>:</p>
<blockquote>
<p>By convention, type parameter names are single, uppercase letters.   </p>
<p>The most commonly used type parameter names are:  </p>
<p>E - Element (used extensively by the Java Collections Framework)<br>K - Key<br>N - Number<br>T - Type<br>V - Value<br>S,U,V etc. - 2nd, 3rd, 4th types</p>
</blockquote>
<p>Let's take a look at how we can write a generic method. Below is the convention:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> &lt;T&gt; <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printArray</span><span class="hljs-params">(T[] inputArr)</span> </span>{
    <span class="hljs-keyword">for</span> (T element : inputArr) {
        System.out.print(element + <span class="hljs-string">" "</span>);
    }
    System.out.println();
}
</code></pre>
<p>Here, we take an array of any type and print its elements. Note that you need to specify the generic type parameter <code>T</code> in the angle brackets <code>&lt;&gt;</code> before the return type of the method. The method body iterates over the array that we have passed as a parameter, of any type <code>T</code>, and prints each element.</p>
<pre><code class="lang-java"> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Create different arrays of type Integer, Double and Character</span>
        Integer[] intArr = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>};
        Double[] doubleArr = {<span class="hljs-number">1.1</span>, <span class="hljs-number">2.2</span>, <span class="hljs-number">3.3</span>, <span class="hljs-number">4.4</span>, <span class="hljs-number">5.5</span>};
        Character[] charArr = {<span class="hljs-string">'H'</span>, <span class="hljs-string">'E'</span>, <span class="hljs-string">'L'</span>, <span class="hljs-string">'L'</span>, <span class="hljs-string">'O'</span>};

        System.out.println(<span class="hljs-string">"Integer array contains:"</span>);
        printArray(intArr);   <span class="hljs-comment">// pass an Integer array</span>

        System.out.println(<span class="hljs-string">"Double array contains:"</span>);
        printArray(doubleArr);   <span class="hljs-comment">// pass a Double array</span>

        System.out.println(<span class="hljs-string">"Character array contains:"</span>);
        printArray(charArr);   <span class="hljs-comment">// pass a Character array</span>
    }
</code></pre>
<p>We can call this generic method by passing different types of arrays (<code>Integer</code>, <code>Double</code>, <code>Character</code>) and you will see that your program will print the elements of each of these arrays.</p>
<p>##Restrictions on Generics</p>
<p>In Generics, we use bounds to restrict the types that a generic class, interface, or method can accept. There are two types:</p>
<p>####1. Upper Bounds
This is used to restrict the generic type to an upper limit. To define an upper bound, you use the <code>extends</code> keyword. By specifying an upper bound, you ensure that the class, interface, or method accepts the specified type and all of its subclasses.</p>
<p>The syntax would be as follows: <code>&lt;T extends SuperClass&gt;</code>.</p>
<p>If you consider the same <code>Box</code> class that we used previously, it can be modified as below:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Box</span>&lt;<span class="hljs-title">T</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Number</span>&gt; </span>{
    <span class="hljs-keyword">private</span> T value;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setValue</span><span class="hljs-params">(T value)</span> </span>{
        <span class="hljs-keyword">this</span>.value = value;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">getValue</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> value;
    }
}
</code></pre>
<p>In this example, T can be any type that extends <code>Number</code>, such as <code>Integer</code>, <code>Double</code>, or <code>Float</code>.</p>
<p>####2. Lower Bounds
This is used to restrict the generic type to a lower limit. To define a lower bound, you use the <code>super</code> keyword. By specifying a lower bound, you ensure that the class, interface, or method accepts the specified type and all of its superclasses.</p>
<p>The syntax would be as follows: <code>&lt;T super SubClass&gt;</code>.</p>
<p>To illustrate the use of lower bounds, let us take a look at the following example:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printList</span><span class="hljs-params">(List&lt;? <span class="hljs-keyword">super</span> Integer&gt; list)</span> </span>{
    <span class="hljs-keyword">for</span> (Object element : list) {
        System.out.print(element + <span class="hljs-string">" "</span>);
    }
    System.out.println();
}
</code></pre>
<p>The usage of a lower bound <code>&lt;? super Integer&gt;</code> ensures that you can pass the specified type and all of its superclasses, which in this case would be a list of <code>Integer</code>, <code>Number</code>, or <code>Object</code> to the method <code>printList</code>.</p>
<p>##What are Wildcards?</p>
<p>The <code>?</code> that you saw in the previous example is called a Wildcard. You can use them to refer to an unknown type. </p>
<p>You can use a wildcard with an upper bound, in which case it would look something like this: <code>&lt;? extends Number&gt;</code>. It can also be used with a lower bound, such as <code>&lt;? super Integer&gt;</code>.</p>
<p>##Type Erasure </p>
<p>The generic type that we use in our class, interface, or method is only available at compile time and it is removed at run-time. This is done to ensure backward compatibility, as the older versions of Java (before Java 1.5) do not support it.</p>
<p>The compiler makes use of the generic type information that is available to it to ensure type safety. In the process of type erasure:</p>
<ul>
<li>If the type is unbounded, then the parameters get replaced with their bounds or <code>Object</code> type</li>
<li>If the type is bounded, then the parameters get replaced by the first bound, and the generic type information will be removed after compilation</li>
</ul>
<p>If we take a look at the <code>Box</code> class example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Box</span>&lt;<span class="hljs-title">T</span>&gt; </span>{
    <span class="hljs-keyword">private</span> T value;
    <span class="hljs-comment">//getters and setters</span>
 }
</code></pre>
<p>The above code will become this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Box</span> </span>{
    <span class="hljs-keyword">private</span> Object value;
    <span class="hljs-comment">//getters and setters</span>
 }
</code></pre>
<p>##Conclusion</p>
<p>In this article, we explored the concept of generics in Java and how you can use them, with some basic examples. Understanding and using generics enhances type safety in your program. They also eliminate the need for explicit casting and make your code reusable and maintainable.</p>
<p>Let's connect on <a target="_blank" href="https://www.linkedin.com/in/abaradwaj/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are the SOLID Principles in Java? Explained With Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ In this article, you'll learn about the SOLID principles. You'll gain an understanding of each principle along with Java code examples. SOLID principles are a set of five design principles used in object-oriented programming. Adhering to these princi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/introduction-to-solid-principles/</link>
                <guid isPermaLink="false">66ba1abe4067550ef7868690</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ solid ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Anjan Baradwaj ]]>
                </dc:creator>
                <pubDate>Mon, 24 Jun 2024 15:45:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/kozjat-mlsSgJ6LiP4-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, you'll learn about the SOLID principles. You'll gain an understanding of each principle along with Java code examples.</p>
<p>SOLID principles are a set of five design principles used in object-oriented programming. Adhering to these principles will help you develop robust software. They will make your code more efficient, readable, and maintainable.</p>
<p>SOLID is an acronym that stands for:</p>
<ul>
<li>Single Responsibility Principle</li>
<li>Open/Closed Principle</li>
<li>Liskov Substitution Principle</li>
<li>Interface Segregation Principle</li>
<li>Dependency Inversion Principle</li>
</ul>
<h2 id="heading-single-responsibility-principle">Single Responsibility Principle</h2>
<p>The single responsibilty principle states that every class must have a single, focused responsibility, a single reason to change.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span></span>{
  <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDesignation</span><span class="hljs-params">(<span class="hljs-keyword">int</span> employeeID)</span></span>{ <span class="hljs-comment">// }</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateSalary</span><span class="hljs-params">(<span class="hljs-keyword">int</span> employeeID)</span></span>{ <span class="hljs-comment">// }</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sendMail</span><span class="hljs-params">()</span></span>{ <span class="hljs-comment">// }</span>
}
</code></pre>
<p>In the above example, the <code>Employee</code> class has a few employee class-specific behaviors like <code>getDesignation</code> &amp; <code>updateSalary</code>. </p>
<p>Additionally, it also has another method named <code>sendMail</code> which deviates from the responsibility of the <code>Employee</code> class. </p>
<p>This behavior is not specific to this class, and having it violates the single responsibility principle. To overcome this, you can move the <code>sendMail</code> method to a separate class.</p>
<p>Here's how:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span></span>{
  <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDesignation</span><span class="hljs-params">(<span class="hljs-keyword">int</span> employeeID)</span></span>{ <span class="hljs-comment">// }</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateSalary</span><span class="hljs-params">(<span class="hljs-keyword">int</span> employeeID)</span></span>{ <span class="hljs-comment">// }</span>
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NotificationService</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sendMail</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">// }</span>
}
</code></pre>
<h2 id="heading-openclosed-principle">Open/Closed Principle</h2>
<p>According to the open/closed priniciple, components must be open for extension, but, closed for modification. To understand this principle, let us take an example of a class that calculates the area of a shape.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> class <span class="hljs-title">AreaCalculator</span><span class="hljs-params">()</span></span>{
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">area</span><span class="hljs-params">(Shape shape)</span></span>{
    <span class="hljs-keyword">double</span> areaOfShape;
    <span class="hljs-keyword">if</span>(shape <span class="hljs-keyword">instanceof</span> Square){
        <span class="hljs-comment">// calculate the area of Square</span>
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(shape <span class="hljs-keyword">instanceof</span> Circle){
        <span class="hljs-comment">// calculate the area of Circle</span>
    }
    <span class="hljs-keyword">return</span> areaOfShape;
  }
</code></pre>
<p>The problem with the above example is that if there is a new instance of type <code>Shape</code> for which you need to calculate the area in the future, you have to modify the above class by adding another conditional <code>else-if</code> block. You will end up doing this for every new object of the <code>Shape</code> type.</p>
<p>To overcome this, you can create an interface and have each <code>Shape</code> implement this interface. Then, each class can provide its own implementation for calculating the area. This will make your program easily extensible in the future. </p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">IAreaCalculator</span>()</span>{
  <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">area</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Square</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">IAreaCalculator</span></span>{
  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">area</span><span class="hljs-params">()</span></span>{
    System.out.println(<span class="hljs-string">"Calculating area for Square"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0.0</span>;
   }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">IAreaCalculator</span></span>{
  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">area</span><span class="hljs-params">()</span></span>{
    System.out.println(<span class="hljs-string">"Calculating area for Circle"</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">0.0</span>;
   }
}
</code></pre>
<h2 id="heading-liskov-substitution-principle">Liskov Substitution Principle</h2>
<p>The Liskov substitution principle states that you must be able to replace a superclass object with a subclass object without affecting the correctness of the program.</p>
<pre><code class="lang-java"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bird</span></span>{
   <span class="hljs-function"><span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fly</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Eagle</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Bird</span> </span>{
   <span class="hljs-meta">@Override</span>
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fly</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">// some implementation }</span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Ostrich</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Bird</span> </span>{
   <span class="hljs-meta">@Override</span>
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fly</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">// dummy implementation }</span>
}
</code></pre>
<p>In the above example, the <code>Eagle</code> class and the <code>Ostrich</code> class both extend the <code>Bird</code> class and override the <code>fly()</code> method. However, the <code>Ostrich</code> class is forced to provide a dummy implementation because it cannot fly, and therefore it does not behave the same way if we replace the <code>Bird</code> class object with it. </p>
<p>This violates the Liskov substitution principle. To address this, we can create a separate class for birds that can fly and have the <code>Eagle</code> extend it, while other birds can extend a different class, which will not include any <code>fly</code> behavior.</p>
<pre><code class="lang-java"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FlyingBird</span></span>{
   <span class="hljs-function"><span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fly</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NonFlyingBird</span></span>{
   <span class="hljs-function"><span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Eagle</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">FlyingBird</span> </span>{
   <span class="hljs-meta">@Override</span>
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fly</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">// some implementation }</span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Ostrich</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">NonFlyingBird</span> </span>{
   <span class="hljs-meta">@Override</span>
   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">// some implementation }</span>
}
</code></pre>
<h2 id="heading-interface-segregation-principle">Interface Segregation Principle</h2>
<p>According to the interface segregation principle, you should build small, focused interfaces that do not force the client to implement behavior they do not need.</p>
<p>A straightforward example would be to have an interface that calculates both the area and volume of a shape.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">IShapeAreaCalculator</span>()</span>{
  <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">calculateArea</span><span class="hljs-params">()</span></span>;
  <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">calculateVolume</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Square</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">IShapeAreaCalculator</span></span>{
  <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">calculateArea</span><span class="hljs-params">()</span></span>{ <span class="hljs-comment">// calculate the area }</span>
  <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">calculateVolume</span><span class="hljs-params">()</span></span>{ <span class="hljs-comment">// dummy implementation }</span>
}
</code></pre>
<p>The issue with this is that if a <code>Square</code> shape implements this, then it is forced to implement the <code>calculateVolume()</code> method, which it does not need. </p>
<p>On the other hand, a <code>Cube</code> can implement both. To overcome this, we can segregate the interface and have two separate interfaces: one for calculating the area and another for calculating the volume. This will allow individual shapes to decide what to implement.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">IAreaCalculator</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">calculateArea</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">IVolumeCalculator</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">double</span> <span class="hljs-title">calculateVolume</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Square</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">IAreaCalculator</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">calculateArea</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">// calculate the area }</span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cube</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">IAreaCalculator</span>, <span class="hljs-title">IVolumeCalculator</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">calculateArea</span><span class="hljs-params">()</span> </span>{ <span class="hljs-comment">// calculate the area }</span>

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">calculateVolume</span><span class="hljs-params">()</span> </span>{<span class="hljs-comment">// calculate the volume }</span>
}
</code></pre>
<h2 id="heading-dependency-inversion-principle">Dependency Inversion Principle</h2>
<p>In the dependency inversion principle, high-level modules should not depend on low-level modules. In other words, you must follow abstraction and ensure loose coupling</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Notification</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">notify</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailNotification</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Notification</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">notify</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Sending notification via email"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span> </span>{
    <span class="hljs-keyword">private</span> EmailNotification emailNotification; 
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Employee</span><span class="hljs-params">(EmailNotification emailNotification)</span> </span>{
        <span class="hljs-keyword">this</span>.emailNotification = emailNotification;
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">notifyUser</span><span class="hljs-params">()</span> </span>{
        emailNotification.notify();
    }
}
</code></pre>
<p>In the given example, the <code>Employee</code> class depends directly on the <code>EmailNotification</code> class, which is a low-level module. This violates the  dependency inversion principle.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Notification</span></span>{
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">notify</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span></span>{
  <span class="hljs-keyword">private</span> Notification notification;
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Employee</span><span class="hljs-params">(Notification notification)</span></span>{
      <span class="hljs-keyword">this</span>.notification = notification;
  }
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">notifyUser</span><span class="hljs-params">()</span></span>{
    notification.notify();
  }
 }

 <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EmailNotification</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Notification</span></span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">notify</span><span class="hljs-params">()</span></span>{
        <span class="hljs-comment">//implement notification via email </span>
    }
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String [] args)</span></span>{
    Notification notification = <span class="hljs-keyword">new</span> EmailNotification();
    Employee employee = <span class="hljs-keyword">new</span> Employee(notification);
    employee.notifyUser();
 }
</code></pre>
<p>In the above example, we have ensured loose coupling. <code>Employee</code> is not dependent on any concrete implementation, rather, it depends only on the abstraction (notification interface). </p>
<p>If we need to change the notification mode, we can create a new implementation and pass it to the <code>Employee</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, we've covered the essence of SOLID principles through straightforward examples in this article. </p>
<p>These principles form the building blocks for developing applications that are highly extensible and reusable.</p>
<p>Let's connect on <a target="_blank" href="https://www.linkedin.com/in/abaradwaj/">LinkedIn</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Guide to Object-Oriented Programming Principles ]]>
                </title>
                <description>
                    <![CDATA[ A programming language is generally classified based on its support for one or more paradigms.  Object-oriented programming is one such paradigm, where the code is organized as objects.  It is used to develop desktop and mobile applications or more c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-guide-to-object-oriented-programming-principles/</link>
                <guid isPermaLink="false">66ba1ab52ab35c1de21292f8</guid>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Anjan Baradwaj ]]>
                </dc:creator>
                <pubDate>Tue, 18 Jun 2024 09:13:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/oop-principles.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A programming language is generally classified based on its support for one or more paradigms. </p>
<p>Object-oriented programming is one such paradigm, where the code is organized as objects. </p>
<p>It is used to develop desktop and mobile applications or more complex web or enterprise applications. </p>
<p>Using object-oriented programming, you can build modular and scalable software that is easy to maintain.</p>
<p>In this article, you will learn about the principles of object-oriented Programming that lay the foundation for building robust systems. </p>
<p>We will use Java as the programming language for the examples provided below.</p>
<h2 id="heading-what-is-object-oriented-programming">What is Object-Oriented Programming?</h2>
<p>Object-Oriented Programming is a programming methodology that models real-world entities in the form of objects. </p>
<p>These objects are instances of classes. </p>
<p>A class can be thought of as a blueprint and each class can contain fields, which define the attributes of the object, and methods, which describe the object's behavior. Each class can be developed, tested, and debugged independently.</p>
<p>Now that you have an understanding of the basic definition of object-oriented programming, let us jump right in and learn about its core principles.</p>
<p>There are four core principles, or pillars, in the object-oriented Programming paradigm. They are:</p>
<ul>
<li>Abstraction</li>
<li>Encapsulation</li>
<li>Inheritance</li>
<li>Polymorphism</li>
</ul>
<p>What do they mean? Let us explore further with a simple explanation followed by an example for each of them in the following sections.</p>
<h2 id="heading-what-is-abstraction">What is Abstraction?</h2>
<p>Abstraction is defined as the concept of hiding the details of implementation and exposing only the necessary functionalities of the object to the user. </p>
<p>The keywords that you need to keep in mind here are: 'Implementation hiding'. </p>
<p>Abstraction in Java can be achieved through Interfaces and Abstract classes.</p>
<pre><code class="lang-java"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Bark"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Dog myDog = <span class="hljs-keyword">new</span> Dog();
        myDog.makeSomeNoise(); <span class="hljs-comment">// Output - Bark</span>
    }
}
</code></pre>
<p>In the above example, abstraction is achieved with the help of an abstract class named <code>Animal</code>. </p>
<p>Here, only the necessary functionality of the class is exposed via the <code>makeSomeNoise()</code> method. </p>
<p>The details of implementation are hidden in the abstract class and they are only provided in the concrete class <code>Dog</code>, which extends the <code>Animal</code> class. </p>
<p>Note that you will learn more about the <code>extends</code> keyword while we discuss Inheritance.</p>
<h2 id="heading-what-is-encapsulation">What is Encapsulation?</h2>
<p>Encapsulation refers to the concept of encapsulating or wrapping up the member variables (data) and the methods (behavior) of an object into a single unit, such as a class. </p>
<p>The internal information of the object is hidden so that we can prevent unintended modifications and allow only controlled access. The keywords that you need to keep in mind here are: 'Information hiding'.</p>
<p>Encapsulation in Java is achieved through access modifiers. We mark the fields as <code>private</code> and make them accessible via public setter and getter methods.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Person</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> age)</span> </span>{
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-keyword">this</span>.age = age;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
        <span class="hljs-keyword">this</span>.name = name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> age;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>{
        <span class="hljs-keyword">this</span>.age = age;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Name: "</span> + name + <span class="hljs-string">", Age: "</span> + age);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Person person = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Raj"</span>, <span class="hljs-number">30</span>);
        person.display(); <span class="hljs-comment">// Output - Name: Raj, Age: 30</span>

        person.setName(<span class="hljs-string">"Kumar"</span>);
        person.setAge(<span class="hljs-number">25</span>);
        person.display(); <span class="hljs-comment">// Output - Name: Kumar, Age: 25</span>
    }
}
</code></pre>
<p>In the above example, the fields and methods are encapsulated within a class named <code>Person</code>. </p>
<p>You declare the fields <code>name</code> and <code>age</code> as <code>private</code> and provide public setter and getter methods <code>getName()</code>, <code>setName()</code>, <code>getAge()</code>, and <code>setAge()</code> to modify the values as needed. </p>
<h2 id="heading-what-is-inheritance">What is Inheritance?</h2>
<p>Inheritance establishes a hierarchical relationship between two classes. </p>
<p>In this concept, one class inherits the fields (properties) and methods (behavior) of another class, while having properties and behavior of its own. </p>
<p>The class that inherits from another is called a subclass, derived class, or child class. The class from which the subclass inherits is known as the superclass, base class, or parent class. </p>
<p>In Java, inheritance is achieved using the <code>extends</code> keyword.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span></span>{
        System.out.println(<span class="hljs-string">"Make some animal noise"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Bark"</span>);
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span></span>{
        System.out.println(<span class="hljs-string">"Play with ball"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Dog myDog = <span class="hljs-keyword">new</span> Dog();
        myDog.makeSomeNoise(); <span class="hljs-comment">// Output - Bark</span>
        myDog.doSomething(); <span class="hljs-comment">// Output - Play with ball</span>
    }
}
</code></pre>
<p>In the above example, the <code>extends</code> keyword indicates that the <code>Dog</code> class is the subclass of the <code>Animal</code> class. </p>
<p>The <code>Dog</code> class inherits the <code>makeSomeNoise()</code> method from the <code>Animal</code> class. This allows the <code>Dog</code> class to reuse the method and provide its own implementation without having to rewrite it completely. </p>
<p>You can also note that the <code>Dog</code> class has its own behavior through the <code>doSomething()</code> method. </p>
<p>Inheritance defines an "IS-A" relationship between the two classes. In our example, Dog IS-A Animal.</p>
<p>Note that Java supports multi-level inheritance. For example, <code>class Labrador</code> inherits from <code>class Dog</code>, which in turn inherits from <code>class Animal</code>. However, it does not support multiple inheritance. That is, a class is not allowed to inherit from two or more parent classes.</p>
<h2 id="heading-what-is-polymorphism">What is Polymorphism?</h2>
<p>Poly (many), morph (forms). </p>
<p>Polymorphism defines the capability of an object to be represented in different forms. </p>
<p>In Java, polymorphism can be categorized into two types: compile-time polymorphism and runtime polymorphism.</p>
<p>Compile-time polymorphism is achieved through method overloading – multiple methods have the same name but different type or number of parameters.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MathOperation</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
        <span class="hljs-keyword">return</span> a + b;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b, <span class="hljs-keyword">int</span> c)</span> </span>{
        <span class="hljs-keyword">return</span> a + b + c;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        MathOperation math = <span class="hljs-keyword">new</span> MathOperation();
        System.out.println(math.add(<span class="hljs-number">95</span>, <span class="hljs-number">5</span>));       <span class="hljs-comment">// Output - 100</span>
        System.out.println(math.add(<span class="hljs-number">75</span>, <span class="hljs-number">5</span>, <span class="hljs-number">20</span>));   <span class="hljs-comment">// Output - 100</span>
    }
}
</code></pre>
<p>In the above example, we have overloaded the <code>add()</code> method. There are two methods with the same name <code>add</code> but they have different number of parameters. </p>
<p>During compilation, based on the number of parameters passed to the method, the appropriate call is made.</p>
<p>Runtime polymorphism is achieved through method overriding – a subclass has a method with the same name and same set of parameters as that of its superclass method. However, it provides its own implementation of the method. </p>
<p>Here, the method resolution happens at runtime.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Make some animal noise"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Barks"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Meows"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Animal myAnimal; 

        myAnimal = <span class="hljs-keyword">new</span> Dog(); 
        myAnimal.makeSomeNoise(); <span class="hljs-comment">// Output - Barks</span>

        myAnimal = <span class="hljs-keyword">new</span> Cat(); 
        myAnimal.makeSomeNoise(); <span class="hljs-comment">// Output - Meows</span>
    }
}
</code></pre>
<p>In the above example, the <code>makeSomeNoise()</code> method of the <code>Animal</code> class is overridden by the <code>Dog</code> and <code>Cat</code> subclasses and they provide their own implementation of this method. </p>
<p>During object creation, the <code>Animal</code> variable holds a <code>Dog</code> or <code>Cat</code> object and when the <code>makeSomeNoise()</code> method is called, the appropriate overridden method is called based on the actual object type.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we explored the fundamental principles of Object-Oriented Programming (OOP). </p>
<p>Familiarity with these concepts is crucial for building robust, maintainable, and scalable software systems.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
