<?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 Kavindaperera on Medium]]></title>
        <description><![CDATA[Stories by Kavindaperera on Medium]]></description>
        <link>https://medium.com/@kavindaperera25?source=rss-63f683205b88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RTLvfU_phgV3Ncm0</url>
            <title>Stories by Kavindaperera on Medium</title>
            <link>https://medium.com/@kavindaperera25?source=rss-63f683205b88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:15:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kavindaperera25/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[BASIC FUNDAMENTALS OF DATA STRUCTURE]]></title>
            <link>https://medium.com/@kavindaperera25/basic-fundamentals-of-data-structure-e3cfb8cc2764?source=rss-63f683205b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3cfb8cc2764</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <category><![CDATA[depth-first-search]]></category>
            <dc:creator><![CDATA[Kavindaperera]]></dc:creator>
            <pubDate>Sun, 10 Apr 2022 23:08:19 GMT</pubDate>
            <atom:updated>2022-04-10T23:08:19.515Z</atom:updated>
            <content:encoded><![CDATA[<h4>Breadth First Search(BFS) and Depth First Search(DFS)</h4><p>If you need to be a software engineer, you require good problem-solving knowledge. Coding only doesn’t make you a software engineer; therefore. As a result, the upcoming articles will be about data structure fundamentals. In this article, we will mainly focus on BFS and DFS and how we can implement them in java. If you haven’t gone through my previous <a href="https://medium.com/@kavindaperera25">articles, </a>please do. It will help you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q2gLKEYrjFeJY1Kxg6tUpA.png" /><figcaption>Basic Fundamentals Of Data Structure</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*6fLE0RTiVRca1vUM90Tu6A.png" /></figure><p>Bread first search is a traversing algorithm. In a breadth-first search graph, traversal means visiting every vertex precisely once in a defined order. You must ensure that every vertex of the graph is visited exactly once. You can select any node as the source (Starting note) and traverse the graph layer-wise, thus exploring the neighbor nodes(nodes directly connected to the source node). If we require to implement bread first search, we can do that by using a queue.</p><p>The <strong>rule </strong>of breadth-first search is that you can start from any vertex, which is optional, but you are required to explore every neighbor vertex precisely one time.</p><p>There are two types of graphs: directed and undirected graphs. The directed graph simply specifies in which direction you should traverse. Other than that, there is no further alteration. Whereas the undirected graph stipulates that you can travel through the graph in any direction</p><h3>QUEUE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*ZLRD_OgmXaJZh7zZ5KJsuw.png" /><figcaption>Queues</figcaption></figure><p>A queue is a common data structure that places elements in a sequence that is pretty much similar to stacks. However, queues follow a first in, first out mechanism(FIFO), whereas the stack follows a last in first out(LIFO). In a queue, the first element that has been inserted (enqueued) is the first element that has been removed (dequeued). For example, you can consider a whole line of people waiting in the supermarket to purchase food. Whoever is the first person to come into the line will get the food first and likewise. Therefore, whatever the first element to be inserted in the same element is to be removed first as well.</p><h4>Demonstration of how breadth-first search algorithm works on an undirected graph</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*SgpUsG41INKmtIiUPCtC3w.png" /><figcaption>Breadth First Search</figcaption></figure><p>Let’s see how we can traverse through this graph. First, assuming that we start with A. (source node).</p><p>Initially, we insert the <strong>A</strong> into the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*84_lUaIYDhVa1nCwfAdIWg.png" /><figcaption>Queue initial step(A inserted)</figcaption></figure><p>The <strong>A</strong> is taken out from the Queue, and then the neighboring vertex is explored. As you can see, now we can reach vertex <strong>B</strong> and <strong>C</strong>. As a result, these two vertexes are inserted or enqueued into the Queue.</p><p><strong>Traversing path = A</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*mvHLprFBgaVu2Xr4LwR3-A.png" /><figcaption>Queue(Now A is taken out and Band Cis inserted)</figcaption></figure><p>Next in our queue is <strong>B</strong>. As a result, we take the <strong>B </strong>out from the queue. The <strong>B </strong>is only connected to the vertex <strong>D </strong>(Neighboring vertex). Thus the <strong>D </strong>vertex is inserted(enqueued) in the queue.</p><p><strong>Traversing path = A,B</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*Amqbpi2T72076K373ljXMA.png" /><figcaption>Queue (B is taken out and insert D)</figcaption></figure><p>Now the vertex <strong>C </strong>is taken out from the queue, and we can see that the neighboring vertexes of <strong>C </strong>are <strong>E</strong> and <strong>H</strong>. Thus, the vertex <strong>E </strong>and <strong>H </strong>are inserted into the queue</p><p><strong>Traversing path = A,B,C</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*EVb31utbIZ89bhy9ZfOcKA.png" /></figure><p>Now once the vertex <strong>D </strong>is taken out. There are no more neighboring vertexes of <strong>D</strong>. As a result. Nothing will be inserted(Enqueued) into the queue.</p><p><strong>Traversing path = A,B,C,D</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*OIuHtHdZ8GeQO3_zCzi4RA.png" /></figure><p>Once the vertex <strong>E </strong>is taken out from the queue, you can reach the vertex <strong>F </strong>and <strong>I </strong>since it is their neighbors. As a result, the vertex <strong>F </strong>and I will be inserted into the queue.</p><p><strong>Traversing path = A,B,C,D,E</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*9hwr67_Ax-aSaO_VBskfDQ.png" /></figure><p>Now the vertex <strong>H </strong>is taken out, and from the <strong>H </strong>vertex, you can reach the vertex <strong>G</strong>. As a result, the vertex <strong>G </strong>is inserted(Enqueued) into the queue.</p><p><strong>Traversing path = A,B,C,D,E,H</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*qRd-Q89Bhg0E-DUucpk1Lw.png" /></figure><p>Next, the vertex <strong>F </strong>is taken out from the queue, and from vertex <strong>F</strong>, you can reach vertex <strong>G</strong>, but this vertex <strong>G </strong>is already inserted into the queue. As a result, nothing will be inserted into the queue. Simply the vertex <strong>F </strong>will be removed from the queue.</p><p><strong>Traversing path = A,B,C,D,E,H,F</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*DExUNOs7F3EJFOW6U53hJA.png" /></figure><p>You cannot reach any vertex from vertex <strong>I</strong>; therefore, nothing will get inserted as a result you remove the vertex I from the queue.</p><p><strong>Traversing path = A,B,C,D,E,H,F,I</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*d790YWeQQt6T7oQgItc-eA.png" /></figure><p>You cannot reach any vertex from vertex <strong>G</strong>; therefore, as a result you remove vertex <strong>G </strong>from the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*TwvfKxZIZ8iV1G1Ak0UK4A.png" /></figure><p><strong>Traversing path = A,B,C,D,E,H,F,I,G</strong></p><p><strong>Bread first search for this graph(undirected)</strong> is A,B,C,D,E,H,F,I,G</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*-qMD3hylCQ6xnpTUM_tSMQ.png" /></figure><p><a href="http://en.wikipedia.org/wiki/Depth-first_search">D</a>epth First Search(DFS) algorithm traverses a graph in a depth ward motion. <strong>This algorithm can be implemented with a stack. So why we can’t implement it with queue? </strong>Good question. This is because, in this graph, we need to reach the depth of vertexes. As a result, all the previous vertexes should be known to go back (whereas queues use a FIFO principle. As a result, we cannot implement this with the queue).</p><p><strong>Rule 1</strong> − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.</p><p><strong>Rule 2</strong> − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the vertices from the stack which do not have adjacent vertices.)</p><p><strong>Rule 3</strong> − Repeat Rule 1 and 2 until the stack is empty.</p><h3><strong>STACK</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*-uBYZQu2j7uOquk6EIdJYQ.png" /><figcaption>Stack of plates</figcaption></figure><p>Stack is another highly used data structure. Stack is a linear data structure that follows a particular order in which the operations are carried out. For example, they follow the order of FILO(First In, Last out). In stack, the first element inserted, aka the first element pushed, is the last element to be removed (pop). For example, you can imagine a stack of plates — one plate on top of another plate. To reach and take the last plate, all the plates on top should be removed. This is the principle that the stack follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*rOPyRu5PI2bcoOPJbBVCCQ.png" /></figure><h4>Demonstration of how depth-first search algorithm works on an undirected graph</h4><p>You can start with any vertex you prefer, but I will be starting with vertex <strong>0</strong>. You will insert it into the stack since you start with the vertex <strong>0</strong>. You can decide which path you want to go from that point onwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*q_iU_0oNZr4yNNkmTXeDuQ.png" /></figure><p><strong>DFS= 0</strong></p><p>Now I can go to path <strong>4 </strong>as well as path <strong>2</strong>. It is totally up to you. For this example, I will be going to path <strong>4</strong>. As a result, you insert four into the stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*F64U-72gMBycUWDomUbdwQ.png" /></figure><p><strong>DFS = 0,4</strong></p><p>Next, you can reach <strong>3 </strong>and insert <strong><em>3</em> </strong>into the stack once again. When you reach <strong>3 </strong>you can again decide which way you want to go. For this example, we reach vertex <strong>8</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*VThjizkdtiudgcXceSdp_Q.png" /></figure><p><strong>DFS = 0,4,3,8</strong></p><p>You reach the end by pushing the vertexes into the stack. Once you reach the end, there is no more vertex left. As a result, you start to go back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*G6AsNihptH18xkXJMjHnKw.png" /></figure><p><strong>DFS=0,4,3,8,6,7</strong></p><p>Once you start to come back, you see in the vertex <strong>3 </strong>another path to vertex <strong>5</strong> that has not been visited. As a result, we do not remove vertex <strong>3</strong> instead of removing vertex <strong>3 </strong>we visit vertex <strong>5</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*KVzvBoCPofnZqYzCHQcjdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*dJ9hyQCrbwgoKj5m9fUf3g.png" /></figure><p><strong>DFS=0,4,3,8,6,7,5</strong></p><p>Once again, you start to reverse the process and come back by popping the elements out of the stack. At vertex <strong>0</strong>, you see there is another path to vertex <strong>2</strong>, which is not visited; therefore, without removing vertex <strong>0,</strong> we call vertex <strong>2</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*GQS0df4eelHtCMeLCf63BA.png" /></figure><p>Over here, we reach vertex <strong>2 </strong>then we go and reach vertex <strong>1 </strong>as a result, we push these elements into the stack. All the elements have been reached; therefore, we pop everything out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*aG7E7Cjzq21wPJkuPQm2SQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*1lYOn01ZPTFzWKDf9gAm9w.png" /></figure><p><strong>DFS=0,4,3,8,6,7,5,2,1</strong></p><h3><strong>REFERENCES</strong></h3><p><a href="https://www.youtube.com/watch?v=aMCI4AqVUug">How to Think as a Software Engineer | Part 01 — YouTube</a></p><p>Youtube.com. 2022. [online] Available at: &lt;https://www.youtube.com/watch?v=aMCI4AqVUug&gt; [Accessed 9 April 2022].</p><p>GeeksforGeeks. 2022. <em>Stack Data Structure — GeeksforGeeks</em>. [online] Available at: &lt;https://www.geeksforgeeks.org/stack-data-structure/#:~:text=Stack%20is%20a%20linear%20data,(First%20In%20Last%20Out).&gt; [Accessed 9 April 2022].</p><p>En.wikipedia.org. 2022. <em>Stack (abstract data type) — Wikipedia</em>. [online] Available at: &lt;https://en.wikipedia.org/wiki/Stack_(abstract_data_type)&gt; [Accessed 9 April 2022].</p><p>Tutorialspoint.com. 2022. <em>Data Structure and Algorithms — Stack</em>. [online] Available at: &lt;https://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm&gt; [Accessed 9 April 2022].</p><p>GeeksforGeeks. 2022. <em>Queue Data Structure — GeeksforGeeks</em>. [online] Available at: &lt;https://www.geeksforgeeks.org/queue-data-structure/&gt; [Accessed 9 April 2022].</p><p>En.wikipedia.org. 2022. <em>Queue (abstract data type) — Wikipedia</em>. [online] Available at: &lt;https://en.wikipedia.org/wiki/Queue_(abstract_data_type)&gt; [Accessed 9 April 2022].</p><p>2022. [online] Available at: &lt;https://www.merriam-webster.com/dictionary/queue&gt; [Accessed 9 April 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3cfb8cc2764" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is immutability?]]></title>
            <link>https://medium.com/@kavindaperera25/what-is-immutability-bdec16d20a2b?source=rss-63f683205b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdec16d20a2b</guid>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[string]]></category>
            <category><![CDATA[objects]]></category>
            <dc:creator><![CDATA[Kavindaperera]]></dc:creator>
            <pubDate>Fri, 08 Apr 2022 04:33:00 GMT</pubDate>
            <atom:updated>2022-04-08T04:33:00.432Z</atom:updated>
            <content:encoded><![CDATA[<h4>Is string immutable?</h4><p>What does immutability mean? Any idea? This question is one of the most highly asked during the interview. To know what immutability is, I advise you to go back and look at my previous article, especially my JVM <a href="https://medium.com/@kavindaperera25/everything-you-need-to-know-about-java-fundamentals-df740ed88cba">article</a>. During this article, we will mainly focus on what immutability is and its advantage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DCH9xeTUCpvdBZsmKkM2ug.png" /><figcaption>What is Immutability</figcaption></figure><h3>What is meant by immutability?</h3><p>The immutable means that once an object has been created, you cannot change or modify it. But then again, you may doubt that once you have declared a string variable and later on in the code, you change the value of that string variable, yet you can still compile without any error? Is that so? Don’t worry. We will take a close look at it.</p><p><strong>We need to know how this is implemented internally to understand this fully.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*ONUrIdce6cai0HPgQHT_wA.png" /><figcaption>String Name= “KAVINDA”</figcaption></figure><p>Assume that we have a string variable called Name. We initialize this name variable to “Kavinda” .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*zWiXAUyUSFoWtf5OY4FUsw.png" /><figcaption>Name = “KAVI”</figcaption></figure><p>Assume that later the user decides to change the string variable name value-form KAVINDA to KAVI, Which is pretty much valid and capable of compiling without any error. So why do you say String is immutable? You need to understand that over here, what we do is that we change the value of the variable name. You don’t make any changes or modifications to the object. Let’s take a look at how this works internally to understand this concept more</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*duJbB5lhBfZ6J6KpYvFfYw.png" /><figcaption>We change the value not doing any modification to the object</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*82KDE-tadrCV620Bl4E1Ag.png" /><figcaption>Output</figcaption></figure><p><strong>HOW DOES THIS WORK INTERNALLY!</strong></p><p>The JVM consists of method area/heap area, stack, native method, and pc registers. When an object is created, it is stored in a heap. If you do not remember how the JVM works please do a look at this <a href="https://medium.com/@kavindaperera25/everything-you-need-to-know-about-java-fundamentals-df740ed88cba">article</a>. In this case, the JVM, is responsible for creating the object in a heap(KAVINDA). After that, the JVM sets the value to name(variable) by pointing the name variable into the KAVINDA’S object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*mk5IV9FXpIqK6yUOmwk6jA.png" /><figcaption>Name variable is now referenced to the object in the heap(KAVINDA)</figcaption></figure><p>So now, the user has decided to change the variable name value to “KAVI” instead of “KAVINDA.” Therefore now, the JVM creates a new object called KAVI. Now the variable (name) is being dereferenced from the object KAVINDA, and then the variable is being referenced to the object KAVI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*4I5krYyWzHR3R3eIy2nQqw.png" /><figcaption>Now the variable name is being dereferenced from KAVINDA object and it is being referenced to KAVI object.</figcaption></figure><p>As you can see, the object isn’t being modified. What we do is change the value. When the user changes the variable(name) value, the JVM creates a new object, and now the variable will be pointing to this new object. These objects can be stored in different memory addresses.</p><h3>What are the benefits of immutability? Why string is immutable?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*XIdB9KhLuvAVn8B-0aPgFg.png" /><figcaption>3 VARIABLES (dog1,dog2,dog3) with same name “DODO”</figcaption></figure><p>For this example lets assume we create three variables (like dog1, dog2, dog3) and all those 3 variables have the same name which is “DODO”</p><p>In java, the string is the most used data type, and as a result, java consists of a string pool which is used to improve performance(to get things done sooner). Now let’s assume that the variable dog1 uses 4bytes to store the value. Since there are 3 variables(dog1,dog2,dog3) we require 12 bytes in the memory(Assuming that the three variables having the same value). In other words, the number of variables created requires more space(bytes) in the memory. Instead of doing this, java does that once the dog1 variable is created, the “DODO” object is been created on the heap. Now the dog1 variable is pointing to the DODO object. Now once the dog2 is created, it does something tricky that is instead of creating another new object in a heap, it points to the same initial object. The same scenario goes with dog3. There are three variables, but java creates just one object(since it has the same value), and these three variables will be the point to this single object. As a result you can see that we are capable of saving up the space (or memory) due to the face that string is immutable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*jgZ2c0IyFhjHYTkHb5bQnA.png" /></figure><h3>What happens in this scenario ? Any Ideas?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*eMHfqTwlw4IApc2U7K3Jqw.png" /><figcaption>Creating a new string object in a different way</figcaption></figure><p>This command works differently. This command specifies explicitly creating a new object instead of pointing to or referencing an object which was created before. In other words, instead of pointing to the same object, it will create a new object in a heap, and then the variable will be pointed to the new object that has been created.</p><h3>THREAD SAFE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*DrneRAxf76VvWkOOI8cn0w.png" /></figure><p>During this scenario, we have a variable called dog1, which points to the object in string pool “DODO.” Now we have another variable which is dog2, that is also being pointed to the same object, “DODO.” After some time, the user decides to change the dog1 value from “DODO” to “RUBIE.” As a result, the new object “RUBIE” has been created in the string pool, and now the dog1 is being dereferenced from “DODO” and reference to “RUBIE.” But still, the dog2 is referenced to the object “DODO.” As a result, this would lead to a thread-safe issue.</p><p>Assuming that a method uses the name as the parameter to do some crucial coding execution, another thread could change the name if it is not thread-safe. In other words, someone can alter the object’s value you are referencing. In this case if the java is not immutable someone could simply access and change the object to another value.</p><blockquote>If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why String objects are immutable in Java.</blockquote><blockquote>Since the internal state of an immutable object remains constant in time, <strong>we can share it safely among multiple threads</strong>.</blockquote><h3>REFERENCES</h3><p><a href="https://www.youtube.com/watch?v=jK1Ik8q0lyM&amp;t=356s">Why is immutability matters ? — YouTube</a></p><p><a href="http://www.javatpoint.com./">www.javatpoint.com.</a> 2022. <em>Immutable String in Java — javatpoint</em>. [online] Available at: &lt;https://www.javatpoint.com/immutable-string&gt; [Accessed 8 April 2022].</p><p>dzone.com. 2022. <em>Java Immutable Objects — DZone Java</em>. [online] Available at: &lt;https://dzone.com/articles/java-immutable-objects&gt; [Accessed 8 April 2022].</p><p>2022. [online] Available at: &lt;https://www.baeldung.com/java-immutable-object&gt; [Accessed 8 April 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdec16d20a2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HOW JAVA LIBARY CAN BE USED!]]></title>
            <link>https://medium.com/@kavindaperera25/how-java-libary-can-be-used-d1811b417da6?source=rss-63f683205b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1811b417da6</guid>
            <category><![CDATA[java-library]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Kavindaperera]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 02:00:18 GMT</pubDate>
            <atom:updated>2022-04-04T02:00:18.187Z</atom:updated>
            <content:encoded><![CDATA[<h4>Head First Java Chapter 06</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R5XZbleKp7N-B5iV4OZV5g.png" /><figcaption>Java Library</figcaption></figure><p>Java is built with hundreds and thousands of pre-built classes. As a result, it provides the developers with some flexibility without having not to reinvent the wheel. Using pre-build classes in the library, aka Java API, you can write or change the parts that truly customize the application without writing the entire code. Additionally, in this article, we will try to develop an advanced game (Make our previous game advance). I advise you to go through the previous articles to gain more insights about java and how it works before coming to java Libraries. You can click on the following <a href="https://medium.com/@kavindaperera25/">link </a>and check the articles in order.</p><h3>ArrayList</h3><p>Array List is a class in the core Java library(the API). By declaring an array list, it can expand and shrink as you add and remove elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*KB3qmusQ5ZrLQcMuIqJSMQ.png" /><figcaption>Most common used methods in array List</figcaption></figure><h3><strong>Some of the most commonly used methods with Array List are</strong></h3><p><strong><em>How to create Array List Object (For This example, We create an array list of fish ):</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQgxn1ZjN9M3dDk32bTDEg.jpeg" /><figcaption>Creating An ArrayList.</figcaption></figure><p><strong><em>Adding a value to the newly created array List(in this example, we add an object type since our array list is an object type of fishes).</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*-4Uz0skMtytveasg5-HYAg.jpeg" /><figcaption>Adding an object to the arrayList</figcaption></figure><p><strong><em>This method is used to remove an item in the ArrayList.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*nsPGZLXPtd-vf0c7GwJGEw.jpeg" /></figure><p><strong><em>Size Method is used to identify how many items are presented in the array List.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*T5HGOjmKeNeYbZKOgNCMmw.jpeg" /><figcaption>Size Method To identify how many items in the arrayList</figcaption></figure><p><strong><em>The ArrayList DOES contain the fish object referenced by ‘s’, so contains() returns true</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*IEXeds2TwppC0LvFlLFZFg.jpeg" /><figcaption>Contain Method to check if the object you referencing to exist in the arrayList.</figcaption></figure><p><strong><em>It will return the index of the object your referring to</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*6F3UJm3YYg1ShvWisQVY_A.jpeg" /><figcaption>Return the index of the object your refereeing to. In this case it will return 0 (first item)</figcaption></figure><p><strong><em>This method is used to check if the ArrayList has any items. If not, it will return true</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*63yM3WMCjyNVY1cSLkJk1Q.jpeg" /><figcaption>Return true if the arrayList doesn&#39;t have any values in it.</figcaption></figure><h3>COMPARING ARRAY AND ARRALIST</h3><p>An array is a dynamically-created object. The array is a container used to hold several values of the same type. In other words, it is a continuous memory location that is used to store a list of values of the same type. Array is a fixed length data structure(cannot change the size). Once the array is created, we are unable to change its size. Array can contain both primitives and objects in <em>Java. An</em> array can be created as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*IGC_eUilQmIrn-IK_cfzgQ.jpeg" /></figure><p>In Java, the ArrayList is a class of collections framework. The array in Java internally backs ArrayList. As of Java 5.0, we can store primitives in the ArrayList, but internally, these will be stored as objects(these will be discussed in an upcoming article). ArrayList consists of methods to add, remove, check an item, and check if the array list is empty.<strong> </strong>ArrayList is a variable-length Collection class. In other words, the length of the ArrayList can be changed. <em>An</em> ArrayList can be created as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_c1qZva8T30b_f9WJQrGSg.jpeg" /></figure><h3>Using the Library (the Java API)</h3><p>In the Java API, the classes are grouped into packages. To use a class in the <br>API, you have to know which package the class is in. The package consists of a name such as javax. Swing, java.util.</p><p>One fun fact is that the System.out.println package and the Math.random all belong to java.lang package. We have already been using these classes from packages. These classes will be automatically called instead of importing them.</p><p>When you use a class from a package. you need to know the full name of the class that your required.<br><strong>Packages are essential for three main reasons</strong></p><ul><li>Instead of having a large pile of classes, there are grouped into packages based on the functionalities.</li><li>Package gives you a name scoping to prevent collision between you and the other programmers. Important when you and another developer working in the same project have two classes with the same name(important when you have two classes with the same name)</li><li>packages provide a level of security as it enables you to restrict the code you write</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w-l-HF5MlnmXlM8OS9pxdQ.jpeg" /><figcaption>(Difference between Array and ArrayList — Javatpoint, 2022)</figcaption></figure><p>Thanks for reading the article hope you enjoyed it. If you do require any additional support for code, go through my GitHub link — <a href="https://github.com/KavindaPereraa/Krish-training/blob/main/HeadFirst/GuessGame_Kavinda">https://github.com/KavindaPereraa/Krishtraining/blob/main/HeadFirst/GuessGame_Kavinda</a></p><h3>References</h3><p><em>Bates, B. and Sierra, K., 2005. Head First Java, 2nd Edition. [S.l.]: O’Reilly Media, Inc.</em></p><p><a href="http://www.javatpoint.com./">www.javatpoint.com.</a> 2022. <em>Loops in Java | Java For Loop — Javatpoint</em>. [online] Available at: &lt;https://www.javatpoint.com/java-for-loop&gt; [Accessed 3 April 2022].</p><p><a href="http://www.javatpoint.com./">www.javatpoint.com.</a> 2022. <em>Difference between Array and ArrayList — Javatpoint</em>. [online] Available at: &lt;https://www.javatpoint.com/difference-between-array-and-arraylist&gt; [Accessed 4 April 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1811b417da6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extra-Strength Methods]]></title>
            <link>https://medium.com/@kavindaperera25/extra-strength-methods-35dfa1f28345?source=rss-63f683205b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/35dfa1f28345</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[methods]]></category>
            <dc:creator><![CDATA[Kavindaperera]]></dc:creator>
            <pubDate>Sun, 03 Apr 2022 04:28:00 GMT</pubDate>
            <atom:updated>2022-04-03T04:28:00.922Z</atom:updated>
            <content:encoded><![CDATA[<h4>Head First Java Chapter 05</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8_8ULBzeBVXh3mw-G-kSg.png" /><figcaption>Extra Strength Methods</figcaption></figure><p>As in previous examples, we talked about the basics of java, how to create objects and methods, primitives, and references, but we didn’t implement anything. As a result, we will try to implement a simple console application game during this article, including everything we have talked about so far. We will also work with some APIs, aka libraries, to get user input, generate random numbers, and learn how to convert a string into an integer. If you haven’t gone through my previous <a href="https://medium.com/@kavindaperera25/">articles</a>, please do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*zE79J15cuevqiq2LXUuc5w.png" /></figure><p>We will develop a simple console-based application to guess the number during this article. <strong>How does this game work?</strong> The user has to guess a number randomly, and if that number exists in the grid aka array(cell), it will print Hit. If it misses, it will print Miss, and once all the numbers are guessed, it will print Kill and exist the program. Finally, based on the number of guesses, it will print an outcome. As for this example, let’s assume that the user has to guess three numbers to complete the game. One key point to notice is that since we haven’t yet talked about how the GUI works, we will create a console-based application.</p><p><strong>STEP 1</strong> — Before coming to the implementation, our initial step is to design a high-level diagram of how the system works. For this, we can use a flow chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*kUT81eYDVx1pu9TxW3Hpcw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*8gH1AkgeIAps3boveMSQBw.jpeg" /><figcaption>flow chart presenting the flow of the system we going to build</figcaption></figure><p>As a standard for each class, we carry out three things.</p><ul><li><strong>Prep Code</strong></li><li><strong>Test Code</strong></li><li><strong>Real Code</strong></li></ul><h3><strong>Prep Code</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*7fBjsM1cX-bqoquWAhuSmw.png" /></figure><p>Prep code means writing down the code in plain text, for example, in the form of pseudocode which helps to focus on the logic without stress about the syntax.</p><p>Most prep code allows to identify the instance variable declarations required, methods declarations required, and most importantly, allows a better understanding of the method logic. Prep code gives a better understanding of what has to happen rather than how it has to happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYaMgGZg_6moS9sfX5ZlbA.jpeg" /><figcaption>Pseudo Code</figcaption></figure><h3><strong>Test Code</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*jGlyuQTdxKdxyvqkw3U9Uw.jpeg" /><figcaption>Test Code</figcaption></figure><p>Class and methods can be tested with the real code to ensure that they work as expected. It preferred to write the test code way before writing the actual code. Even though you will not be able to compile the test code until the real code is written down, it still ensures you write the actual code first and then test your code asap. (Many people feel lazy to write the test code).</p><h3><strong>Real Code</strong></h3><p>The actual implementation of the class(where you write your final java code). Once you write the code, you can test your code with the methods you have already done to ensure that you get the expected output from the methods.</p><h3><em>LOOPS</em></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*pIYJGkU239glx30m0FDvZA.png" /></figure><ul><li><strong>For Loop</strong></li><li><strong>While Loop</strong></li><li><strong>Enhance Loop</strong></li><li><strong>Do while Loop</strong></li></ul><ol><li><strong>Initialization</strong>: When the loop begins, the initial condition is executed once. We can either initialize the variable or use one already been initialized. It’s a condition that can be turned off.</li><li><strong>Condition</strong>: This is the second condition, which is run every time the loop is tested. It keeps running until the condition is false. It must return either true or false as a boolean value. It’s a condition that can be turned off.</li><li><strong>Increment/Decrement</strong>: It increases or decreases the value of the variable. It’s a condition that can be turned off.</li><li><strong>Statement</strong>: The loop’s statement is executed each time the second condition is false.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WnICwuhF4bX-bDWuE6E3MA.jpeg" /><figcaption>(Loops in Java | Java For Loop — Javatpoint, 2022)</figcaption></figure><h3>THE ACTUAL GAME IMPLEMENTATION</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4SNItgxfZbPmaA4g8ng4w.jpeg" /><figcaption>Guess Game Implementation</figcaption></figure><p>The above class consists of two methods. One method is used to initialize the array with random numbers. The other method is to check whether the user guessed the correct number. All the code explanation is given within the screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfwRQ58NiuagssUjGyanIA.png" /><figcaption>Game class Testing</figcaption></figure><p>This is not optional, it is required, but the main thing this class does is that it is used to check whether our intended methods work as expected. To validate this, we used some values and passed them into the method to check whether we got our desired output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVM9f4wEESY_VL2PlWF3aw.png" /><figcaption>Class to get user input</figcaption></figure><p>This class is used to gather the user’s input. First, the user input will be gathered as a string value, and later, we will convert it to an integer. This class also validates the user input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YuqgZLyWSRZSNfOsUlwn7Q.png" /><figcaption>Application (Full running the system)</figcaption></figure><p>Finally, we create another class called application, where we create objects from previous classes and then run the whole system. Further details are given on each line of code.</p><p>Thanks for reading the article hope you enjoyed it. If you do require any additional support for code, go through my GitHub link — <a href="https://github.com/KavindaPereraa/Krish-training/blob/main/HeadFirst/GuessGame_Kavinda">https://github.com/KavindaPereraa/Krishtraining/blob/main/HeadFirst/GuessGame_Kavinda</a></p><h3>References</h3><p><em>Bates, B. and Sierra, K., 2005. Head First Java, 2nd Edition. [S.l.]: O’Reilly Media, Inc.</em></p><p><a href="http://www.javatpoint.com./">www.javatpoint.com.</a> 2022. <em>Loops in Java | Java For Loop — Javatpoint</em>. [online] Available at: &lt;https://www.javatpoint.com/java-for-loop&gt; [Accessed 3 April 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35dfa1f28345" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HOW OBJECTS BEHAVE]]></title>
            <link>https://medium.com/@kavindaperera25/how-objects-behave-1a70c58b71b6?source=rss-63f683205b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a70c58b71b6</guid>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kavindaperera]]></dc:creator>
            <pubDate>Fri, 01 Apr 2022 10:39:27 GMT</pubDate>
            <atom:updated>2022-04-01T10:39:27.616Z</atom:updated>
            <content:encoded><![CDATA[<h4>Head First Java Chapter 04</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jos6aK7izWlET-ihIk5Rqg.png" /><figcaption>How Objects Behave</figcaption></figure><p>This article talks about how the state and behavior are related to one another. We all know that each class instance (object)can have its unique value. What about the method?. Ex: if you take a dog class consisting of a property name. The instance of this class, aka the object, can have unique dog names. Like Jeff, Raff, don’t worry if your not familiar with these . We will go through each step in this article, but you should initially have some basic java knowledge about JVM, classes, and objects. If you haven’t gone through my previous articles, please click on the following link and check those <a href="https://medium.com/@kavindaperera25/basics-of-java-dd432ba79a90">articles </a>first. It will help you.</p><p>We know that the objects have a state and behavior represented by instance variables and methods. When we declare a class, it describes how the JVM should make an object of that type. You know that every class object of a particular class can have different instance variables, but what about <strong>methods</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*VDzlHqXgMNQyhCMIen2-vw.png" /></figure><h3>Can every object in a particular class have a different method behavior?</h3><p>Kind of. The methods are the same for each instance of a particular class, but the methods can behave differently based on the values of the instance variables. This means that the method code for each class instance is pretty much the same nothing has changed. Only what it changes is the values that are passed in through the instance variables.</p><h3>Arguments and Parameters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*qUIA0aKJhqe4XyphIxnRZA.png" /><figcaption>Arguments vs parameters</figcaption></figure><p>You can pass values into your Method. For example, let’s assume that you are required to play a song in a loop(In other words, it means how many times a particular song should be played). As a result, based on the parameters, we can specify the amount of time that the particular song should be played. For example, if you pass 3 for the Method, we should play the song three times.</p><p>Usually, most developers use the term <strong>arguments </strong>or <strong>parameters </strong>when they used to pass values into the Method, But Technically, we call it as</p><blockquote><strong>The Method uses parameters, and the caller of the Method uses Arguments.</strong></blockquote><p><strong>Argument:</strong> An argument is things you pass into the method, which can be a value such as a numeric, floating, reference, or string.</p><p><strong>Parameter:</strong> Parameter is nothing more than a local variable. Consist of type and name which can be used inside the method body.</p><p><strong>Special Note:</strong> When you pass an argument, it simply faces down into parameters (In other words, it means that the values passed as arguments will be considered parameters). Another critical point is that whenever a method takes a parameter, it is required to pass some value in a correct type whenever you call the particular method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7dVLidI8dRB8522FKfZ7A.jpeg" /><figcaption>Argument and parameter rules.</figcaption></figure><p>You can specify if the method is used to return any value or print anything using the void key. It simply says that the particular method doesn’t have a return type. If you require to return any specific type of value to the caller, you can do so.</p><h4>ex: you’re returning a number</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rN5gjtyB_64p6V3a6C9XNg.png" /><figcaption>When returning a value</figcaption></figure><p>Methods are capable of having multiple arguments. You can separate the arguments with a comma Similarly, you can separate the parameters with a comma when coding the method.</p><p><strong>Special Note </strong>— when you pass arguments, you need to pass the arguments in the correct order and the correct type</p><blockquote><strong>JAVA IS PASS BY VALUE; IN OTHER WORDS, PASS BY COPY</strong></blockquote><h3><strong>GETTERS AND SETTERS</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*yKBR7v2f0hfEciJWUYeFrg.png" /><figcaption>Getters and Setters</figcaption></figure><p>Getters and setters allow to get and set things. A getter’s sole purpose in life is to send back as a return value (the value that the particular getter is supposed to be getting). The setter is used to get an argument value. Use it to set the value of an instance variable.</p><h3><strong>ENCAPSULATION</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*ppCd19zWu7IBWGRrLNjglQ.jpeg" /></figure><p>Encapsulation is the process where you assign a force field around your instance variables as a result; then, no one can inappropriately manipulate them. We have used declared and printed our instances variables where anyone can use them. In that case, the wrong person is capable of getting access to these instance variables. In that case, we need to find a way to call the setters rather than accessing the data directly.</p><h3><strong>How do objects in an array behave?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*-0_ytj1pPCiwK-R7b1F28Q.png" /><figcaption>Example of array(index from 0 to size -1)</figcaption></figure><p>The only difference is how you get to them. (how you get the remote control). The instance variable always has a value even before using setters and getters.<br>ex : int -0, floating-point = 0.0, boolean = false, references = null.</p><h3>Difference between instances and local variables</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*ngNtzqhc2k4WED-IkQRWiA.png" /><figcaption>Instances and local variables</figcaption></figure><p>Instance variables are declared within the class but not declared within the method. Local variables are declared within the method. Additionally, local variables should be initialized before being used. In other words, the local variables don’t get the default value as instance variables. Parameters<br>are also considered as local variables; additionally, they ALWAYS initialized</p><p>Thanks for reading the article hope you enjoyed it. If you do require any additional support for code, go through my GitHub link — <a href="https://github.com/KavindaPereraa/Krish-training/tree/main/DesignPatterns/Chain0fResponsibility%20_Pattern">https://github.com/KavindaPereraa/</a></p><h3>References</h3><p><em>Bates, B. and Sierra, K., 2005. Head First Java, 2nd Edition. [S.l.]: O’Reilly Media, Inc.</em></p><p>GeeksforGeeks. 2022. <em>The complete History of Java Programming Language — GeeksforGeeks</em>. [online] Available at: &lt;https://www.geeksforgeeks.org/the-complete-history-of-java-programming-language/&gt; [Accessed 31 March 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a70c58b71b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Primitives and References]]></title>
            <link>https://medium.com/@kavindaperera25/primitives-and-references-bf840aab3aa1?source=rss-63f683205b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf840aab3aa1</guid>
            <category><![CDATA[datatypes-in-java]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[primitive-data-types]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kavindaperera]]></dc:creator>
            <pubDate>Fri, 01 Apr 2022 03:46:05 GMT</pubDate>
            <atom:updated>2022-04-01T03:46:05.952Z</atom:updated>
            <content:encoded><![CDATA[<h4>Head First Java Chapter 03</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5d0HEEWyla6zF4vbwoMaA.png" /></figure><p>This article will look at the difference between primitive and reference data types. We will also discuss the variables we have used in the two stages: the object state(Instance variables) and the local variables(variables declared within the method). Finally, we will also get into the variables passed as arguments. If you haven’t gone through the initial or the first article, please follow the link. It will help you to begin and follow through with the upcoming <a href="https://medium.com/@kavindaperera25/basics-of-java-dd432ba79a90"><strong>articles</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*VtomHyaE0eUgZcZ3Rwu2jA.png" /><figcaption>Variables</figcaption></figure><p>As the first step, let’s see how we can declare a simple variable and the rules we should follow when declaring a variable.</p><p><strong>When declaring a variable, it consists of 2 rules which are</strong></p><ul><li>Variables are required to have a type.</li><li>A Name should be given when declaring a variable. Therefore, you can use this name to do the necessary operations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*ldVGW5KrVzBXwQ_yKvDZrw.png" /><figcaption>Example when declaring a variable</figcaption></figure><p>A variable is just a container that is used to hold something. It consists of a size and a type. It is advised that when naming a variable, give a meaningful name; therefore, you can easily interpret it when you look back on the code.</p><h4>Naming Rules</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*pEBBLKrhPTgNmceS5d3ETg.png" /><figcaption>Naming Java Conventions</figcaption></figure><p>When naming variables, methods, and classes, you should follow some rules. Here are the rules.</p><ul><li>When naming, it should start with a letter, underscore, or a dollar sign. You cant start a name with a <strong>number</strong></li><li>After the initial or first character, you can include numbers</li><li>You cannot use any java reserved words (public, integer, Boolean, static, etc.)</li></ul><p>The below differentiation between primitives’ data type and reference data type can also be found in the following <a href="https://medium.com/@kavindaperera25/data-types-in-jvm-e45eedd00435">article</a>.</p><h3>Primitive Data Type</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*9NSfrlieizbzaRtWhqbCHg.png" /><figcaption>Primitive and non primitive data types</figcaption></figure><p>All the language primitive data types are dealt with the same compared to JVM primitive data types unless it comes to Boolean data types.</p><p>In JVM, Boolean data types are managed with either int or byte. Whereas Boolean false is considered zero and Boolean true is considered non-zero.<br>An operator Boolean is represented by an int value. While arrays are accessed using byte array instructions. Byte, char, short data types are also compiled to use int data type.</p><p>JVM Boolean data type has limited instruction support for it. When the java source file is converted to a bytecode file by the compiler, it uses int or byte data type to present Boolean. Arrays of Boolean are accessed as arrays of bytes, although they may be repented on the heap as bit-field or array of bytes.</p><p>The data type is the same in every environment (in every language). But the difference is long. Long always take 64bit 2’s compliment as its size doesn’t change based on the platform(independent of the underlying host platform). So in every implementation, it takes the same size.</p><p>The other primitive data type is the return address type, where developers have no access. This data type is specially dedicated to JVM. This data type is used to implement the final block. (final keyword = to prevent making changes).</p><p>JVM has an instruction set for handling the actual java programming data type with JVM data type. It has limited support for the byte, char, short and Boolean data types.</p><h3>Reference Data Type+</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*r6aZSv_VW_QgjrI4mDmh9A.png" /><figcaption>Example: Reference Data type</figcaption></figure><p>Reference data type does not store the value itself; therefore. As a result, it stores only the reference to the actual value itself. (Memory location ). In other words, it is just a holder used to store the address of where the object is located. Also, reference type can be assigned null, stating there is no memory location. Reference data type works as a pointer.</p><p>In JVM, there are four reference data types: class reference, interface reference, array reference, and null.</p><p><strong>The class type references</strong> the class instance or is also known as a dynamically created class instance. <strong>Next, an array reference</strong> is used to simply reference the array itself (which are full-fledged objects in the Java virtual machine). Where as the <strong>interface reference</strong> is used to reference the class implementation or array that implements the interface(class instances that implement an interface.) and lastly the <strong>null reference</strong> is used to state that there is no value in it (no value or memory location/ a specific type that is not referenced to anywhere).</p><blockquote><strong>Arrays are always objects, whether they’re declared to hold primitives or object references</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*XU92eU6rTfUS2-s7.png" /></figure><p>Thanks for reading the article hope you enjoyed it. If you do require any additional support for code, go through my GitHub link — <a href="https://github.com/KavindaPereraa/Krish-training/tree/main/DesignPatterns/Chain0fResponsibility%20_Pattern">https://github.com/KavindaPereraa/</a></p><h3>References</h3><p><em>Bates, B. and Sierra, K., 2005. Head First Java, 2nd Edition. [S.l.]: O’Reilly Media, Inc.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf840aab3aa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classes and Objects]]></title>
            <link>https://medium.com/@kavindaperera25/classes-and-objects-afc4cc1859bf?source=rss-63f683205b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/afc4cc1859bf</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[classes-and-objects]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[java-basics]]></category>
            <dc:creator><![CDATA[Kavindaperera]]></dc:creator>
            <pubDate>Fri, 01 Apr 2022 01:55:30 GMT</pubDate>
            <atom:updated>2022-04-01T01:57:38.121Z</atom:updated>
            <content:encoded><![CDATA[<h4>Head First Java Chapter 02</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQ1fv8d8o-mPV5iYJIFqLA.png" /><figcaption>Classes and objects</figcaption></figure><p>This article will mainly focus on the difference between procedural and object-oriented programming and its benefits. In addition to that, we will mainly focus on and discuss the differentiation between classes and objects. If you haven’t gone through the initial or the first article, please follow the link. It will help you to begin and follow through with the upcoming <a href="https://medium.com/@kavindaperera25/basics-of-java-dd432ba79a90">articles</a>.</p><h3><strong>Procedural Programming</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*l7yTym1Os5GG8oLL6AUD6Q.png" /></figure><p>Procedural programming is the initial programming paradigm that a new developer learns. This paradigm approaches a linear top-down approach. In other words, it can also be considered a programming model derived from structured programming. The program is divided into procedures, basically a segment of codes or steps to be carried out. In other words, procedural programming is a list of instructions or code that tells what the computer to carry out from top to down approach.<br>ex: Pascal, C, COBOL</p><h3>Object Oriented Programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*-AoCPrN2WJWR7GSuvbUF-A.png" /><figcaption>Features of OOP</figcaption></figure><p>Object-oriented programming is a programming model based on the concepts of classes and objects. Objects can contain the data in the form of attributes and code (what to do ) in the form of a method. The objects are instances of classes. Computer programs are designed explicitly with objects to interact with the real world in object-oriented programming.<br>ex: JAVA, C++, C#</p><h3><strong>DIFFERENCE BETWEEN PROCEDURAL AND OBJECT ORIENTED PROGRAMMING.</strong></h3><p>The below figure consists of the major drawbacks and differences between procedural and object-oriented programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LN29_EIhD_BIGHu0bQ8otw.png" /><figcaption>DIFFERENCE BETWEEN PROCEDURAL AND OBJECT ORIENTED PROGRAMMING.</figcaption></figure><h3>Classes and Objects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*WqIXvSneCZxIztxxbLGuTw.png" /><figcaption>Class Example</figcaption></figure><p><strong>A class</strong> is a blueprint or prototype defined by the user from which the objects are created. It tells the virtual machine how to make an object of that particular type. It consists of a set of properties or methods that are common to all the objects created from one class. Ex: you can have a class for animals to represent animals. Each animal may have different features, colors, etc.</p><p><strong>An object </strong>is used to represent real-life entities. An object is an element or instance of the class. The object is considered the program’s actual component, whereas the class specifies how the instances are created and how they behave. Whenever an object is created, it has the behavior of its class as well.</p><p>Whenever an object is created and knows about itself is called an instance variable. They represent the object state, in other words, data. This data can consist of unique values for each object creation from the same class type. The segments of codes that the object can do are known as methods. When designing a class, you always consider what kind of data and methods are required by the objects created by the same class type.</p><h3>JAVA TAKES OUT THE GARBAGE.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*FGkwSi8ImR9ykypAKN3utQ.png" /></figure><p>Whenever an object is created in java, it simply goes into the area of memory known as the heap. No matter how the object is created, it lives in the heap memory. The java heap is also known as <strong>the garbage collection heap.</strong> Whenever an object is created, it allocates memory space to a heap-based on the requirements of the object. What happens when you need to reclaim the space? How to get the object out of the heap when done? Java is capable of managing the memory automatically. JM is capable of checking whether a particular object can never be used again, and if so, that object becomes eligible for garbage collection. If the memory of your pc is too low, then the garbage collector will run and throw out the unrequired objects and free up space</p><p>Thanks for reading the article hope you enjoyed it. If you do require any additional support for code, go through my GitHub link — <a href="https://github.com/KavindaPereraa/Krish-training/tree/main/DesignPatterns/Chain0fResponsibility%20_Pattern">https://github.com/KavindaPereraa/</a></p><h3>References</h3><p><em>Bates, B. and Sierra, K., 2005. Head First Java, 2nd Edition. [S.l.]: O’Reilly Media, Inc.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afc4cc1859bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BASICS OF JAVA]]></title>
            <link>https://medium.com/@kavindaperera25/basics-of-java-dd432ba79a90?source=rss-63f683205b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd432ba79a90</guid>
            <category><![CDATA[java-basics]]></category>
            <category><![CDATA[head-first]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kavindaperera]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 04:28:27 GMT</pubDate>
            <atom:updated>2022-04-02T00:06:07.314Z</atom:updated>
            <content:encoded><![CDATA[<h4>Head First Java Chapter 01</h4><p>You will be wondering with doubts why java? Why is this language so powerful? What makes it powerful? Are you still concerned about it? Don’t Worry. We will discuss these topics in much more detail throughout these upcoming articles. Stay Tuned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nydziaTqOz0S0yoUI21y6w.png" /><figcaption>Basics Of Java</figcaption></figure><blockquote><strong>The main objective of java is to write one application and have it work on any device.</strong></blockquote><p>Initially, to know the benefits of java, let’s dive deep into how this java exactly works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjs8IbiKOz9k-o8Q6RxMsw.jpeg" /><figcaption>The way java works</figcaption></figure><p>Initially, you would write a source code(any code). For this example, let’s consider you write some codes to the print hello world on the console. <strong>One</strong> <strong>key point </strong>is that you can write codes on either notepad or IDE (like Eclipse, IntelliJ IDEA, NetBeans) or a simple online tool. For this upcoming article, I will provide examples using the IDE IntelliJ IDEA and Notepad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQp12-dfOj9nCJyAg6ltPg.png" /><figcaption>You can use different ides (totally up to you).</figcaption></figure><p>Lets go through some steps of how the java actually works and why is it widely used.</p><h4><strong>Step 01</strong></h4><p>Type a source code file (In this case, it is just a bunch of codes to the print hello world).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*JfPe6QnLBo4qrk2xpkJCRA.png" /><figcaption>Source code file</figcaption></figure><h4><strong>Step 02</strong></h4><p>Compile the HelloWorld.java file by running the javac(The compiler application). If the particular source code is error-free, you will create another document with the name of HelloWorld.class. The javac compiler generates the particular document, and it is made up of bytecodes. This particular document, aka compiled byte code, is platform-independent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*odMrIonclM_UP4Cz5yl8WQ.png" /><figcaption>Step 02 — javac Compiler.</figcaption></figure><h4><strong>Step 03</strong></h4><p>Finally, the JVM can translate the particular bytecode into something that the specific platform can understand and run the program(If you do require to know more about the JVM, please refer to my article based on that ).</p><h3><strong>History of java</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*PILlcDMQStrAdSg9RsT73g.jpeg" /><figcaption>Java History</figcaption></figure><p>Initially, java 1.02 was released, which consisted of about 250 classes. This particular language had minor difficulties, such as bugs during this time, but the overall general public found it interesting to use. Later on, java 1.1, with about 500 classes, was released, which became very friendly to most people with its GUI. This version was much faster compared to the previous. Later, all java 2.0 and java 5.0 were released, adding more classes to each version and making it much faster than the earlier releases. They’re ever able to release the enterprise Micro and the Standard edition during this type.</p><h4><strong>What is a source file</strong></h4><p>A source code file holds the class definition. In other words, it’s just a segment of codes in your program. The codes should be written inside a pair of curly braces by default. Additionally, you can declare your methods inside a class file (segment of codes to do a specific function ).</p><p>Initially, when JVM starts running, it looks for a specific class with a special method as below. After this, JVM runs between this method’s curly braces, AKA the main method. (You require at least have one main method per application to run the relevant application)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*zakUXIGogdzMhph9dM3OdA.png" /><figcaption>(The complete History of Java Programming Language — GeeksforGeeks, 2022)</figcaption></figure><blockquote><strong>public static void main(String[] args){<br> System.out.println(“Hello World”);<br> }</strong></blockquote><p><strong>The public keyword </strong>stands that everyone is capable of accessing it.<br>A static keyword will be covered in the next article. Do not worry about it right now.</p><p><strong>Void </strong>specifies that the appropriate method has no return value.</p><p><strong>Main </strong>specifies the name of the method.</p><p><strong>Arguments </strong>to the method. The method must be given an array of strings, and the array will be called <strong>args</strong>.</p><p>Other things will cover in the upcoming articles. Thank you</p><p>Thanks for reading the article hope you enjoyed it. If you do require any additional support for code, go through my GitHub link — <a href="https://github.com/KavindaPereraa/Krish-training/tree/main/DesignPatterns/Chain0fResponsibility%20_Pattern">https://github.com/KavindaPereraa/</a></p><h3>References</h3><p><em>Bates, B. and Sierra, K., 2005. Head First Java, 2nd Edition. [S.l.]: O’Reilly Media, Inc.</em></p><p>GeeksforGeeks. 2022. <em>The complete History of Java Programming Language — GeeksforGeeks</em>. [online] Available at: &lt;https://www.geeksforgeeks.org/the-complete-history-of-java-programming-language/&gt; [Accessed 31 March 2022].</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd432ba79a90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DESIGN PATTERN FOR MICROSERVICES —CIRCUIT BREAKER PATTERN]]></title>
            <link>https://medium.com/@kavindaperera25/design-pattern-for-microservices-circuit-breaker-pattern-4c76fecaafbf?source=rss-63f683205b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c76fecaafbf</guid>
            <category><![CDATA[circuit-breaker-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Kavindaperera]]></dc:creator>
            <pubDate>Sun, 27 Mar 2022 03:32:33 GMT</pubDate>
            <atom:updated>2022-03-27T03:32:33.384Z</atom:updated>
            <content:encoded><![CDATA[<h4>Circuit Breaker Pattern</h4><p>One of the most famous topics is microservice. Microservice is considered as famous architecture nowadays as it has become the most favorable choice for modern application. The majority of applications were switched from monolithic to microservices architecture. Each of these architectures has its benefits as well as drawbacks. If you are new to microservices, you can refer to my article <a href="https://medium.com/@kavindaperera25/introduction-of-microservices-3c6ca3057ed1"><strong>Introduction to microservices.</strong></a><strong> </strong>You can refer to the <a href="https://medium.com/@kavindaperera25/design-pattern-for-microservices-aggregator-pattern-519f98710995"><strong>aggregator and proxy design pattern</strong></a>.</p><h3>Why do we require design patterns in microservices?</h3><p>The whole decision of whether your application is running smoothly through microservice architecture depends on the way you design. Thus, design pattern plays a significant role. There are several design patterns available in microservices, and we will discuss each of them and the benefits of every design pattern. Choosing the most appropriate design pattern is the essential factor; otherwise, it will shut down your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNDx-U7HLi-hw8kRfn3Lew.jpeg" /><figcaption>Circuit Breaker Pattern</figcaption></figure><p>In this article, we will talk about what is circuit breaker pattern. This pattern is more than a design pattern. It is a sustainable pattern. In a distributed system, components could fail, such as a network issue, or the switch may be broken. We don’t know how these components could fail, and the developers are responsible for keeping them alive.</p><p>To talk about the circuit breaker pattern, let’s first talk about circuit breaker. The thing where your parents are saying not to mess with. Because we need to know what it is to understand the circuit breaker pattern. It is somewhat similar.</p><h3>CIRCUIT BREAKER</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*qi3Y5GCQ3JmL7l8sQtEMTw.jpeg" /><figcaption>Circuit Breaker</figcaption></figure><p>If you go and check your house, you will find a closed or transparent box (electricity box) only if your house is powered by electricity. If you open your electricity box, it consists of circuit breakers. If you get high voltage or when the main grid works in an abnormal way due to some scenario, your circuit break will break by protecting your internal wires. This is pretty much equal to the design pattern.</p><p>The circuit breaker is an electrical switch that operates automatically to protect an electrical circuit from damage done by an overload.</p><h3>CIRCUIT BREAKER PATTERN</h3><p>The primary responsibility of the circuit breaker design pattern is to stop the request and response process if a particular service is not working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*OqeyP19UTFdCE6ZvWRZHWg.png" /><figcaption>Circuit Breaker Pattern</figcaption></figure><p>The Circuit Breaker pattern has 3 states.</p><ol><li>Open.</li><li>Closed.</li><li>Half-Open.</li></ol><p>The circuit breaker normally works when it is in a closed state. But when the request’s response exceeds the threshold limit, the circuit breaker trips. And switch its state from closed to open. Once the circuit is in the open state, all the incoming requests will return with an error stating the current service is not available without having to execute any real operation. After some time, the circuit again goes to the half-open state. During this state, the circuit breaker will only allow a limited number of test requests to pass through, and during this state, if the request succeeds, the whole circuit breaker stats reset or go back to the default(closed), and once again, it will start to receive the requests.</p><h3><strong>what causes to break the service</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*mqYjx028CRsg2vV7aXQfdQ.png" /></figure><h4><strong>SCENARIO 1</strong></h4><p>Assume you have five different microservices, and you have a webserver to call these services. Now you receive the request. In other words, the server allocates one thread to call the backend(Server)</p><p>Afterward, the server is delayed due to some failure. As a result, this thread is waiting. One thread waiting is acceptable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xlmf_6CGxLhyNAEXBHuC2g.png" /><figcaption>Server allocates one thread</figcaption></figure><p>But assume that the particular service is a high-demand service. In other words, it receives a large number of requests. Therefore more threads will be allocated for this service. Therefore when one thread fails and waits, the rest of the threads allocated to the service have no option other than waiting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgUZykom7wQYtDR9xIL-1Q.png" /><figcaption>High demand service receive many request therefore allocates many threads</figcaption></figure><p>So, for example, if you have 100 threads and out of that 100 threads, 98 of them are occupied. Another two services occupy the remaining two threads, and now all the threads are blocked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L271Eh67S81UUCWezW4ZQw.png" /></figure><p>As a result remaining thread that comes to the service will be queued(blocked). Meanwhile, more requests arrive, all of them are queued because the thread was frozen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPzebw7NnkQZ3OX9UIY5Zg.png" /></figure><p>A few seconds later, the service recovers from the fail state. Now the webserver trying to process the requests in the queue mean that more and more requests arrive. As a result, the webserver or the proxy may never recover. This type of scenario will kill your service.</p><h4><strong>SCENARIO 2</strong></h4><p>This problem is known as cascade failure. Let’s assume there are several services for this example lets consider there is a service <strong>A </strong>, service <strong>B</strong>; service <strong>C</strong>. Lets assume service <strong>A </strong>calls service <strong>B</strong>, service <strong>B</strong> call service <strong>C</strong> , and service <strong>C</strong> calls service <strong>D</strong> . In addition to that, there are few other services as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ol3AHPuSA-rRCDi7ixdy8Q.png" /></figure><p>What would happen if service <strong>D</strong> (the last service didn’t respond) in this scenario?</p><p>If service <strong>D</strong> fails to respond, then service <strong>C</strong> has to wait until service <strong>D</strong> responds. If service <strong>C</strong> is waiting, then service <strong>B</strong> also has to wait, and as a result, service <strong>A</strong> is waiting for a response from service <strong>B</strong>. This problem is known as cascade failure.</p><h4>NO MATTER HOW IF YOU FAIL THE SERIVCE WILL GO OFFLINE WHICH IS NOT ACCAPTABLE WE NEED TO FIND A SCENARIO TO MAKE THE SERVICE UP AND RUNNING</h4><h3>SOLUTION WITH CIRCUITE BREAKER PATTERN</h3><p>For example, let’s consider you have four services, in other words, four backends. In addition to that, you have a proxy or a pattern to call these services. Let’s assume you have defined a threshold like service should respond within 200 milliseconds.</p><blockquote><em>Ex: Service A should respond within 200ms or the service should fail</em></blockquote><blockquote>Below are some conditions you should follow for this example.</blockquote><blockquote><em>0ms -100ms : expected delay interval(Expected all the request to fall in this interval).<br>100ms -200ms : risky.</em></blockquote><blockquote><em>If response time is more than 200ms then cut off the service.</em></blockquote><p>As a result, if the number of requests, let’s assume 75 percent of the request reaches the upper threshold between 150 and 200 milliseconds, we know that the service is falling slowly. If the number of requests exceeds 200 milliseconds, now the proxy understands the particular service is not responding anymore.</p><p>As soon as the proxy understands that the particular service is not responding, it will break the connection between the proxy and the not responding service, and as a result, now the new request will not go to service a. Therefore, the request will not enter the queue instead it will fail fast.</p><h3>why not directly go to the service and see. If it’s failing the request can go back. Why is it necessary to have something in between?</h3><p>Assume that you have 30 seconds timeout. If the request is trying to hit or reach the Service without considering its falling, all the requests which come from the consumer will wait 30 seconds. End of 30 seconds, these requests will fail (timeout).</p><p>During that 30 seconds, the remaining request comes to the server by the consumer. These requests come to server <strong>A </strong>and try to reach <strong>A, </strong>and those will go and wait in the queue.</p><p>As a result, the circuit breaker pattern now does that if the Service is failing more than the given threshold, it will not try to reach Service A anymore at all. It will simply just fail back to the consumer stating that service A is not currently available.</p><h3>How it is going to connect back?</h3><p>In the background, it sends a ping request or a default request to service A from time to time. When the communication time or response time comes back to the normal threshold, it will turn on the circuit again then the next request trying to reach A will go directly to service A. In this way, there is no queue during the failing time. All the result which comes to service A will get a response with an error message. When the service is back up, it is open for new traffic.</p><h3>Didn’t we fail to respond to some of the consumer requests?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvOVJQSyvS5QbGaY0keN0A.png" /></figure><p>Now there is an issue since we will fail some requests done by the consumer/ user due to service A not responding. The user will get an error message stating that service A is not currently available.</p><p><strong><em>There request that aren&#39;t even queued?</em></strong></p><p>Yes, if we queue all the requests. Even if the service comes back, the request in the queues will try to access and eventually fail, but with this approach, we can make it fail for a certain time, mentioning the relevant service is not currently available. It is the main responsibility of implementing such a design pattern. When you implement a circuit breaker pattern, you can define a threshold saying that the request takes more than 200milliseconds then cuts the service.</p><p>Thanks for reading the article hope you enjoyed it. If you do require any additional support for code, go through my GitHub link — <a href="https://github.com/KavindaPereraa/Krish-training/tree/main/DesignPatterns/Chain0fResponsibility%20_Pattern">https://github.com/KavindaPereraa/</a></p><h3>References</h3><p><a href="https://www.youtube.com/watch?v=mw8W-RpvCu0">Design pattern 02 — Protect your services with Circuit Breaker pattern — YouTube</a></p><p><a href="https://www.galvinpower.org/circuit-breaker-sparks-when-turned-on/">Circuit Breaker Sparks When Turned On — Here’s Why (galvinpower.org)</a></p><p><a href="https://martinfowler.com/bliki/CircuitBreaker.html">CircuitBreaker (martinfowler.com)</a></p><p><a href="https://techblog.constantcontact.com/software-development/circuit-breakers-and-microservices/">Circuit Breakers and Microservices Architecture | Constant Contact Tech Blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c76fecaafbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DESIGN PATTERN FOR MICROSERVICES — PROXY DESGIN PATTERN]]></title>
            <link>https://medium.com/@kavindaperera25/design-pattern-for-microservices-proxy-desgin-pattern-9cb19627f91f?source=rss-63f683205b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cb19627f91f</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[proxy-pattern]]></category>
            <category><![CDATA[desing-pattern]]></category>
            <category><![CDATA[microservices-pattern]]></category>
            <dc:creator><![CDATA[Kavindaperera]]></dc:creator>
            <pubDate>Sat, 26 Mar 2022 08:03:56 GMT</pubDate>
            <atom:updated>2022-03-26T08:03:56.922Z</atom:updated>
            <content:encoded><![CDATA[<h3>DESIGN PATTERN FOR MICROSERVICES — PROXY DESGIN PATTERN</h3><h4>Proxy Design Pattern</h4><p>One of the most famous topic is microservice . Microservice is considered as famous architecture nowadays as it has become the most favorable choice for modern application. The majority of applications were switched from monolithic to microservices architecture . Each of these architectures has its benefits as well as drawbacks. If you are new to microservices, you can refer to my article <a href="https://medium.com/@kavindaperera25/introduction-of-microservices-3c6ca3057ed1"><strong>Introduction to microservices.</strong></a><strong> </strong>You can also refer to the <a href="https://medium.com/@kavindaperera25/design-pattern-for-microservices-aggregator-pattern-519f98710995"><strong>aggregator </strong></a>design pattern as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hejjU9RpitTAeO8XeSXzUg.png" /></figure><h3>Why do we require design patterns in microservices?</h3><p>The whole decision of whether your application is running smoothly through microservice architecture depends on the way you design. Thus, design pattern plays a significant role. There are several design patterns available in microservices, and we will discuss each of them and the benefits of every design pattern. Choosing the most appropriate design pattern is the essential factor; otherwise, it will shut down your application.</p><h3><strong>Proxy pattern</strong></h3><p>Everyone has some idea what a proxy is, but many people don’t know how the proxy is implemented. To talk about the proxy pattern, let’s consider an example. Assume you have a current client who is willing to change his company from a monolithic application to microservice architecture. Microservice is highly valuable when working with agile due to its continued development throughout life. With this continuous development, some services might require changes like updating functionalities, queries, etc. Updating a particular service also might affect the other services (the services which are connected ). Due to this, the system will fail. To solve this, we can use the proxy design pattern.</p><p>This is similar to the aggressiveness design pattern, only instead of aggregation, a different microservice may be invoked depending on the business need. This pattern may scale independently, and its major task is to avoid exposing each service to its users by going through an interface.</p><p>To make things simpler and easier to understand, let’s consider an example. Assume a school management system(the same example taken in our previous article). It also consists of service to obtain each student’s marks. To obtain the marks, you use your student’s full name, but after some time, you deploy a new version of the service, which is also used to obtain marks. Still, now, in this case, let’s assume it takes the student It number to obtain the student’s marks, and in this case, the consumers of the mark service are going to break. To solve this, we can you the proxy pattern. We can create a proxy server for the particular service(mark service) to overcome this situation. As a result, all the consumers will communicate to the mark service through the proxy service. Now the developers are required to change anything on the consumer side, and now when the user enters the student’s full name, it will communicate with the old version or the initial version. Once the user passes the student its number, it will communicate the new version. This way you can independently deploy your service without disturbing your consumer. After some time, if you don’t see any traffic on your previous or initial version of the service, you can decommission that particular version</p><h3>Semantic versioning</h3><p>The semantic version has <strong>major</strong>, <strong>minor</strong>, and <em>patch </em>versions.</p><ul><li>You increment the <strong>major version </strong>when the new version is incompatible with the previous or existing version.</li><li>You increment the <strong>minor</strong> <strong>version</strong> whenever you have new functionalities, but the previous or the initial service will work. If the user wants the new version, then the user is capable of updating, or else the user can go with the old functionalities.</li><li>The <strong>Patch version</strong> is not much relevant, and you are capable of updating it as you want.</li></ul><h3>Service Discovery Tool</h3><p>Whenever a service is created, it is much better to use an external party to discover the service for you because when the infrastructure is changed, it may also change the hostname, IP address, etc. To avoid this, you might need to use some service discovery tool. Therefore, the proxy will invoke this discovery tool and ask the discovery tool the student version 1 or student version 2 based on the values of the parameters passed. This solution is much better rather than hard coding the values. You can use the ws02 governor’s register for the service discovery tool. Service discovery tool is essential because, again, your service is independent</p><p><strong>Message queues:</strong> Message queues will store the messages in a queue, and the queue processor will process them one by one into the database. This is required when the database takes a long time to save the data in the DB(important when DB takes a lot of time to respond). In other words, it allows us to reduce the cascade effect. Message queues come in handy to reduce or get rid of cascading effects. You also need to consider other facts whenever you implement message queues, such as failures, fault tolerance, queue fails. Having a redundancy mechanism is essential.</p><p><strong>Time out:</strong> This is an important factor you should consider when using a proxy service. Let’s assume your student version 1 is getting more and more deployed. If you haven’t implemented the time out, that block thread can also affect version 2.</p><p>Thanks for reading the article hope you enjoyed it. If you do require any additional support for code, go through my GitHub link — <a href="https://github.com/KavindaPereraa/Krish-training/tree/main/DesignPatterns/Chain0fResponsibility%20_Pattern">https://github.com/KavindaPereraa/</a></p><h3>References</h3><p><a href="https://www.youtube.com/watch?v=7mBvb7nKONg">Design patterns for microservices — 03 — YouTube</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cb19627f91f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>