<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nimasha Madhushani on Medium]]></title>
        <description><![CDATA[Stories by Nimasha Madhushani on Medium]]></description>
        <link>https://medium.com/@nimashamadhushani19?source=rss-59081e8b5c9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oYmqSoQVX08E8WnnEkLfWw.jpeg</url>
            <title>Stories by Nimasha Madhushani on Medium</title>
            <link>https://medium.com/@nimashamadhushani19?source=rss-59081e8b5c9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 11:11:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nimashamadhushani19/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[HashSet & LinkedHashSet in the Java Collections Framework]]></title>
            <link>https://medium.com/linkit-intecs/hashset-linkedhashset-in-the-java-collections-framework-d95174961f4f?source=rss-59081e8b5c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d95174961f4f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[blogging]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Nimasha Madhushani]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 21:55:17 GMT</pubDate>
            <atom:updated>2024-06-23T17:35:07.940Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*fMSEijLQfcmkc0CV0NDzVg.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>Hey Guys, I hope you have already read the first 3 articles of the Java Collections Framework Article Series. If not, this is for you.</p><ul><li>Part 1 — <a href="https://medium.com/@nimashamadhushani19/java-collection-framework-360e88b11906">Java Collections Framework</a></li><li>Part 2 — <a href="https://medium.com/@nimashamadhushani19/interfaces-classes-in-java-collections-framework-499d6ae25ba3">Interfaces &amp; Classes in Java Collections Framework</a></li><li>Part 3 — <a href="https://medium.com/@nimashamadhushani19/methods-in-classes-interfaces-of-collections-framework-6e21a97851a4">ArrayList &amp; LinkedList in the Java Collections Framework</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*nJeoizGJ7hWbG3AhcX_-1w.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><h3>HashSets</h3><p><strong>🟣Concepts in HashSets,</strong></p><ul><li>Duplicate elements are not allowed.</li><li>Insertion order is not preserved. Elements are in a random order. So, there is no index concept.</li><li>Insert element using the concept called HashCode. It helps to fetch elements in a HashSet faster.</li><li>Heterogeneous data will be supported.</li><li>Null values are supported. So, we can add null values in the HashSets.</li></ul><p>If need to fetch many elements, the most suitable concept is HashSet, because It’s very fast.</p><p>We’ll see how elements can be allocated to a HashSet.</p><ul><li>HashSet hashSet = new HashSet(); , HashSet() is the default/empty constructor. There, 16 allocations are available by default/initially. So, we can store 16 objects/elements.</li></ul><h4>Load Factor / Fill Ratio</h4><p>The load factor concept in HashSets is very important.</p><ul><li>ArrayList arrayList = new ArrayList(); , the default size is 10. So, 10 elements can be stored.</li><li>Assume, that you need to insert the 11th element. Then a new ArrayList will be created and, elements in the old ArrayList will be added to this new ArrayList and then the 11th element will be added finally. Then the old ArrayList will be added to the garbage collection.</li></ul><p>The load factor in the HashSet is 0.75. If the HashSet is filled with 0.75, then a new HashSet will be created. And the elements in the old HashSet are added to this new HashSet.</p><ul><li>HashSet hashSet = new HashSet(100);, the load factor is 0.75</li><li>HashSet hashSet = new HashSet(100, 0.95);, the load factor is 0.95</li><li>HashSet&lt;Integer&gt; hashSet = new HashSet(); , Integer elements will be stored here.</li></ul><p>HashSet has no specific/own methods. So, the methods which are in the Set interface are implemented in the HashSet class.</p><h4>💦Methods available in the Set Interface</h4><ul><li>add(value); — An element will be added to the HashSet</li></ul><p>The index concept is not used in HashSets. So, there are no index-based insertions. Because, in HashSet, elements are arranged in random order. Furthermore, we can’t do the sorting and shuffling as well. If needed, we have to convert this HashSet into an ArrayList and apply sortings/shufflings.</p><ul><li>addAll(Collection); — A group of elements will be added to the HashSet</li><li>remove(value); — An element will be removed from the HashSet Collection</li><li>removeAll(Collection); — A group of elements will be removed from the HashSet</li><li>contains(element); — Check the availability of the element in the HashSet. If that element is available this will return true and otherwise it return false.</li><li>containsAll(Collection); — Check the availability of a group of elements in the HashSet. If that group of elements is available this will return true and otherwise it return false.</li><li>isEmpty(); — If the HashSet is empty this will return true, otherwise false will be returned.</li></ul><p>So, guys, we will try these methods,</p><pre>import java.util.HashSet;<br>import java.util.Iterator;<br><br>public class HashSetDemo1 {<br>    public static void main(String[] args) {<br>        HashSet hashSet = new HashSet();//default capacity is 16, load factor is 0.75<br>        HashSet hashSet1 = new HashSet(100);//initial capacity 100<br>        HashSet hashSet2 = new HashSet(100, (float) 0.90);<br><br>        HashSet&lt;Integer&gt; integerHashSet = new HashSet&lt;&gt;();<br><br>        //add elements/objects into HashSet<br>        hashSet.add(75);<br>        hashSet.add(&quot;Welcome&quot;);<br>        hashSet.add(12.3);<br>        hashSet.add(&#39;A&#39;);<br>        hashSet.add(true);<br>        hashSet.add(null);<br><br>        System.out.println(hashSet);//insertion order not preserved<br><br>        //remove<br>        hashSet.remove(12.3);<br>        System.out.println(&quot;After removing a value : &quot; + hashSet);<br><br>        //contains<br>        System.out.println(&quot;Check for \&quot;Welcome\&quot; : &quot; + hashSet.contains(&quot;Welcome&quot;));<br>        System.out.println(&quot;Check for \&quot;Java\&quot; : &quot; + hashSet.contains(&quot;Java&quot;));<br>        System.out.println(&quot;Check for isEmpty : &quot; + hashSet.isEmpty());<br><br>        //Reading elements/objects from the hashset<br>        for (Object element : hashSet<br>        ) {<br>            System.out.print(element + &quot; &quot;);<br>        }<br>        System.out.println();<br>        Iterator iterator = hashSet.iterator();<br>        while (iterator.hasNext()) {<br>            System.out.print(iterator.next() + &quot; &quot;);<br>        }<br><br>        HashSet&lt;Integer&gt; evenNumber = new HashSet&lt;&gt;();<br>        evenNumber.add(2);<br>        evenNumber.add(4);<br>        evenNumber.add(6);<br>        System.out.println(&quot;HashSet : &quot; + evenNumber);<br><br>        HashSet&lt;Integer&gt; numbers = new HashSet&lt;&gt;();<br><br>        //addAll<br>        numbers.addAll(evenNumber);<br>        numbers.add(10);<br>        System.out.println(&quot;New HashSet : &quot; + numbers);<br><br>        //removeAll<br>        numbers.removeAll(evenNumber);<br>        System.out.println(&quot;After removing all even numbers : &quot; + numbers);<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>[null, A, 12.3, Welcome, 75, true]<br>After removing a value : [null, A, Welcome, 75, true]<br>Check for &quot;Welcome&quot; : true<br>Check for &quot;Java&quot; : false<br>Check for isEmpty : false<br>null A Welcome 75 true <br>null A Welcome 75 true HashSet : [2, 4, 6]<br>New HashSet : [2, 4, 6, 10]<br>After removing all even numbers : [10]</pre><p><strong>Now, we will see how to get the union, intersection, and the difference in HashSets</strong></p><p><strong>Union</strong></p><pre>import java.util.HashSet;<br><br>public class HashSetDemo2 {<br>    public static void main(String[] args) {<br>          HashSet&lt;Integer&gt; integerHashSet1 = new HashSet&lt;&gt;();<br>        integerHashSet1.add(1);<br>        integerHashSet1.add(2);<br>        integerHashSet1.add(3);<br>        integerHashSet1.add(4);<br>        integerHashSet1.add(5);<br><br>        System.out.println(&quot;HashSet 1 : &quot; + integerHashSet1);<br><br>        HashSet&lt;Integer&gt; integerHashSet2 = new HashSet&lt;&gt;();<br>        integerHashSet2.add(3);<br>        integerHashSet2.add(4);<br>        integerHashSet2.add(5);<br>        integerHashSet2.add(6);<br><br>        System.out.println(&quot;HashSet 2 : &quot; + integerHashSet2);<br><br>        //union<br>        integerHashSet1.addAll(integerHashSet2);<br>        System.out.println(&quot;Union : &quot; + integerHashSet1);<br>    }<br>}</pre><p><strong>Output of Union:</strong></p><pre>HashSet 1 : [1, 2, 3, 4, 5]<br>HashSet 2 : [3, 4, 5, 6]<br>Union : [1, 2, 3, 4, 5, 6]</pre><p><strong>Intersection</strong></p><pre>import java.util.HashSet;<br><br>public class HashSetDemo2 {<br>    public static void main(String[] args) {<br>          HashSet&lt;Integer&gt; integerHashSet1 = new HashSet&lt;&gt;();<br>        integerHashSet1.add(1);<br>        integerHashSet1.add(2);<br>        integerHashSet1.add(3);<br>        integerHashSet1.add(4);<br>        integerHashSet1.add(5);<br><br>        System.out.println(&quot;HashSet 1 : &quot; + integerHashSet1);<br><br>        HashSet&lt;Integer&gt; integerHashSet2 = new HashSet&lt;&gt;();<br>        integerHashSet2.add(3);<br>        integerHashSet2.add(4);<br>        integerHashSet2.add(5);<br>        integerHashSet2.add(6);<br><br>        System.out.println(&quot;HashSet 2 : &quot; + integerHashSet2);<br><br>        //intersection<br>        integerHashSet1.retainAll(integerHashSet2);<br>        System.out.println(&quot;Intersection : &quot; + integerHashSet1);<br>    }<br>}</pre><p><strong>Output of Intersection:</strong></p><pre>HashSet 1 : [1, 2, 3, 4, 5]<br>HashSet 2 : [3, 4, 5, 6]<br>Intersection : [3, 4, 5]</pre><p><strong>Difference</strong></p><pre>import java.util.HashSet;<br><br>public class HashSetDemo2 {<br>    public static void main(String[] args) {<br>          HashSet&lt;Integer&gt; integerHashSet1 = new HashSet&lt;&gt;();<br>        integerHashSet1.add(1);<br>        integerHashSet1.add(2);<br>        integerHashSet1.add(3);<br>        integerHashSet1.add(4);<br>        integerHashSet1.add(5);<br><br>        System.out.println(&quot;HashSet 1 : &quot; + integerHashSet1);<br><br>        HashSet&lt;Integer&gt; integerHashSet2 = new HashSet&lt;&gt;();<br>        integerHashSet2.add(3);<br>        integerHashSet2.add(4);<br>        integerHashSet2.add(5);<br>        integerHashSet2.add(6);<br><br>        System.out.println(&quot;HashSet 2 : &quot; + integerHashSet2);<br><br>         //difference<br>        integerHashSet1.retainAll(integerHashSet2);<br>        System.out.println(&quot;Difference : &quot; + integerHashSet1);<br>    }<br>}</pre><p><strong>Output of Difference:</strong></p><pre>HashSet 1 : [1, 2, 3, 4, 5]<br>HashSet 2 : [3, 4, 5, 6]<br>Difference : [3, 4, 5]</pre><p><strong>Subset</strong></p><pre>import java.util.HashSet;<br><br>public class HashSetDemo2 {<br>    public static void main(String[] args) {<br>        HashSet&lt;Integer&gt; integerHashSet1 = new HashSet&lt;&gt;();<br>        integerHashSet1.add(1);<br>        integerHashSet1.add(2);<br>        integerHashSet1.add(3);<br>        integerHashSet1.add(4);<br>        integerHashSet1.add(5);<br><br>        System.out.println(&quot;HashSet 1 : &quot; + integerHashSet1);<br><br>        HashSet&lt;Integer&gt; integerHashSet2 = new HashSet&lt;&gt;();<br>        integerHashSet2.add(3);<br>        integerHashSet2.add(4);<br>        integerHashSet2.add(5);<br>        integerHashSet2.add(6);<br><br>        System.out.println(&quot;HashSet 2 : &quot; + integerHashSet2);<br><br>        //subset<br>        integerHashSet1.containsAll(integerHashSet2);<br>        System.out.println(&quot;Subset : &quot; + integerHashSet1);<br>    }<br>}</pre><p><strong>Output subset:</strong></p><pre>HashSet 1 : [1, 2, 3, 4, 5]<br>HashSet 2 : [3, 4, 5, 6]<br>Subset : [1, 2, 3, 4, 5]</pre><h3>LinkedHashSets</h3><p>In linkeHashSets also default memory allocation is 16 and the load factor is 0.75 initially.</p><p>The methods available in the HashSet are available inside the LinkedHashSet as well.</p><pre>import java.util.LinkedHashSet;<br><br>public class LinkedHashSetDemo {<br>    public static void main(String[] args) {<br>        LinkedHashSet&lt;Integer&gt; integerLinkedHashSet = new LinkedHashSet&lt;&gt;();<br>        LinkedHashSet linkedHashSet = new LinkedHashSet();<br>        linkedHashSet.add(100);<br>        linkedHashSet.add(200);<br>        linkedHashSet.add(300);<br>        linkedHashSet.add(400);<br>        linkedHashSet.add(500);<br><br>        System.out.println(linkedHashSet);<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>[100, 200, 300, 400, 500]</pre><p>Ok..😎! Now we have discussed a lot. Let’s have a summary of the points we discussed.</p><ul><li>HashSet has a HashTable data structure.</li><li>LinkedHashSet has a HashTable + LinkedList data structure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlyQD54_ZL9tF0NbHVfs3w.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>Cool…! Yes, guys, It’s time to have a break. Let’s meet with part 5 of this blog series to discuss other things.</p><p>So, Stay tuned…!</p><p>Until then bye to you…👋🏼👋🏼👋🏼</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d95174961f4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/hashset-linkedhashset-in-the-java-collections-framework-d95174961f4f">HashSet &amp; LinkedHashSet in the Java Collections Framework</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ArrayList & LinkedList in the Java Collections Framework]]></title>
            <link>https://medium.com/linkit-intecs/methods-in-classes-interfaces-of-collections-framework-6e21a97851a4?source=rss-59081e8b5c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e21a97851a4</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[lists]]></category>
            <category><![CDATA[blog]]></category>
            <dc:creator><![CDATA[Nimasha Madhushani]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 13:42:49 GMT</pubDate>
            <atom:updated>2024-06-23T17:34:08.591Z</atom:updated>
            <content:encoded><![CDATA[<h4>Methods in Classes &amp; Interfaces of Lists in Collections Framework</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*5xQU7a8UbBFKMtWs1mXy3g.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>Hey Guys, I hope you have already read the first 2 articles of the Java Collections Framework Article Series. If not, this is for you.</p><ul><li>Part 1 — <a href="https://medium.com/@nimashamadhushani19/java-collection-framework-360e88b11906">Java Collections Framework</a></li><li>Part 2 — <a href="https://medium.com/@nimashamadhushani19/interfaces-classes-in-java-collections-framework-499d6ae25ba3">Interfaces &amp; Classes in Java Collections Framework</a></li></ul><p>So, below I have given you a summarized diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*WMWgW7jS9hOtqVd95sTcPQ.jpeg" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><h4>🔷Methods available in the Collection Interface</h4><p>These methods are derived as abstract methods. So there is no implementation available inside the Collection and List interfaces. So these methods are implemented using <strong>ArrayList</strong> and <strong>LinkedList</strong> classes.</p><h4>👁‍🗨add()</h4><ul><li>Add a single object to the Collection.</li><li>If I want to add an object to the collection, there is a method called add(). So, this particular method will add an object to the Collection as add(Object o).</li></ul><h4>👁‍🗨addAll()</h4><ul><li>Add multiple objects to the Collection.</li><li>So, a group of objects can be added to the Collection as addAll(Collection c).</li></ul><h4>👁‍🗨remove()</h4><ul><li>An object can be removed from the Collection as remove(Object o).</li></ul><h4>👁‍🗨removeAll()</h4><ul><li>All objects will be removed from the Collection as removeAll(Collection c).</li></ul><h4>👁‍🗨retainAll()</h4><ul><li>Except for this object, other objects will be removed from the Collection as retainAll(Object o).</li><li>If we use retainAll(Collection c) , except for the group of objects represented as ‘c’, all other objects in the Collection will be removed.</li></ul><h4>👁‍🗨clear()</h4><ul><li>This method will clear all the objects in the collection.</li></ul><h4>👁‍🗨isEmpty()</h4><ul><li>This method will check whether the Collection is empty or not.</li></ul><h4>👁‍🗨size()</h4><ul><li>This method can be used to get the no: of objects in the Collection/ to get the Collection size.</li></ul><h4>👁‍🗨contains()</h4><ul><li>This method will check whether the particular object is available in the Collection or not by the contains(Object o).</li></ul><h4>👁‍🗨containsAll()</h4><ul><li>This method will check whether the particular group of objects/elements is available in the Collection or not by the containsAll(Collection c).</li></ul><h4>👁‍🗨toArray()</h4><ul><li>The Collection can be converted to an array by using this method as toArray(Collection c).</li><li>So, this entire Collection will be converted to an array. As a result, an object array will be returned Object[].</li></ul><p>List, Set, and Queue are the child interfaces of the Collection interface. So, the methods which are in this Collection class will be inherited by these child classes. Some methods are specific to the List, Set, and Queue interfaces.</p><p>Ok guys, will see the own methods of the List interface...</p><h4>💦Methods available in the List Interface</h4><p>The index numbers represent the elements in the List. Duplicate elements are allowed in Lists. But we can differentiate them using the indexes of the List. So, to uniquely identify the elements, retrieving and inserting the elements in a List, we use these indexes.</p><p>We use add(Object o) method in the Collection interface. Here, the object will be added to the end of the List.</p><p>When it comes to the List interface, If we need to add an element/object somewhere in the List,add(index,Object o) is used. So the particular object will be added to the List based on the index.</p><ul><li>add(Object o) — Coming from the Collection interface</li><li>add(index,Object o) — Own method of List interface</li></ul><p>In the Collection interface, we have addAll(Collection c) method. But in the List interface, we use the index along with the group of elements/objects. So, the method definitions are different.</p><ul><li>addAll(Collection c) — Coming from the Collection interface</li><li>addAll(index,Collection c) — Own method of List interface</li></ul><p>In the Collection interface, we have remove(Object o) method. But in the List interface, we use the index along with the group of elements/objects. Then the element in the position of the index will be removed. So, the method definitions are different.</p><ul><li>remove(Object o) — Coming from the Collection interface</li><li>remove(index,Object o) — Own method of List interface</li></ul><h4>🦄get()</h4><ul><li>get() method is not available in the Collection interface. But it is used in the List interface to get the elements from the List.</li><li>get(index) — This will give the element/object corresponding to the position of the index.</li></ul><h4>🦄set()</h4><ul><li>Here we pass an index and a new object. So, the existing object will be replaced by the new object by using this set method.</li></ul><h4>🐳Classes in List Interface</h4><p><strong>ArrayList Class </strong>and <strong>LinkedList Class </strong>are included in the List interface.</p><h4>🐌ArrayList Class</h4><ul><li>ArrayList class is inside the java.utils package.</li><li>Declaring an ArrayList as ArrayList arrList = new ArrayList();</li><li>arrList, the reference variable of the ArrayList.</li><li>Every location in the ArrayList is identified by the index</li><li>ArrayList is automatically growable. So, it’s a growable object.</li><li>Insertion order is preserved and duplicate elements are allowed in the ArrayList.</li><li>There are many methods inside the ArrayList class.</li><li>ArrayList arrList = new ArrayList(); ArrayList() is the default constructor of the ArrayList Class</li><li>ArrayLists are allowed for different types of elements(heterogenous)</li><li>If we need similar types of objects/data to be stored, we should define only Strings inside the ArrayList,</li></ul><p>➡ArrayList &lt;String&gt;arrList = new&lt;String&gt;();</p><p>Assume that, there is an empty ArrayList initially. If we need to add an element to this ArrayList, we can use the add(Object o) method. And if we need to add an element to a specific position of this ArrayList we can use add(index, Object o).</p><p>If we need to get the no: of elements/objects inside the ArrayList, size() method can be used.</p><p>If need to remove an element/object, we can use the remove() method. If we need to remove an element/object from a specific place of the array list, we can do it based on the index as remove(index, Object o).</p><ul><li>get(index) method can be used to retrieve the data from the ArrayList.</li><li>set(index, Object o) method can be used to retrieve the data from the ArrayList.</li><li>contains(Object o) is used to whether this Collection has this object. Here a boolean value will be returned.</li><li>isEmpty() is used to check whether the ArrayList is empty or not. Tf the ArrayList is empty it will return true and otherwise return false.</li><li>addAll() is used to add a group of objects/elements to the ArrayList.</li><li>removeAll() is used to remove a group of objects/elements from the ArrayList.</li></ul><blockquote>We don’t have the sort() method directly in the ArrayList. So, we can use the predefined sort() method in the Collections Class which is inside the java.utils package. To sort the elements in the ArrayList, all elemts inside the ArrayList should be in the same type.</blockquote><blockquote>Collections.sort(arrayList); will sort the all elements inside the ArrayList. Here, the arrayList parameter which is inside this method is the reference variable of the ArrayList .</blockquote><blockquote>If we want to shuffle the elements in the ArrayList, we can use Collections.shuffle(arrayList); .</blockquote><p>If we have an array, we can convert that to an ArrayList as well.</p><p>🐞Guys, we will do some hands-on experience to verify the things we discussed so far.</p><pre>import java.util.*;<br><br>public class ArrayListCollection {<br>    public static void main(String[] args) {<br>        //Declare an ArrayList<br>        ArrayList arrayList = new ArrayList(); // arrayList is the object reference variable<br><br>        //this arraylist allow to store heterogeneous data. So, to restrict that by allowing only to insert homogenous data<br>        //we can specify the ArrayList by using a wrapper class<br>        ArrayList&lt;Integer&gt; integerArrayList = new ArrayList&lt;&gt;();<br>        ArrayList&lt;String&gt; stringArrayList = new ArrayList&lt;&gt;();<br><br>        //List interface is implemented by the ArrayList<br>        List list = new ArrayList();//This is an example of polymorphism and coding to interfaces in Java.<br><br>        //Add new elements to the ArrayList<br>        arrayList.add(100);<br>        arrayList.add(&quot;Nimasha&quot;);<br>        arrayList.add(10.5);<br>        arrayList.add(&#39;A&#39;);<br>        arrayList.add(true);<br><br>        System.out.println(arrayList);<br><br>        //Add new elements to a specific place in the array list<br>        //arrayList.add(index, object);<br>        arrayList.add(1, &quot;Welcome&quot;);<br>        System.out.println(&quot;After insertion : &quot; + arrayList);<br><br>        //size()<br>        System.out.println(&quot;\nNumber of elements in array list : &quot; + arrayList.size());<br><br>        //remove()<br>        //remove elements based on the index of the array list<br>        arrayList.remove(1); // here 1 is index<br>        System.out.println(&quot;After removing the element in index 1 : &quot; + arrayList);<br><br>        //remove existing elements by the value<br>        arrayList.remove(&quot;Nimasha&quot;); // here Nimasha is an element in the array list<br>        System.out.println(&quot;After removing the element &#39;Nimasha&#39;: &quot; + arrayList);<br><br>        //retrieve specific element from the array list<br>        System.out.println(&quot;Element in the 0th index of the array list : &quot; + arrayList.get(0));<br><br>        //change the existing value, replace with a new value<br>        arrayList.set(0, 50);<br>        System.out.println(&quot;After changing the existing value in the 0th index : &quot; + arrayList);<br><br>        //search elements in the array list, it returns true/false<br>        System.out.println(arrayList.contains(10.5));<br>        System.out.println(arrayList.contains(&quot;Nimasha&quot;));<br><br>        //check for empty<br>        System.out.println(&quot;is ArrayList empty? : &quot; + arrayList.isEmpty());<br>        System.out.println();<br><br>        //Approaches to read the data in an array list<br><br>        //1) for loop<br>        System.out.println(&quot;Reading elements using for loop&quot;);<br>        for (int i = 0; i &lt; arrayList.size(); i++) {<br><br>            System.out.print(arrayList.get(i) + &quot; &quot;);<br>        }<br>        System.out.println(&quot;\n\nReading elements using for each loop&quot;);<br><br>        //2) for..each loop<br>        for (Object element : arrayList<br>        ) {<br>            System.out.print(element + &quot; &quot;);<br>        }<br><br>        //3) iterator<br>        System.out.println(&quot;\n\nReading elements using iterator method&quot;);<br>        Iterator iterator = arrayList.iterator();//This will read each and every element in the array list<br>        while (iterator.hasNext()) {<br>            System.out.print(iterator.next() + &quot; &quot;);//print and automatically move to the next element<br>        }<br><br>        //Adding multiple elements/objects<br>        ArrayList arrayListNew = new ArrayList();<br>        arrayListNew.add(&quot;A&quot;);<br>        arrayListNew.add(&quot;M&quot;);<br>        arrayListNew.add(&quot;P&quot;);<br>        arrayListNew.add(&quot;L&quot;);<br><br>        ArrayList duplicateArrayList = new ArrayList();<br>        duplicateArrayList.addAll(arrayListNew);<br>        System.out.print(&quot;\n\nDuplicated ArrayList : &quot; + duplicateArrayList);<br><br>        //Remove all objects in the array list<br>        duplicateArrayList.removeAll(arrayListNew);<br><br>        System.out.println(&quot;\n\nAfter removing all elements in ArrayList : &quot; + duplicateArrayList);<br><br>        //Sorting the elements in the array list<br>        Collections.sort(arrayListNew);<br>        System.out.println(&quot;\nAfter sorting : &quot; + arrayListNew);<br>        Collections.sort(arrayListNew, Collections.reverseOrder());<br>        System.out.println(&quot;\nAfter sorting in reverse : &quot; + arrayListNew);<br><br>        //Shuffling the elements in the array list<br>        Collections.shuffle(arrayListNew);<br>        System.out.println(&quot;\nAfter shuffling array list : &quot; + arrayListNew);<br><br>        //Declaring an array<br>        String array[] = {&quot;Dog&quot;, &quot;Cat&quot;, &quot;Elephant&quot;};<br>        System.out.print(&quot;Array : &quot;);<br>        for (String value:array<br>             ) {<br>            System.out.print(value + &quot; &quot;);<br>        }<br><br>        //Convert array into ArrayList<br>        ArrayList arrayToArrayList =new ArrayList(Arrays.asList(array));<br>        System.out.println(&quot;\nArrayList : &quot;+arrayToArrayList+&quot; &quot;);<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>[100, Nimasha, 10.5, A, true]<br>After insertion : [100, Welcome, Nimasha, 10.5, A, true]<br><br>Number of elements in array list : 6<br>After removing the element in index 1 : [100, Nimasha, 10.5, A, true]<br>After removing the element &#39;Nimasha&#39;: [100, 10.5, A, true]<br>Element in the 0th index of the array list : 100<br>After changing the existing value in the 0th index : [50, 10.5, A, true]<br>true<br>false<br>is ArrayList empty? : false<br><br>Reading elements using for loop<br>50 10.5 A true <br><br>Reading elements using for each loop<br>50 10.5 A true <br><br>Reading elements using iterator method<br>50 10.5 A true <br><br>Duplicated ArrayList : [A, M, P, L]<br><br>After removing all elements in ArrayList : []<br><br>After sorting : [A, L, M, P]<br><br>After sorting in reverse : [P, M, L, A]<br><br>After shuffling array list : [M, L, A, P]<br><br>Array : Dog Cat Elephant <br>ArrayList : [Dog, Cat, Elephant] <br><br>Process finished with exit code 0</pre><h4>🐌LinkedList Class</h4><ul><li>The LinkedList class is used to implement the List interface. There is an interface called the Dequeue interface which extends from the Queue interface. So, this Dequeue interface is implemented using the LinkedList class.</li><li>The LinkedList class has many methods.</li><li>If we have a collection and if we need to do frequent retrieving, it is better to use the ArrayList concept. So, we can do that using get() method. There we can obtain the needed value by passing the index of the array list.</li></ul><p>If we need to do more operations(insertion/deletion) it is better to use a LinkedList. Why…?</p><p>If we need to insert an element to the middle of the array list we need to shift the elements to the right side. And if we need to delete a specific element from the array list we have to shift the other elements to the left side. So, we need to do shifting for both insertion and deletion. This shifting will take time. When the number of elements in the array list is high the time taking is also high.</p><p>Assume an array list has 100 elements. We need to add an element to the 2nd index position of it. Then we have to shift 98 elements to the right side.</p><p>So, we do not prefer to use the ArrayList concept when there are more insertion and deletion operations.</p><p>LinkedList representation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*uw5yJ_W0x5M2HDwEjv7WCA.jpeg" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>If we need to add a new element, a new node will be created and inserted into the LinkedList as below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUhRNkTuMlMGvr23iIOp_g.jpeg" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><ul><li>If we delete an element, that will be added to the garbage collection.</li></ul><p>🟣 If we have more no: of retrievals, the LinkedList concept is not suitable.</p><ul><li>When we need to search for any element, then need to traverse through the LinkedList to get the element. If we need to get the 100th element, 99 navigations are required to retrieve it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xvtEPvi1me_WQFfjhJHgw.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>LinkedLists are used to implement Queues and Stacks.</p><ul><li>Queues — FIFO (First In First Out) Concept</li><li>Stacks — FILO (First In Last Out) Concept</li></ul><p>List and Dequeue interface methods are implemented inside the LinkedList.</p><p>🦉LinkedList Features,</p><ul><li>Duplicate elements are allowed.</li><li>Insertion order is preserved.</li><li>Null values are acceptable.</li><li>All elements are linked with the addresses of nodes.</li><li>Default LinkedList is a Doubly Linked List Data Structure.</li></ul><p>Methods used in LinkedLists,</p><ul><li>add(Object) — Adding an object to the LinkedList</li><li>add(index, Object) — Adding an object with an index to the LinkedList</li><li>addAll(Collection)— Adding a group of objects/Collection to the LinkedList</li><li>remove(Object) — Removing an object directly in the LinkedList</li><li>remove(index, Object) — Removing an object with an index directly in the LinkedList</li><li>removeAll(Collection) — Removing a group of objects/Collection to the LinkedList</li><li>get(index) — Accordingly can get the specific element</li><li>set(index, Object) — Replace the existing value in the node</li></ul><p>Collections class which is in java.util package provides the methods for sorting and shuffling elements.</p><ul><li>Collections.sort()</li><li>Collections.shuffle()</li></ul><pre>import java.util.Collections;<br>import java.util.Iterator;<br>import java.util.LinkedList;<br><br>public class LinkedListDemo1 {<br>    public static void main(String[] args) {<br>        //Declare a LinkedList<br>        LinkedList linkedList = new LinkedList();// allows to store heterogeneous data<br>        LinkedList&lt;Integer&gt; integerLinkedList = new LinkedList&lt;&gt;();//allows to store only homogeneous data<br>        LinkedList&lt;String&gt; stringLinkedList = new LinkedList&lt;&gt;();<br><br>        //Adding elements<br>        linkedList.add(100);<br>        linkedList.add(&quot;Welcome&quot;);<br>        linkedList.add(15.5);<br>        linkedList.add(&#39;A&#39;);<br>        linkedList.add(true);<br>        linkedList.add(null);<br><br>        System.out.println(linkedList);<br><br>        //Get the length of the LinkedList<br>        System.out.println(linkedList.size());<br><br>        //Remove an element<br>        linkedList.remove(3);<br>        System.out.println(&quot;After removing 3rd element : &quot; + linkedList);<br><br>        //Adding elements in the middle of the LinkedList<br>        linkedList.add(3, &quot;Java&quot;);<br>        System.out.println(&quot;After inserting an element : &quot; + linkedList);<br><br>        //Retrieving value/object<br>        System.out.println(&quot;3rd element : &quot; + linkedList.get(2));<br><br>        //Changing the value<br>        linkedList.set(5, &quot;X&quot;);<br>        System.out.println(&quot;After changing the value : &quot; + linkedList);<br><br>        //Contains<br>        System.out.println(&quot;Check for availability \&quot;Java\&quot; :&quot; + linkedList.contains(&quot;Java&quot;));<br>        System.out.println(&quot;Check for availability \&quot;Python\&quot; :&quot; + linkedList.contains(&quot;Python&quot;));<br><br>        //Check for empty<br>        System.out.println(&quot;Linkedlist is Empty? :&quot; + linkedList.isEmpty());<br><br>        //Reading elements from LinkedList using for loop<br>        for (int i = 0; i &lt; linkedList.size(); i++) {<br>            System.out.print(linkedList.get(i) + &quot; &quot;);<br>        }<br>        System.out.println();<br>        for (Object element : linkedList<br>        ) {<br>            System.out.print(element + &quot; &quot;);<br><br>        }<br>        System.out.println();<br><br>        //iterator method<br>        Iterator iterator = linkedList.iterator();<br>        while (iterator.hasNext()) {<br>            System.out.print(iterator.next() + &quot; &quot;);<br>        }<br><br>        LinkedList list = new LinkedList();<br>        list.add(&quot;X&quot;);<br>        list.add(&quot;B&quot;);<br>        list.add(&quot;F&quot;);<br>        list.add(&quot;D&quot;);<br>        list.add(&quot;C&quot;);<br><br>        LinkedList newList = new LinkedList();<br>        newList.addAll(list);<br>        System.out.print(newList + &quot; &quot;);<br><br>        newList.removeAll(list);<br>        System.out.println(&quot;\n&quot; + newList);<br><br>        //soring<br>        System.out.println(&quot;Before Sorting : &quot; + list);<br>        Collections.sort(list);<br>        System.out.println(&quot;After Sorting : &quot; + list);<br><br>        //reverse order<br>        Collections.sort(list, Collections.reverseOrder());<br>        System.out.println(&quot;Reverse Sorting : &quot; + list);<br><br>        //shuffling elements<br>        System.out.println(&quot;\nBefore Shuffling : &quot; + list);<br>        Collections.shuffle(list);<br>        System.out.println(&quot;After Shuffling : &quot; + list);<br>    }<br>}</pre><p><strong>Output:</strong></p><pre>[100, Welcome, 15.5, A, true, null]<br>6<br>After removing 3rd element : [100, Welcome, 15.5, true, null]<br>After inserting an element : [100, Welcome, 15.5, Java, true, null]<br>3rd element : 15.5<br>After changing the value : [100, Welcome, 15.5, Java, true, X]<br>Check for availability &quot;Java&quot; :true<br>Check for availability &quot;Python&quot; :false<br>Linkedlist is Empty? :false<br>100 Welcome 15.5 Java true X <br>100 Welcome 15.5 Java true X <br>100 Welcome 15.5 Java true X [X, B, F, D, C] <br>[]<br>Before Sorting : [X, B, F, D, C]<br>After Sorting : [B, C, D, F, X]<br>Reverse Sorting : [X, F, D, C, B]<br><br>Before Shuffling : [X, F, D, C, B]<br>After Shuffling : [F, X, C, D, B]<br><br>Process finished with exit code 0</pre><p>🔴Special methods belong to the LinkedList class,</p><p>🐇<strong>addFirst(Object) </strong>— Adding the element in the first place as the 1st element</p><p>🐇<strong>addLast(Object) </strong>— Adding the element as the element</p><p>🐇<strong>removeFirst() </strong>— The first element will be removed from the LinkedList.</p><p>🐇<strong>removeLast() </strong>— The last element will be removed from the LinkedList.</p><p><strong>🐇getFirst()</strong> — Get the 1st element/node from the LinkedList</p><p><strong>🐇getLast()</strong> — Get the Last element/node from the LinkedList</p><pre>import java.util.LinkedList;<br><br>public class LinkedListDemo2 {<br>    public static void main(String[] args) {<br>        LinkedList list = new LinkedList();<br>        list.add(&quot;Dog&quot;);<br>        list.add(&quot;Cat&quot;);<br>        list.add(&quot;Horse&quot;);<br><br>        System.out.println(list + &quot; &quot;);<br><br>        list.addFirst(&quot;Tiger&quot;);<br>        list.addLast(&quot;Elephant&quot;);<br><br>        System.out.println(list + &quot; &quot;);<br><br>        System.out.println(list.getFirst());<br>        System.out.println(list.getLast());<br><br>        list.removeFirst();<br>        System.out.println(&quot;After removing first element : &quot; + list + &quot; &quot;);<br><br>        list.removeLast();<br>        System.out.println(&quot;After removing last element : &quot; + list + &quot; &quot;);<br><br>    }<br>}</pre><p><strong>Output:</strong></p><pre>[Dog, Cat, Horse] <br>[Tiger, Dog, Cat, Horse, Elephant] <br>Tiger<br>Elephant<br>After removing first element : [Dog, Cat, Horse, Elephant] <br>After removing last element : [Dog, Cat, Horse] <br><br>Process finished with exit code 0</pre><p>Cool..Guys!😎</p><p>I think we can have a break here, So, I hope to discuss,</p><p>💦Methods available in the Set Interface</p><p>💦Methods available in the Queue Interface</p><p>in the next blog. Then bye for all…! Stay tuned to grab the knowledge in the part 4 article in the <strong><em>Java Collections Framework </em></strong>article series…!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e21a97851a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/methods-in-classes-interfaces-of-collections-framework-6e21a97851a4">ArrayList &amp; LinkedList in the Java Collections Framework</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interfaces & Classes in Java Collections Framework]]></title>
            <link>https://medium.com/linkit-intecs/interfaces-classes-in-java-collections-framework-499d6ae25ba3?source=rss-59081e8b5c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/499d6ae25ba3</guid>
            <category><![CDATA[interfaces]]></category>
            <category><![CDATA[medium]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[class]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nimasha Madhushani]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 17:53:46 GMT</pubDate>
            <atom:updated>2024-06-23T17:32:05.111Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*OnptrYKvnbgN-5w_MAS1cg.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>Hi Java lovers😌,</p><p>I think you have already read part 01 of this Java collections framework article series. If not here is the link: <a href="https://nimashamadhushani19.medium.com/java-collection-framework-360e88b11906">Java Collection Frameworks — Part 01</a>.</p><p>Let’s continue…</p><h4>🔷Collection Interface</h4><p>Collections have ‘n’ no: of interfaces.</p><h4>🔷Main Interfaces</h4><p>The Collection Interface is the main interface. It is the root interface for all other collection-related interfaces and cases. It also includes common methods that can be used for other collection objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*hfFJHdNoFM2tU1G0sZPgQA.jpeg" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><ul><li>A group of objects is a collection. In the above image, you can see that there are multiple objects represented in a single entity.</li><li>Adding an object, removing an object, and verifying an existing object can be done using a set of methods. Those methods are included inside the collection interface. So, the methods defined inside the collection interface are common across all classes in the collection.</li><li>Collection(I) is purely an interface.</li></ul><p>Then, <strong>what are the Collections in Java?</strong></p><p>In Java, we have a package called java.utils. So, this <strong>collections</strong> is a pre-defined class inside this package.</p><ul><li>Collections class includes a set of methods. So, these methods inside the collection<strong>s</strong> can be used for performing the operations inside collection objects.</li></ul><p>Example,</p><ul><li>Assume that ArrList is an array list. An array list is a collection object. Elements 1,2,3 are different objects inside this array list. If we need to sort the elements inside the array list, we can use <strong>collections class. </strong>There is a utility method called sort is available inside this collections class. Therefore, we can do the sort as Collections.sort(ArrList);</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*TYxGM4aCIMDEaJcuISIr8Q.jpeg" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>🎯Summary</p><ul><li>The collection is an interface that comes under the collections framework.</li><li>Collections is a pre-defined class containing a set of utility methods.</li><li>Collections call is available in the java.utils package</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*GOX3uGqqtC5xWwuCyvLlNw.jpeg" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*xjvfK5LY9vAyurCtIF5xxw.jpeg" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><ul><li>List, Set, and Queue are the children of the Collection interface.</li><li>These child interfaces are implemented using different classes.</li></ul><h4>🔷List Interface</h4><p>The list is a collection in which we can store a group of elements/objects.</p><ul><li>The root interface of the List interface is the Collection interface. So, the List is a child interface.</li></ul><p>⚡Features in List concept,</p><ul><li>Insertion order should be preserved</li><li>Duplicate elements are allowed</li></ul><p>⚡The list interface is implemented using different classes. They are,</p><ul><li>ArrayList Class</li><li>LinkedList Class</li><li>Vector Class — Stack Class (Legacy Classes)</li></ul><h4>🔷Set Interface</h4><p>The Set interface is a child of the Collection interface.</p><p>⚡Features in Set concept,</p><ul><li>Insertion order is <strong>not</strong> preserved</li><li>Duplicate elements are <strong>not </strong>allowed</li></ul><p>⚡The set interface is implemented using different classes. They are,</p><ul><li>HashSet</li><li>LinkedHashSet</li></ul><h4>🔷Queue Interface</h4><p>The Queue interface is a child of the Collection interface.</p><p>⚡Features in Queue concept,</p><ul><li>Queues follow the FIFO(First In First Out) concept.</li><li>Queue concept is applied for the objects that are prior to processing.</li></ul><p>⚡The queue interface is implemented using different classes. They are,</p><ul><li>PriorityQueue Class (used to implement the queue interface)</li></ul><h4>🔷Map Interface</h4><p>Independent from the Collection interface. So, the map is not a child of the Collection interface.</p><p>⚡Features in map concept,</p><ul><li>Duplicates are not allowed for keys, and duplicates are allowed for values. So, keys are unique.</li><li>Each key is an object, and each value is also an object.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*vSyC8Iass9loomgztW9s-A.jpeg" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>⚡The map interface is implemented using different classes. They are,</p><ul><li>HashMap</li><li>LinkedHashMap</li></ul><p>Yeah…!</p><p>I think we have discussed a lot in this article. So, I thought to have a little break here. Hope you will count fingures to enjoy the next article. Then, stay tuned guys…</p><p>Thank you for reading this.</p><p>Bye bye…👋🏼👋🏼</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=499d6ae25ba3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/interfaces-classes-in-java-collections-framework-499d6ae25ba3">Interfaces &amp; Classes in Java Collections Framework</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Collections Framework]]></title>
            <link>https://medium.com/linkit-intecs/java-collection-framework-360e88b11906?source=rss-59081e8b5c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/360e88b11906</guid>
            <category><![CDATA[arraylist]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[collections-framework]]></category>
            <category><![CDATA[blogging]]></category>
            <dc:creator><![CDATA[Nimasha Madhushani]]></dc:creator>
            <pubDate>Mon, 29 Jan 2024 20:12:35 GMT</pubDate>
            <atom:updated>2024-06-23T17:30:59.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*qXiwoqes10SpZqq1f3itOA.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>Hi techies…😎, This is the first blog to have an understanding of the Java collection framework. After reading this mini blog, you will realize why we should learn about collections.</p><p>Ok…, Let’s have a start🐣</p><h4>📌Introduction</h4><p>In Java, the collection framework has provided a certain no: of classes and interfaces. So we have,</p><ul><li>ArrayList</li><li>List</li><li>HashMap</li><li>HashTable</li><li>Tree</li><li>Stack</li></ul><h4>📌What is Collection</h4><ul><li>A collection is a Group of Objects(A single entity which represents multiple objects)</li></ul><blockquote>If there are multiple students in a class we can say it is a collection of students, If there are many employees in a company we can say it is a collection of employees.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*0TM8aBSltcJR0VhxLQ3Jdg.jpeg" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>To represent a group of elements we need a collection.</p><h4>📌What is the Collection Framework</h4><p>Defines the different interfaces and classes representing a group of objects to a collection.</p><p>For example collection framework,</p><ul><li>ArrayLists in Java can be used to store elements in a collection</li></ul><h4>📌Problems with Array Concept</h4><p>The way of storing a value in a variable,</p><ul><li>int a = 10; (int — data type, a — variable, 10 — value)</li></ul><p>If we need to store 100 values, we need to initiate 100 variables. It is not a best programming practice. So, we can use the array concept to store multiple values.</p><ul><li>int a[] = new int[100];(This is a single variable, that we can store multiple values). This will create 100 memory locations. So, arrays can be used to store multiple elements/objects.</li><li>We can consider the indexes in an array to access the memory locations.</li><li>However, we have some limitations in the array concept. Therefore, we can use a collection framework to overcome these limitations.</li><li>int a[] = new int[10]; Here we can only store 10 elements, as we have only 10 memory locations under this array variable.</li></ul><p>In an array, we can store only homogeneous data. If we create an integer-type array in the above example, we can store only integer-type elements.</p><p>If we create an array with a Student Class object, in every memory location we can store a student detail object. As this is a Student type we can only store student detail objects.</p><h4>📌Object Array</h4><p>Object a[] = new Object[5]; In this array, we can store heterogeneous data. Example,</p><ul><li>a[0] = 10;(Integer type)</li><li>a[1] = 10.5;(Float type)</li><li>a[2] = &quot;Nimal&quot;;(String type)</li></ul><p>Object array is also a type of collection.</p><h4>📌Problem with Array</h4><ol><li>Fixed memory size when defining (Having limited memory space)</li></ol><p>Arrays are not growable in nature.(Cannot increase or decrease the size of the array after defining)</p><ul><li>If Object a[] = new Object[5]; , we can only store 5 objects. If we add the 6th data object, it will return an exception(ArrayIndexOutOfBoundException).</li><li>If we store only 3 objects in the above-defined array, the rest of the memory allocations will be wasted.</li></ul><p>2. Only homogeneous data can be stored</p><p>3. While implementing, underlying data structure concepts haven’t been used. Therefore, any ready-made method is not available.</p><h4>📌Why Collection?</h4><p>To overcome the problems/limitations related to the array concept, we can use collections.</p><h4>📌Collection Vs. Array</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*EhVPLlt04PdwAjmPBFTpwg.jpeg" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>Hope now you know, why we need Java collection framework and the importance of using them. I think you like to sharpen your knowledge about the collection framework further. So, stay tuned guys…😋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=360e88b11906" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/java-collection-framework-360e88b11906">Java Collections Framework</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Foundation to Spring Boot Beginners]]></title>
            <link>https://medium.com/linkit-intecs/foundation-to-spring-boot-beginners-cca48e8e67be?source=rss-59081e8b5c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cca48e8e67be</guid>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[annotations]]></category>
            <dc:creator><![CDATA[Nimasha Madhushani]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 17:43:38 GMT</pubDate>
            <atom:updated>2024-06-23T17:17:35.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*yhguHhjJKfCYEORQ6aczWw.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><blockquote>Spring Boot is a lightweight, powerful framework, and built on top of the Spring Framework.</blockquote><blockquote>Spring Boot module provides a Rapid Application Development feature to the Spring framework.</blockquote><blockquote><em>📝Key points we should focus on learning about the Spring Boot,</em></blockquote><h4>1. Spring Initializer (<a href="http://start.spring.io/">start.spring.io</a>)</h4><ul><li>Web-based tool</li><li>Bootstrap Spring Boot projects</li><li>Allows to select relevant dependencies, packaging options, and project settings</li><li>Generate a customized project structure</li></ul><h4>2. Dependencies</h4><ul><li>Use as external modules/plugins to enhance the functionality of the project</li></ul><h4>3. Dependency Injection</h4><ul><li>A core concept in Spring Boot</li><li>Facilitate loose coupling by allowing management and inject dependencies to application components</li><li>Enhance the flexibility and maintainability</li></ul><h4>4. Maven/ Gradle</h4><ul><li>Spring Boot projects can be built using either Maven or Gradle</li><li>Easy to manage dependencies efficiently</li><li>Automatically fetch required libraries</li><li>Maintain the consistency of the project builds</li></ul><h4>5. Embedded HTTP Servers</h4><ul><li>Spring Boot has embedded HTTP servers like Tomcat</li><li>Eliminate the use of external server configurations</li><li>Simplify the deployment</li></ul><h4>6. JPA</h4><ul><li>Java Persistence API</li><li>Stands for ORM(Object Relational Mapping) in Java applications</li><li>Spring Boot provides easy integration with JPA for data access</li><li>Streamline database operations</li><li>Interact with database</li></ul><h4>7. Annotations</h4><ul><li>Use to simplify the configurations</li><li>Reducing boilerplate codes</li><li>Enhance the readability</li></ul><h4>8. Jar</h4><ul><li>Spring Boot applications are usually packaged as JAR(Java Archive) files</li><li>Standalone executable JAR simplifies deployment and execution</li></ul><h4>9. Lombok Library</h4><ul><li>Lombok is a Java library that helps reduce boilerplate code by automatically generating common code blocks such as getters, setters, and, constructors.</li><li>So, Lombok provides annotations. (We will discuss the annotations belonging to this Lombok library in the latter part of this article).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*YNcBnbJkP7qTPzve7U_0HA.jpeg" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><h4>The flow of Spring Boot Application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKrKzMctdtEWLYh58mJVqw.jpeg" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>💎<strong>FrontEnd</strong></p><p>A client that is responsible for interacting with the user and recent data</p><p>💎<strong>Backend</strong></p><ol><li>Controller</li></ol><ul><li>Serving as an entry point for processing user inputs.</li><li>The controller can handle requests and responses.</li><li>Controller-received things are attached to a DTO and sent to the service layer.</li></ul><p>2. API(Application Programming Interface)</p><ul><li>RESTful APIs that allow communication between the frontend and backend.</li></ul><p>3. DTO(Data Transferring Objects)</p><ul><li>Objects used to transfer data between different layers of an application, typically between the frontend, controller, and service layers.</li></ul><p>4. Service</p><ul><li>Contain business logic and perform operations requested by controllers.</li></ul><p>5. Entity</p><ul><li>Represent objects stored in DB.</li><li>Most of the time entity will map the table in the DB</li></ul><p>6 . Repository</p><ul><li>Provide an abstraction for data access</li><li>Interact with databases to handle CRUD operations</li></ul><p>7. Database</p><ul><li>Stores and manages data persistently</li><li>Spring Boot supports various databases(MongoDB, MySQL, MSSQL, PostgreSQL)</li><li>Can use technologies like JPA to interact with databases easily</li></ul><h4>🔮Annotations</h4><h4><strong>@Entity</strong></h4><ul><li>When the application runs, Hibernate, the JPA provider, creates a table in the database based on this entity.</li></ul><h4>@Id</h4><ul><li>Use to designate a field as the primary key of an entity</li><li>Signifies the unique identifier for database records</li></ul><h4>@Query</h4><ul><li>Used to declare custom queries in Spring Data JPA</li><li>Allows developers to define complex database operations(custom inserts or updates)</li></ul><h4>@RestController</h4><p><em>(response body + controller)</em></p><ul><li>Responses are converted to XML/JSON automatically</li></ul><h4><strong>@RequestMapping</strong></h4><ul><li>Maps HTTP requests to handler methods in a controller</li></ul><p><strong><em>@GetMapping</em></strong><em> — Handle HTTP GET requests, and use</em> <em>for retrieving resources or data</em></p><p><strong><em>@PostMapping</em></strong><em> — Handle HTTP POST requests, and used for creating or adding new resources</em></p><p><strong><em>@PutMapping</em></strong><em> — Handle HTTP PUT requests, and used for updating existing resources or creating if not present</em></p><p><strong><em>@DeleteMapping </em></strong><em>— Handle HTTP DELETE requests, and used for </em>for deleting or removing resources</p><h4><strong>@CrossOrigin</strong></h4><ul><li>Cross-origin resource sharing when the frontend and backend are in two origins (It is blocked for a security reason)</li></ul><h4><strong>@Autowired</strong></h4><ul><li>Used for automatic dependency injection (If two things depend mostly on each other then as a dependency we can inject that into another class)</li></ul><h4>@Service</h4><ul><li>Identify the service layer when performing business logic or service-layer operations</li></ul><h4>@Transactional</h4><ul><li>Indicates that a method, or all methods in a class, should be executed within a database transaction.</li><li>Ensures consistency for database operations, preventing data inconsistencies.</li></ul><h4><strong>@AllArgsConstructor/@NonArgsConstructor</strong></h4><ul><li>These 2 annotations are <strong>provided by the Lombok Library</strong>.</li><li>@AllArgsConstructor generate a constructor with arguments for all fields in the class.</li><li>@NoArgsConstructor generates a constructor with no arguments.</li></ul><h4>@Builder</h4><ul><li>Provided by the Lombok Library.</li><li>Generates a builder pattern for class.</li></ul><h4><strong>@Getter / @Setter</strong></h4><ul><li>Provided by the Lombok Library.</li><li>Generates getter and setter methods for the fields in the class.</li></ul><h4>@ToString</h4><ul><li>Provided by the Lombok Library.</li><li>Generates a toString() method for the class, including all fields.</li></ul><h4>@Data</h4><ul><li>Provided by the Lombok Library.</li><li>This is a combination of @Getter, @Setter, @ToString, @EqualsAndHashCode, and @RequiredArgsConstructorannotations.</li><li>Generates common boilerplate code like getters, setters, toString, equals, hashCode, and constructors, streamlining Java class definitions.</li></ul><p>In this article, I hope to make you aware of the background and the jargon you may know to learn Spring Boot. So, I will guide you to implement a simple Spring Boot application in the next blogs.</p><p>Stay tuned guys😎, until then bye byeeee…👋🏼👋🏼</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cca48e8e67be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/foundation-to-spring-boot-beginners-cca48e8e67be">Foundation to Spring Boot Beginners</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-Oriented Programming Concepts in Java]]></title>
            <link>https://medium.com/linkit-intecs/object-oriented-programming-concepts-in-java-906a694f327b?source=rss-59081e8b5c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/906a694f327b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[blogging]]></category>
            <category><![CDATA[example]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Nimasha Madhushani]]></dc:creator>
            <pubDate>Fri, 26 Jan 2024 19:04:45 GMT</pubDate>
            <atom:updated>2024-06-23T17:16:42.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*h861RRQ5f6YmZ0WnwNV6kQ.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>OOP is a fundamental programming concept that includes the concepts of <strong>abstraction, encapsulation, inheritance,</strong> and <strong>polymorphism</strong>. When comparing earlier programming methods, Reusability, maintainability, and extensibility, of code are the main advantages of OOP concepts.</p><p>Ok…Now, Let’s move on with further clarifications.</p><h3><strong>Inheritance</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*_D2AWEp18oxFG2IJj4tbWg.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><blockquote>Inheritance is a core concept of object-oriented programming and eliminates redundant code. Therefore, we can use inheritance for method overriding and code reusability. Sub class and super class are the two main important terms, we use in inheritance in Java.</blockquote><p><strong>Super class</strong>- base/parent class where a subclass inherits the features.</p><p><strong>Sub class</strong>- an extended class that inherits the other classes.</p><p><strong>Single Inheritance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*m5dnq2ODjaRW16S8d4rVxw.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*RZA-2d5X-WmqxApxc49Cqw.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*-jzNviVisbU8ujAsz0ObDg.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>If we change the String brand; variable in the super class as private String brand; The sub class called NewPhone will not be allowed to access the variable called brand.</p><p><strong>Hierarchical Inheritance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*gOKwmaojz2juJXWg3hah-A.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*_DWHhaKtxNBCBu5ob_zu1A.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*eckWxDBv_Lk5UYx_0CbCDw.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p><strong>Multilevel Inheritance</strong></p><p>A class inherits properties from a class that again has inherited properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*OHFzqZowvl5oAAOESymg_Q.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*VSqWnmV0t07VBQOnA1TpkQ.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*S7utj6StiRdeu09Z8H2gxg.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><h3>Encapsulation</h3><blockquote>Encapsulation means the bundling of variables and methods inside a class. Furthermore, it can achieve data hiding, and getters and setters are provided. A completely encapsulated class can be created in Java by making all the class variables private. Data hiding, Increased flexibility, and Reusability are some advantages of encapsulation.</blockquote><p><strong>🔮🧸Animal Class</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*_OfiEjBeYb1QSRFcqxDMlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*-ORLFMyD_LcXNvTT6Yj_Tg.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p><strong>🐶Dog Class</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*OMKti_yjORq94w1omYGjbA.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p><strong>🎯Demo Class</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*gyvKLfmSR_0vGdF1Wp0hMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*aLEZ-sekh4hBuFm7msVuHQ.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*6Fa8e6yT1DW0JEUdFEgJ7g.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><h4><strong>Polymorphism</strong></h4><blockquote>Having many forms is the simple definition of polymorphism. When considering the real world, one person can play different roles. For example, a person at the same time is a brother, father, husband, or friend. But, the behavior will be changed according to the situation. This is the meaning of polymorphism. There are two types of polymorphism</blockquote><p><strong>Compile time polymorphism(static polymorphism)</strong></p><p>The method used to create this form of polymorphism is function overloading. Methods will be overloaded when there are multiple methods with the same name but different parameter lists(methods with different method signatures).</p><p><strong>Runtime polymorphism(dynamic polymorphism)</strong></p><p>It is a procedure by which a function call to an overridden method is handled at runtime. By using Method Overriding, this kind of polymorphism is accomplished. Method overriding is the process of declaring a method in a subclass that already exists in the parent class. Constructors, static methods, and final methods cannot be overridden. Overridden is allowed when the instance methods are inherited by the child class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*lRVz6NyJY43ZgkBfyURMMA.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*FtwNelgrpgperPc0OE0OnQ.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*-bcnfNxU3cO5shvh3FQ_4A.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p><strong>Polymorphism using method overriding</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*UxPwMmKkdRtET77_O58Urw.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*lPrQTLEpKUkq3mydiOzgvg.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p><strong>Polymorphism using method overloading</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*6RxuEiMmAu_1a_q3m4dGDA.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*m0MPPPy906-6z98YpE-chA.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><h3>Abstraction</h3><blockquote>The process of hiding specific details and showing only essential information to the user is data abstraction. The abstract keyword (non-access modifier), is used for methods and classes. Abstract classes cannot be used to create objects; abstract methods can only be used inside an abstract class. But, non-abstract classes can be contained inside the abstract class. These abstract methods don’t have a body and the body is provided by the subclass in inherited form. Abstract classes should be extended and the abstract methods should be overridden.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*_rHx9QFN84DH85Vt1ArjhA.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*-pp7a4RB-aBnHGVLMEHZlw.png" /><figcaption>image by <a href="https://nimashamadhushani19.medium.com/">author</a></figcaption></figure><p>All 4 concepts of object-oriented programming have been discussed using examples and code snippets. I hope you gained some knowledge by going through this article.</p><p>Thank you…..!!😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=906a694f327b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/object-oriented-programming-concepts-in-java-906a694f327b">Object-Oriented Programming Concepts in Java</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connecting a SpringBoot Application to a PostgreSQL Database]]></title>
            <link>https://medium.com/linkit-intecs/connecting-a-springboot-application-to-a-postgresql-database-427364f48245?source=rss-59081e8b5c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/427364f48245</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nimasha Madhushani]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 18:20:32 GMT</pubDate>
            <atom:updated>2023-05-01T06:53:08.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gCSYPuKMLxGA0NI7ol8gNw.png" /><figcaption>Artwork by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>Hi Spring Lovers😍, Let’s implement a <strong>spring boot application</strong>. Here, I’m going to connect my application with the <strong>PostgreSQL database</strong>.</p><blockquote>I think you are super excited to try this out😉.</blockquote><blockquote>Now, will initiate a spring application. To that access the below link and follow the steps which have been done in the below image of Spring Initializer.</blockquote><blockquote>⚓<a href="https://start.spring.io/">Link to create spring boot demo application using spring initializer.</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5UJfXSCoxwMmloag.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><blockquote><em>Here, you have to add dependencies as I have done.</em></blockquote><blockquote><strong><em>⛄ PostgreSQL Driver SQL </em></strong><em>→ Allows Java programs to connect to a PostgreSQL database using standard, database-independent Java code.</em></blockquote><blockquote><strong><em>⛄ Spring Data JPA </em></strong><em>→ Persist data in SQL stores with Java Persistence API using Spring Data and Hibernate.</em></blockquote><blockquote><strong><em>⛄ Spring Web </em></strong><em>→ Build web, including RESTful, applications using Spring MVC. Uses Apache Tomcat as the default embedded container.</em></blockquote><blockquote><em>🔮</em>Now click on the <strong>“GENERATE” </strong>button to download the project. Then unzip it and open it using a convenient IDEA. (Ex: IntelliJ)</blockquote><p>📝You can download and install the latest <a href="https://www.postgresql.org/download/">PostgreSQL</a>.</p><h4><strong>Installing Steps of PostgreSQL.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MqL8ikvhon4IvS28.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IPXBrqnz-r7zIN9n.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>When installing you have to give a <strong>password</strong>. And keep it in your mind, because that password is needed to connect the server. Furthermore, you have to give the <strong>port number for PostgreSQL. </strong>Usually, the port number is given as 5432. Now, the app is installed on your local machine.</p><p>🔎Then find the app [<strong>pgAdmin 4</strong>] mentioned below in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hPovwIyJmd6oRQ22.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>Now you can see an interface to enter the password to connect the server as below. Here you have to enter the password you inserted while installing the PostgreSQL onto your machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QtEpPprzT47wI-Lw.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>Now you can see a red colour cross mark on PostgreSQL 15. So, we have to connect the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zDPV-kJ0HyVt70na.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>Therefore, you can follow the below steps to connect to the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uHuxWl6lFljU7BCI.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>Finally, you can see the notifications which show the successful connection of the server in the bottom-right corner of the tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ytmCkTibPq91upzu.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>For the moment if you don’t have created a database, you can follow the steps mentioned in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4ffZ7pcl_dGHlcGG.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>After that, you can see the database and the user of the database in the Statistics tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rPtnZ23ycix0vuTX.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>Then we can connect our database with the created spring boot application.</p><h4><strong>🧾📚Database configuration:</strong></h4><p>application.propertiesfile:</p><pre>spring.datasource.url=jdbc:postgresql:localhost:5432/EmployeeDB //Line 01<br>spring.datasource.username=postgres  //Line 02<br>spring.datasource.password=1234      //Line 03<br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect<br>spring.jpa.properties.hibernate.format_sql=true<br>spring.jpa.show-sql=true<br>spring.jpa.open-in-view=false</pre><blockquote><em>1️⃣</em><strong>Line 01 →</strong> Here, 5432 is given as the port number for PostgreSQL. Your port number may be different. Therefore put your port number there.</blockquote><blockquote>The database name &lt;<strong>EmployeeD</strong>&gt; Balso should be the same as the database you have created while doing the above steps.</blockquote><blockquote><strong><em>2️⃣</em>Line 02 →</strong> Username should be yours one.</blockquote><blockquote><em>3️⃣</em><strong><em>Line 03 → </em></strong>Password also should be yours one.</blockquote><blockquote><em>🔶</em>spring.jpa.hibernate.ddl-auto=update</blockquote><blockquote><strong>update : </strong>The object model created based on the mappings (annotations or XML) is compared with the existing schema, and then Hibernate updates the schema according to the diff. It never deletes the existing tables or columns even if they are no more required by the application.<em> [ </em><a href="https://stackoverflow.com/questions/42135114/how-does-spring-jpa-hibernate-ddl-auto-property-exactly-work-in-spring"><em>Further Readings </em></a><em>: </em><a href="https://stackoverflow.com/questions/42135114/how-does-spring-jpa-hibernate-ddl-auto-property-exactly-work-in-spring"><em>spring.jpa.hibernate.ddl-auto</em></a><em> ]</em></blockquote><blockquote><em>🔶</em>spring.jpa.show_sql=true</blockquote><blockquote>Tells hibernate to Write all SQL statements to console.</blockquote><blockquote><em>🔶</em>spring.jpa.properties.hibernate.show_sql=true</blockquote><blockquote>Hibernate Configuration Properties [ It represents the type of database used in hibernate to generate SQL statements for a particular relational database. It is used to print the SQL in the log and console.]</blockquote><blockquote><em>🔶</em><em>spring.jpa.open-in-view=false</em></blockquote><blockquote>This will disable OSIV so that you can handle the LazyInitializationException the right way. <a href="https://stackoverflow.com/a/48222934/16349670">OSIV (Open Session in View)</a> is an anti pattern.</blockquote><p>😳🤓Wow…! super excited to up the server. we have done. So…, run the application and see.</p><p>Tomcat started on port(s): 8080 (http) with context path &#39;&#39;, you can see this in the terminal.</p><p>📌If you want to change port number 8080,server.port=3000 it should be added to the same file.</p><p><strong>IDEA with the terminal:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPFDcTRYBpU_ZFA-TGxhvg.png" /><figcaption>Image by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>Yeeah…! Finally, we did it.😍😎</p><p>Thank you all for following me. Hope to see you soon with another interesting article. If you have any unclear thing, please put a comment here. Until then bye to you…👋👋👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=427364f48245" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/connecting-a-springboot-application-to-a-postgresql-database-427364f48245">Connecting a SpringBoot Application to a PostgreSQL Database</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js API + MongoDB CRUD Operations | Part 04]]></title>
            <link>https://medium.com/linkit-intecs/node-js-api-mongodb-crud-operations-part-04-779d53496a0?source=rss-59081e8b5c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/779d53496a0</guid>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Nimasha Madhushani]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 01:25:59 GMT</pubDate>
            <atom:updated>2023-01-24T02:46:43.517Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*cZnt8j0UhKAMF2KC_LonQg.png" /><figcaption>Artwork by <a href="https://medium.com/@nimashamadhushani19">Author</a></figcaption></figure><p>This is <strong>Part 04 </strong>of the series of Node.js API + MongoDB CRUD Operations. If you didn’t read Part 01, Part 02, and Part 03, you are not late…</p><p>📝Here are the links, [<a href="https://medium.com/@nimashamadhushani19/node-js-api-mongodb-crud-operations-a3596a0775e8"><strong>Part 01</strong></a>] [<a href="https://medium.com/analytics-vidhya/node-js-api-mongodb-crud-operations-aceb3b1ab7f4"><strong>Part 02</strong></a>] [<a href="https://medium.com/@nimashamadhushani19/node-js-api-mongodb-crud-operations-c9fb5d3a4d44"><strong>Part 03</strong>]</a>.</p><p>In Part 01, we initiated our application and now our server is up on port 3000. Thereafter, the database is connected successfully with the application in Part 02. Then, in Part 03, we got an idea about the model, and controllers, and retrieve the data stored in the database by using the GET HTTP method.</p><p>Super cool guys…😎</p><p>Run npm start on an integrated terminal of your application.</p><p>Let’s have a look at retiring specific data and, storing the relevant data in the database.</p><p>To insert new employees into the <strong>employees collection…,</strong></p><p>🔷Call the method post.</p><p>🔷Call the function to handle the request.</p><p>🔷The request body should be converted to the JSON object.</p><p>📌employee.controller.js [Below post method is used to insert data]</p><pre>router.post(&quot;/&quot;, (req, res) =&gt; {<br>  //req.body<br>  Employee.create(req.body)<br>    .then((data) =&gt; res.send(data))<br>    .catch((err) =&gt; console.log(err));<br>});</pre><p>📌Finally, employee.controller.js with the GET method and POST method are mentioned below.</p><pre>const express = require(&quot;express&quot;);<br>const router = express.Router();<br><br>const Employee = require(&quot;../models/employees.model&quot;);<br><br>//GET method<br>router.get(&quot;/&quot;, (req, res) =&gt; {<br>  Employee.find()<br>    .then((data) =&gt; res.send(data))<br>    .catch((err) =&gt; console.log(err));<br>});<br><br><br>//POST method<br>router.post(&quot;/&quot;, (req, res) =&gt; {<br>  //req.body<br>  Employee.create(req.body)<br>    .then((data) =&gt; res.status(201).json(data))<br>    .catch((err) =&gt; console.log(err));<br>});<br><br><br>module.exports = router;</pre><blockquote>Ooops…!<em>🙄😵</em> Is this working? how can we confirm it?</blockquote><blockquote>Hi there, come here..and..click me, I’m <a href="https://www.postman.com/downloads/"><strong>Postman</strong></a><strong>.</strong></blockquote><blockquote>🚀The Postman platform includes a comprehensive set of tools that help accelerate the API lifecycle — from design, testing, documentation, and mocking to the sharing and discoverability of your APIs.</blockquote><blockquote>No worries, I’ll guide you to use this tool.</blockquote><blockquote>First, you have to download the postman software and install it on your machine. Then below interface will be visible to you.</blockquote><ol><li><strong>Click on the + icon to add a new collection</strong></li><li><strong>Right-click on “New Collection”</strong></li><li><strong>Click on “Add Request”</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SO7UNwPDg3oBolc6zagUOQ.png" /><figcaption>Artwork by <a href="https://medium.com/@nimashamadhushani19">Author</a></figcaption></figure><p>Now, a new request is in your newly created collection. So.., go through the below set of steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuhPPZO9cW6XOZ-73OdD_A.png" /><figcaption>Artwork by <a href="https://medium.com/@nimashamadhushani19">Author</a></figcaption></figure><blockquote><strong>1. Rename your request as you need. Here, I renamed it Insert Employee</strong></blockquote><blockquote><strong>2. Select “POST”, because here we are to save data in the database.</strong></blockquote><blockquote><strong>3. Select the “Body” tab.</strong></blockquote><blockquote><strong>4. Click on “row”</strong></blockquote><blockquote><strong>5. Select “JSON”</strong></blockquote><blockquote>✍JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for <strong>transmitting data in web applications.</strong></blockquote><p>🔶Copy the model you created in employees.model.js</p><p>🔶Wrap the property name with double quotes and provide the corresponding details.</p><pre>{<br>    &quot;fullName&quot;: &quot;Raveena&quot;,<br>    &quot;posiotion&quot;:&quot;Manager&quot;,<br>    &quot;location&quot;: &quot;Colombo&quot; ,<br>    &quot;salary&quot;:50000<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9-GSpvxg82vf17g6tWy7Q.png" /><figcaption>Artwork by <a href="https://medium.com/@nimashamadhushani19">Author</a></figcaption></figure><blockquote><strong>1. Insert the correct url [</strong><strong>path inside the </strong><strong>use() method in </strong><strong>index.js file and </strong><strong>port is also can be found in same file, inside the </strong><strong>listen() method] </strong>localhost:3000/api/employees</blockquote><blockquote><strong>2. Enter data to be inserted as key value pairs [JSON].</strong></blockquote><blockquote><strong>3. Click on “Save” button.</strong></blockquote><blockquote><strong>4. Click on “Send” button, to send the request.</strong></blockquote><p>Now, Status:201 is displayed. Oooh.., what is that 201?🤔🤔</p><blockquote><em>✅</em>Status: 201 → <strong>For a successful request and data was created</strong>.</blockquote><blockquote>The POST variables are stored as key-value pairs in the body.</blockquote><blockquote>So, can see the return object in the postman which returns by the success call back in the post controller as below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaWY91RvD07dpdR1pOFz1g.png" /><figcaption>Artwork by <a href="https://medium.com/@nimashamadhushani19">Author</a></figcaption></figure><p>Even though this says the request is successful, can we believe it…😏</p><p>So…, Refresh the DB. Now go to the browser and try the way we did in <a href="https://miro.medium.com/max/786/1*g0K40A8_xu7jtAxLPF953A.webp">Part 03</a>. At that time you <strong>received an empty array</strong>. Now, that inserted data is <strong>inserted into the array as an object </strong>as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QqUE6o_PjchnY-8ZGa6XQ.png" /><figcaption>image by author</figcaption></figure><blockquote>Then we can check it through the postman also by sending a GET request.</blockquote><blockquote>You can follow the above steps [we did in the POST request] to create a GET Request. [no need to add a request body, as we are to retrieve the data]</blockquote><blockquote>👻Keep it your mind to change the request type to GET .</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQYj0VxCULrsRCV-knuS-w.png" /><figcaption>image by author</figcaption></figure><p>✅Status: 200 OK → T<strong>he request was correct and the desired response has been sent to the client</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKmfFRhZHEg8mmPlk3AUWg.png" /><figcaption>image by author</figcaption></figure><p>Let’s retrieve a specific employee with the given id</p><p>Copy and paste the GET method as below.</p><pre>//GET method<br>router.get(&quot;/&quot;, (req, res) =&gt; {<br>  Employee.find()<br>    .then((data) =&gt; res.send(data))<br>    .catch((err) =&gt; console.log(err));<br>});</pre><p>💠To fetch specific data, <strong>parameter id</strong> should be included in the <strong>path </strong>get(“/:id”, .</p><p>💠And <strong>findById()</strong> method is used. Id which sends through the URL is accessed by the req parameter. findById(req.params.id)</p><p>💠If there is <strong>no id</strong> null value assigned to the data…,</p><p><strong>❗❓Then we have to handle it…</strong></p><p>The below condition can be used to check whether the null data is coming.</p><pre>if (data) {<br>        res.send(data);<br>      } else {<br>        res.status(404).json({<br>          error: &quot;no record with the given id&quot;,<br>        });<br>      }</pre><p>Now, you can have this implementation.</p><pre>router.get(&quot;/:id&quot;, (req, res) =&gt; {<br><br>  Employee.findById(req.params.id)<br>    .then((data) =&gt; {<br><br>      if (data) {<br>        res.send(data);<br>      } else {<br>        res.status(404).json({<br>          error: &quot;no record with the given id&quot;,<br>        });<br>      }<br><br>    })<br>    .catch((err) =&gt; console.log(err));<br>});</pre><p>Let’s check this API using postman.</p><p>We can get an id from one data object and use it to findById. Then I copy and paste the _id of fetched data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*budCwProd28uObT095Ip1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_RrT6j2A3nMAoEoHXsMOg.png" /><figcaption>image by author</figcaption></figure><blockquote>If we missed a character and the object _id is changed while copying and pasting, what will happen…?💥 Will try it…</blockquote><p>Now, I changed the <strong>last digit of the object_id</strong> 4 to 3. After sending the request, our error handling part is working smoothly and returns an error message as below by mentioning,</p><pre>{<br>    &quot;error&quot;: &quot;no record with the given id&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-COlYSAA_dPjqDMIFDa2-g.png" /><figcaption>image by author</figcaption></figure><blockquote>Now, I removed the last digit “4” of the object_id.</blockquote><blockquote>Oops! See below to be aware of the erroneous happened here.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsV-kd6qN5T7JQjfN9Fw3Q.png" /><figcaption>image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LOt0M-rPEr37qD2im_p6Kw.png" /><figcaption>image by author</figcaption></figure><blockquote>👁‍🗨reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer</blockquote><blockquote>Therefore, need to check whether the passed id is a <strong>valid object id.</strong></blockquote><blockquote>So, to that import the object Id from the mongoose as below.</blockquote><pre>const ObjectId = require(&quot;mongoose&quot;).Types.ObjectId;<br><br>router.get(&quot;/:id&quot;, (req, res) =&gt; {<br><br>  if (ObjectId.isValid(req.params.id) == false) {<br><br>    res.status(400).json({<br>      error: &quot;given object id is not valid&quot;,<br>    });<br><br>  } else {<br><br>    Employee.findById(req.params.id)<br>      .then((data) =&gt; {<br>        if (data) {<br>          res.send(data);<br>        } else {<br>          res.status(404).json({<br>            error: &quot;no record with the given id&quot; + req.params.id,<br>          });<br>        }<br>      })<br>      .catch((err) =&gt; console.log(err));<br><br>  }<br>});</pre><blockquote>Now, BSONTypeError<strong> won’t be received when the object_id type is changed</strong>, because we have handle it by checking whether the passing object_id is a valid one or not as below,</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTtg2QnssAFRaHeldiYn3Q.png" /><figcaption>image by author</figcaption></figure><blockquote><em>❎</em>Status: 400 Bad Request → Indicates that <strong>the server cannot or will not process the request due to something that is perceived to be a client error.</strong></blockquote><blockquote>Even though the object_id tye is valid, if there is no object_id which is found, the below error handling part will be worked.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5eM5THVD6aGS8TPKXMu_8A.png" /><figcaption>image by author</figcaption></figure><blockquote><em>❎ </em>Status: 404 Not Found → Response that indicates that <strong>the server won’t process the request because it is unable to locate the resource specified in the request</strong>.</blockquote><blockquote>So…, finally, our controller can POST data, GET all data in the DB and GET specific data in the DB. For that whole completed employees.controller.js file is as below.</blockquote><pre>const express = require(&quot;express&quot;);<br>const router = express.Router();<br><br>const ObjectId = require(&quot;mongoose&quot;).Types.ObjectId;<br><br>const Employee = require(&quot;../models/employees.model&quot;);<br><br>//GET method<br>router.get(&quot;/&quot;, (req, res) =&gt; {<br>  Employee.find()<br>    .then((data) =&gt; res.send(data))<br>    .catch((err) =&gt; console.log(err));<br>});<br><br>//POST method<br>router.post(&quot;/&quot;, (req, res) =&gt; {<br>  //req.body<br>  Employee.create(req.body)<br>    .then((data) =&gt; res.status(201).json(data))<br>    .catch((err) =&gt; console.log(err));<br>});<br><br>//GET method [get specific data]<br>router.get(&quot;/:id&quot;, (req, res) =&gt; {<br>  if (ObjectId.isValid(req.params.id) == false) {<br>    res.status(400).json({<br>      error: &quot;given object id is not valid&quot;,<br>    });<br>  } else {<br>    Employee.findById(req.params.id)<br>      .then((data) =&gt; {<br>        if (data) {<br>          res.send(data);<br>        } else {<br>          res.status(404).json({<br>            error: &quot;no record with the given id&quot; + req.params.id,<br>          });<br>        }<br>      })<br>      .catch((err) =&gt; console.log(err));<br>  }<br>});<br><br>module.exports = router;</pre><p>🎃 <strong>Source Code: </strong><a href="https://github.com/Nimasha-Madhushani/NodeJS-Rest-API"><strong>https://github.com/Nimasha-Madhushani/NodeJS-Rest-API</strong></a></p><p>I think we need a break and it is better to continue with Part 05. 😋 So, practice these things. If you have anything to clarify, please drop a comment under this post or send a private note.</p><p>Thank you all my guys for staying with me 💖💖</p><p>Until then Bye for All 👋👋👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=779d53496a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/node-js-api-mongodb-crud-operations-part-04-779d53496a0">Node.js API + MongoDB CRUD Operations | Part 04</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection in Spring Boot]]></title>
            <link>https://medium.com/linkit-intecs/dependency-injection-in-spring-boot-68fea4747e87?source=rss-59081e8b5c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/68fea4747e87</guid>
            <category><![CDATA[spring-framework]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[blogging]]></category>
            <dc:creator><![CDATA[Nimasha Madhushani]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 02:13:12 GMT</pubDate>
            <atom:updated>2023-01-24T02:58:05.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*JIsrEr1E6OGSgJmKRbEkoA.png" /><figcaption>Artwork by <a href="https://nimashamadhushani19.medium.com/">Author</a></figcaption></figure><p>Hi Enthusiasts…..,🤗</p><p>Java programming has never been quicker, simpler, or safer thanks to Spring😎. Spring is the most widely used Java framework in the world because of its emphasis on productivity, speed, and simplicity. Furthermore, it helps solve real-time technical problems.</p><p>So.., here we go to get a better understanding of dependency injection and how it can be used in Spring Framework…,</p><h4>📝 What is Spring Framework?</h4><blockquote>Spring is a <strong>lightweight framework.</strong></blockquote><blockquote><em>🟢 </em>The conceptual weight of a framework is referred to as “lightweight” in this sentence. A lightweight framework like Spring has little impact on an application.</blockquote><blockquote>It might be considered a framework of frameworks since it supports several different frameworks, including <strong>Struts, Hibernate, Tapestry, EJB, JSF,</strong> etc. In a deeper context, the framework can be described as a structure where we attempt to solve numerous technological issues.</blockquote><blockquote><strong><em>🟣 </em>Struts — open source framework that extends the Java Servlet API and employs a Model, View, Controller (MVC) architecture</strong>. It enables you to create maintainable, extensible, and flexible web applications based on standard technologies</blockquote><blockquote><strong><em>🟣 </em>Hibernate — ORM tool used for saving the state of the Java object in the database. </strong>By default, Spring uses Hibernate as the default JPA vendor.</blockquote><blockquote><strong><em>🟣 </em>Tapestry — Open-source framework for developing Java web applications that are dynamic, reliable, and highly scalable.</strong> Tapestry works in any servlet container or application server since it enhances and expands upon the standard Java Servlet API.</blockquote><blockquote><strong><em>🟣 </em>EJB[Enterprise Java Beans] —Development architecture for building highly scalable and robust enterprise level applications.</strong></blockquote><blockquote><strong><em>🟣 </em>JSF[Java Server Faces] —</strong> <strong>Java-based web application framework intended to simplify development integration of web-based user interfaces.</strong></blockquote><blockquote>🌀 The essential component of Spring Framework is Spring<strong> IoC Container</strong>. It <strong>generates the objects</strong>, <strong>sets up and assembles their dependencies</strong>, and <strong>controls every aspect of their life cycle</strong>. To handle the parts that make up the application, the container makes advantage of<strong> Dependency Injection (DI)</strong>.</blockquote><h4>📝 What is Dependency Injection?</h4><blockquote><strong>Dependency injection (DI), which is used in the design of software using object-oriented programming (OOP), involves providing a resource that a specific piece of code needs. The needed resource is known as dependence, and it is frequently an element of the application itself.</strong></blockquote><blockquote>If a software component needs to communicate with other resources in order to fulfill its intended function, it must be aware of other resources’ identities, locations, and communication protocols. Mapping the locations of each necessary resource is one method of arranging the code. Another approach is to implement dependency injections and delegate the task of locating the resources to an external piece of code.</blockquote><p>📌 <strong>There are 3 types of dependency injections.</strong></p><ol><li>Constructor-Based Dependency Injection</li><li>Setter-Based Dependency Injection</li><li>Field-Based /Property-Based Dependency Injection</li></ol><h4>📝 <strong>How to use Dependency Injection?</strong></h4><h4>📚 Constructor-Based Dependency Injection</h4><p>Constructors are used to inject the dependency.</p><p>📌 Heart.java</p><pre>import org.springframework.stereotype.Component;<br><br>@Component<br>public class Heart {<br>    public void pumpBlood() {<br>        System.out.println(&quot;Pumping Blood&quot;);<br>    }<br>}</pre><p>📌 Human.java</p><pre>import jakarta.annotation.PostConstruct;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class Human {<br>    private Heart heart;<br><br>    public Human(Heart heart) {<br>        this.heart = heart;<br>    }<br><br>    @PostConstruct<br>    public void Sound() {<br>        heart.pumpBlood();<br>    }<br>}</pre><h4>@PostConstruct</h4><blockquote><em>🔷 </em>When the Spring Framework creates/initializes a particular bean.</blockquote><blockquote><em>🔷 </em>Then after, the method which belongs to this @PostConstructshould be executed.</blockquote><h4>@Component</h4><blockquote><em>🔷 </em>Automatically detect custom beans.</blockquote><blockquote><em>🔷 </em>Scan the application for classes annotated with <em>@Component</em></blockquote><blockquote><em>🔷 </em>Instantiate them and inject any specified dependencies into them</blockquote><blockquote><em>🔷 </em>Inject them wherever needed.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*TJN1Bm8D9gopQS6ERlpdWg.png" /><figcaption>image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ICOv_pqHwkAKbmw2w0XAtg.png" /><figcaption>image by author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*BPwH_KYsP1jBDuYFYf2_XA.png" /><figcaption>image by author</figcaption></figure><h4>📚Setter-Based Dependency Injection</h4><p>Setters are used to inject the dependency.</p><p>📌 Heart.java</p><pre>import org.springframework.stereotype.Component;<br><br>@Component<br>public class Heart {<br>    public void pumpBlood() {<br>        System.out.println(&quot;Pumping Blood&quot;);<br>    }<br>}</pre><p>📌 Human.java</p><pre><br>import jakarta.annotation.PostConstruct;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class Human {<br>    private Heart heart;<br><br>    public Heart getHeart() {<br>        return heart;<br>    }<br>    @Autowired<br>    public void setHeart(Heart heart){<br>        this.heart=heart;<br>    }<br><br>    @PostConstruct<br>    public void Sound() {<br>        this.heart.pumpBlood();<br>    }<br>}</pre><h4>@Autowired</h4><blockquote><em>🔷 </em>If have only one constructor this annotation is not required.</blockquote><blockquote><em>🔷 </em>Implementation is wired using this annotation. Autowire spring bean on setter methods, instance variable and constructor.</blockquote><h4>📚 Field-Based /Property-Based Dependency Injection</h4><p>The property of the variable is used to inject the dependency.</p><p>📌 IRun.java <em>[ Interface]</em></p><pre>public interface IRun {<br>    void run();<br>}</pre><p>📌 Cat.java</p><pre>import org.springframework.stereotype.Component;<br><br>@Component(&quot;Cat&quot;)<br>public class Cat implements IRun {<br>    @Override<br>    public void run() {<br>        System.out.println(&quot;Cat runs...&quot;);<br>    }<br>}</pre><p>📌 Dog.java</p><pre>import org.springframework.stereotype.Component;<br><br>@Component(&quot;Dog&quot;)<br>public class Dog implements IRun{<br>    @Override<br>    public void run(){<br>        System.out.println(&quot;Dog runs...&quot;);<br>    }<br>}</pre><p>📌 Human.java</p><pre>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.beans.factory.annotation.Qualifier;<br>import org.springframework.stereotype.Component;<br><br>@Component<br>public class Human {<br>    @Qualifier(&quot;Dog&quot;)<br>    @Autowired<br>    private IRun run;<br>}</pre><blockquote><em>🟢 </em><strong>@Qualifier annotation</strong> is used <strong>to resolve the autowiring conflict, when there are multiple beans of same type.</strong></blockquote><blockquote><strong><em>🟡 </em>“A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.”</strong></blockquote><blockquote>Here, Beans of IRun type,</blockquote><blockquote><em>🔹 </em>Beans : Cat</blockquote><blockquote><em>🔹 </em>Beans : Dog</blockquote><blockquote>Therefore, now Sping cannot separately identify two beans. Then we can apply @Qualifier annotation as the solution.</blockquote><p>Yeeeah…., A little bit lengthy article. So….., it’s time to have a break…😊</p><p>I will bring you a mini blog with different annotations that we can use in Spring Framework and their uses as well.❣❣❣❣❣❣</p><p>Untill then have a nice day… ,Bye..Bye….👋👋👋👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68fea4747e87" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/dependency-injection-in-spring-boot-68fea4747e87">Dependency Injection in Spring Boot</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Upgrade or Downgrade the node Version?]]></title>
            <link>https://medium.com/linkit-intecs/how-to-update-node-js-and-npm-42b8bf3cabe6?source=rss-59081e8b5c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/42b8bf3cabe6</guid>
            <category><![CDATA[downgrade]]></category>
            <category><![CDATA[compatibility]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nvm]]></category>
            <category><![CDATA[upgrade]]></category>
            <dc:creator><![CDATA[Nimasha Madhushani]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 18:36:27 GMT</pubDate>
            <atom:updated>2024-02-17T11:06:16.763Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Downgrade Node Version or Upgrade Node Version in Windows?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*FO9BuTD6VuYt4_d76miQBw.png" /><figcaption>Artwork by <a href="https://medium.com/@nimashamadhushani19">Author</a></figcaption></figure><p>Hi Techies…😎 Here is a <strong>mini blog</strong> post for you. Now, the latest Angular version is <strong><em>Angular 15</em></strong>. And…., <strong><em>LTS v18.13.1</em></strong> is the latest stable node version. But, if you are working on Angular 14, the latest node version is unsupported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*ieXrzs4ENi2NhHpauZY5dg.png" /><figcaption>image by author</figcaption></figure><blockquote><em>🟣 </em>Node v18.13.0 (LTS) was released on 2023–01–06, so it was <strong>after</strong> the release of Angular 15.0.0 (2022–11–16). As a consequence Angular 15.0.0 only guarantees compatibility with Node 18.10.x.</blockquote><p>So……, What we can do is….searching for a compatible node version for Angular 14🤗.</p><blockquote><em>🟢 </em>Here is the link to <a href="https://gist.github.com/LayZeeDK/c822cc812f75bb07b7c55d07ba2719b3">angular-cli-node-js-typescript-rxjs-compatibility-matrix.csv</a> .</blockquote><h4>Steps to <strong>downgrade node version</strong>:</h4><p>🔹 Run command prompt as administrator.</p><p>🔹 Then, check the installed node version by using node -v.</p><p>🔹 Now, you have to install nvm. You can download the NVM executable file (nvm-setup.exe) by this <a href="https://github.com/coreybutler/nvm-windows/releases"><strong><em>Link</em></strong></a> and install it on your machine.</p><p>📋 What is <strong>NVM</strong>?</p><ul><li><strong><em>NVM, short for Node Version Manager, is a command line tool for managing and switching to different versions of Node.js.</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76WVmnpITydnpo4_XbrTmQ.png" /><figcaption>image by author</figcaption></figure><p>🔹 Then for Windows and nvm, the command is: nvm install &lt;version&gt;.</p><p>🔹 Now you have to check the nvm list installed on your machine. To that run nvm list in your command prompt.</p><p>🔹 After that, it shows which version is “<strong>Currently using a 64-bit executable”.</strong></p><p>🔹 Then you can switch it to the version that you are expecting by nvm use &lt;version&gt;.</p><p>🔹 Now command prompt will show as below,</p><h4>📌 Command prompt:</h4><pre>C:\Users\Acer&gt;nvm -v<br>1.1.10<br><br>C:\Users\Acer&gt;nvm install v16.10.0<br>Downloading node.js version 16.10.0 (64-bit)...<br>Extracting node and npm...<br>Complete<br><br>C:\Windows\system32&gt;nvm list<br>    18.12.1<br>    16.16.0<br>    16.10.0<br>  * 14.17.3 (Currently using 64-bit executable)<br><br>C:\Windows\system32&gt;nvm use 16.16.0<br>Now using node v16.16.0 (64-bit)<br><br>C:\Windows\system32&gt;node -v<br>v16.16.0<br><br>C:\Users\Acer&gt;nvm list<br>    18.12.1<br>  * 16.16.0 (Currently using 64-bit executable)<br>    16.10.0<br>    14.17.3</pre><ul><li>Now, you can see * 16.16.0 (Currently using 64-bit executable).</li></ul><h4>📋 What is <strong>Node.js</strong>?</h4><blockquote><strong>“ Node.js® is an open-source, cross-platform JavaScript runtime environment.”</strong></blockquote><blockquote>To install: <a href="https://nodejs.org/en/"><strong>Node.js</strong></a></blockquote><blockquote>[18.13.0 LTS is recommended you to download because the stability is higher than the current node version with the latest features ]</blockquote><h4>📋 What is <strong>npm</strong>?</h4><blockquote><strong>“npm</strong> is the <strong>package manager</strong> for the Node JavaScript platform. It puts modules in place so that node can find them, and <strong>manages dependency conflicts intelligently</strong>. It is extremely configurable to support a wide variety of use cases. Most commonly, it is used <strong>to publish, discover, install, and develop node programs.”</strong></blockquote><p><strong>🔷 Upgrade</strong> — “<em>An upgrade is a whole new version of the software that represents a significant change or major improvement.”</em></p><p><strong>🔷 Downgrade</strong> —<em>“Downgrading refers to reverting software (or hardware) back to an </em><strong><em>older version</em></strong><em>; </em><strong><em>downgrade is the opposite of upgrade</em></strong><em>. Programs may need to be downgraded to remove introduced bugs, restore useful removed features, and increase speed and/or ease of use.”</em></p><p>I think now you can upgrade or downgrade node versions installed in your machines.😎</p><p>A mini blog should be a mini blog… 😜. Hope to see you soon with another important topic. If you need further clarification please put a comment…</p><p>So…., Good Byee…👋👋👋👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42b8bf3cabe6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/linkit-intecs/how-to-update-node-js-and-npm-42b8bf3cabe6">How to Upgrade or Downgrade the node Version?</a> was originally published in <a href="https://medium.com/linkit-intecs">LinkIT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>