<?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 Lakshini Kuganandamurthy on Medium]]></title>
        <description><![CDATA[Stories by Lakshini Kuganandamurthy on Medium]]></description>
        <link>https://medium.com/@lakkuga?source=rss-ed774cb971e0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*B43JbL9V_nmWBygbqGyFHw.jpeg</url>
            <title>Stories by Lakshini Kuganandamurthy on Medium</title>
            <link>https://medium.com/@lakkuga?source=rss-ed774cb971e0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 04:02:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lakkuga/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[Exceptions]]></title>
            <link>https://medium.com/@lakkuga/exceptions-32819f8ea9fe?source=rss-ed774cb971e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/32819f8ea9fe</guid>
            <category><![CDATA[exception]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Lakshini Kuganandamurthy]]></dc:creator>
            <pubDate>Mon, 30 May 2022 11:55:29 GMT</pubDate>
            <atom:updated>2022-06-03T05:39:17.014Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Exceptions 😅 is n’t an easy topic as we think!!! There are minute points that need to be remembered 😄 Let’s dig in and ace them 👍</blockquote><h4>Runtime Exceptions</h4><p>Runtime exceptions extend RuntimeException. They <strong><em>don’t have to be handled or declared</em></strong>. They can be thrown by the programmer or by the JVM.</p><p>Common runtime exceptions include the following:</p><ol><li><strong><em>ArithmeticException</em></strong> — Thrown by the JVM when code attempts to divide by zero.</li><li><strong><em>ArrayIndexOutOfBoundsException</em></strong> — Thrown by the JVM when code uses an illegal index to access an array.</li><li><strong><em>ClassCastException</em></strong> — Thrown by the JVM when an attempt is made to cast an exception to a subclass of which it is not an instance.</li><li><strong><em>IllegalArgumentException </em></strong>— Thrown by the programmer to indicate that a method has been passed an illegal or inappropriate argument.</li><li><strong><em>NullPointerException</em></strong> — Thrown by the JVM when there is a null reference where an object is required.</li><li><strong><em>NumberFormatException</em></strong> — Thrown by the programmer when an attempt is made to convert a string to a numeric type but the string doesn’t have an appropriate format.</li></ol><h4>Checked Exceptions</h4><p>Checked exceptions <strong><em>have Exception in their hierarchy</em></strong> <strong><em>but not RuntimeException</em></strong>. They must be<strong><em> handled </em></strong>or <strong><em>declared</em></strong>. They can be thrown by the programmer or by the JVM. Following are the common checked exceptions:</p><ol><li>FileNotFoundException — Thrown programmatically when code tries to reference a file that does not exist.</li><li>IOException — Thrown programmatically when there’s a problem reading or writing a file.</li></ol><blockquote>For the OCA exam, you only need to know that these are checked exceptions. Note : <strong>FileNotFoundException is a subclass of IOException<em>.</em></strong></blockquote><h4>Errors</h4><p>Errors extend the Error class. They are thrown by the JVM and <strong><em>should not be handled or declared</em></strong>. Following are some errors you may often see!!!</p><ol><li>ExceptionInInitializerError — Thrown by the JVM when a static initializer throws an exception and doesn’t handle it.</li><li>StackOverflowError — Thrown by the JVM when <strong><em>a method calls itself too many times</em></strong> (this is called infinite recursion because the method typically calls itself without end).</li><li>NoClassDefFoundError — Thrown by the JVM when <strong><em>a class that the code uses is available at compile time but not runtime.</em></strong></li></ol><p>❗️Points on each of the above.</p><h4>ExceptionInitializerError</h4><ul><li>Java runs static initializers the first time a class is used.</li><li>If one of the static initializers throws an exception, Java can’t start using the class. It declares defeat by throwing an <strong><em>ExceptionInInitializerError</em></strong>.</li></ul><pre>static {<br>   int[] countsOfMoose = new int[3];<br>   int num = countsOfMoose[-1];<br>}</pre><pre>public static void main(String[] args) { }</pre><p>This code outputs two exceptions:</p><p><em>Exception in thread “main” </em><strong><em>java.lang.ExceptionInInitializerError</em></strong><em> Caused by: </em><strong><em>java.lang.ArrayIndexOutOfBoundsException</em></strong><em>: -1</em></p><p>We get the <strong><em>ExceptionInInitializerError</em></strong> because the error happened in a static initializer. <strong><em>The ExceptionInInitializerError is an error because Java failed to load the whole class</em></strong><em>.</em> Java also tells us the original cause of the problem, which is the <strong><em>ArrayIndexOutOfBoundsException</em></strong> that we need to fix.</p><h4>StackOverflowError</h4><ul><li>When Java calls methods, it puts parameters and local variables on the stack.</li><li>After doing this a very large number of times, the stack runs out of room and overflows. This is called Stack overflowing and throws a StackOverflowError. Mostly, this error occurs <strong><em>when a method calls itself</em></strong>, as shown below.</li></ul><pre>public static void doNotCodeThis(int num) {<br>   doNotCodeThis(1);   //recursive calls<br>}</pre><p>This outputs <em>Exception in thread “main” java.lang.StackOverflowError.</em></p><blockquote>Since the method calls itself, it will never end. Eventually, Java runs out of room on the stack and throws the error. This is called infinite recursion.</blockquote><blockquote>Note: It is better than an <strong>infinite loop</strong> because <strong>at least Java will catch it and throw the error</strong>. With an infinite loop, Java <strong>just uses all your CPU until you can kill it</strong>.</blockquote><h4>NoClassDefFoundError</h4><ul><li>NoClassDefFoundError occurs when <strong><em>Java can’t find the class at runtime</em></strong>.</li><li>This error won’t show up in code on the OCA exam, you just need to know that it is an error.</li></ul><h4>Calling methods that throw exceptions</h4><ul><li>When you’re calling a method that throws an exception, the rules are the same as within a method. Why does the following code not compile???</li></ul><pre>class NoMoreCarrotsException extends Exception {}</pre><pre>public class Bunny {<br>   public static void main(String[] args) {<br>      eatCarrot();// DOES NOT COMPILE<br>   }</pre><pre>   private static void eatCarrot() throws NoMoreCarrotsException {}<br>}</pre><p>The problem is that <strong><em>NoMoreCarrotsException is a checked exception</em></strong>. <strong><em>Checked exceptions must be handled or declared</em></strong>.<strong><em> </em></strong><em>This will compile if you do the following changes:</em></p><ol><li>Declare the exception for the main method as shown below. Here, eatCarrot() didn’t actually throw an exception; it just declared that it could throw an exception.</li></ol><pre>public static void main(String[] args) throws NoMoreCarrotsException {// declare exception<br>   eatCarrot();<br>}</pre><p>2. Handle the exception using try-catch block as shown below.</p><pre>public static void main(String[] args) {<br>   try {<br>   eatCarrot();<br>   } catch (NoMoreCarrotsException e ) {// handle exception<br>        System.out.print(&quot;sad rabbit&quot;);<br>   }<br>}</pre><p>The compiler is still on the lookout for unreachable code. <strong><em>Declaring an unused exception isn’t considered unreachable code</em></strong>. It gives the method the option to<strong><em> change the implementation to throw that exception in the future</em></strong>.</p><h4>Subclasses</h4><p>In this section, we’ll be looking at <strong><em>overriding methods with exceptions in the method declaration</em></strong>.</p><p>When<strong><em> a class overrides a method from a superclass or implements a method from an interface</em></strong>,<strong><em> it’s not allowed to add</em></strong> <strong><em>new checked exceptions</em></strong> <strong><em>to the method signature</em></strong>. Consider the below e.g.</p><pre>class CanNotHopException extends Exception { }</pre><pre>class Hopper {<br>   public void hop() { }<br>}</pre><pre>class Bunny extends Hopper {<br>   public void hop() throws CanNotHopException { } // DOES NOT //COMPILE<br>}</pre><p>Java knows <strong><em>hop() isn’t allowed to throw any checked exceptions</em></strong> because the <strong><em>superclass Hopper doesn’t declare any</em></strong>. Therefore when we override the hop() method in the Bunny class, by adding a checked exception, compiler throws a compile error.</p><ul><li>A <strong><em>subclass is allowed to declare fewer exceptions</em></strong> <strong><em>than the superclass or interface</em></strong>. This is legal because callers are already handling them.</li><li>A <strong><em>subclass not declaring an exception,</em></strong> is <strong><em>similar to a method declaring it</em></strong> <strong><em>throws an exception that it never actually throws</em></strong>.</li><li>Similarly, a <strong><em>class is allowed, to declare a subclass of an exception type</em></strong>.</li></ul><p>Look at the below e.g.</p><pre>class Hopper {<br>   public void hop() throws Exception { }<br>}</pre><pre>class Bunny extends Hopper {<br>   public void hop() throws CanNotHopException { }<br>}</pre><ul><li><strong><em>Bunny could declare that it throws Exception directly or it could declare that it throws a more specific type of Exception. It could even declare that it throws nothing at all</em></strong>.</li></ul><h4>❗️ ❗️ ❗️This rule applies only to checked exceptions.</h4><p>The following code is <strong><em>legal</em></strong> because <strong><em>it has a runtime exception in the subclass’s version.</em></strong></p><pre>class Hopper {<br>   public void hop() { }<br>}</pre><pre>class Bunny extends Hopper {<br>   public void hop() throws IllegalStateException { }<br>}</pre><p>The reason that <strong><em>it’s okay to declare new runtime exceptions in a subclass method is that the declaration is redundant</em></strong>. <strong><em>Methods are free to throw any runtime exceptions</em></strong> they want <strong><em>without mentioning them in the method declaration</em></strong>.</p><h4>Printing an Exception</h4><p>There are three ways to print an exception.</p><ol><li>You can let Java print it out.</li><li>Print just the message.</li><li>Print where the stack trace comes from.</li></ol><p>Check the below e.g.</p><pre>public static void main(String[] args) {<br>   try {<br>      hop();<br>   } catch (Exception e) {<br>        System.out.println(e);<br>        System.out.println(e.getMessage());<br>        e.printStackTrace();<br>     }<br>}</pre><pre>private static void hop() {<br>   throw new RuntimeException(&quot;cannot hop&quot;);<br>}</pre><pre>/*<br>The above code gives the following output:<br>java.lang.RuntimeException: cannot hop<br>cannot hop<br>java.lang.RuntimeException: cannot hop<br>at trycatch.Handling.hop(Handling.java:15)<br>at trycatch.Handling.main(Handling.java:7)<br>*/</pre><p>The first line shows what Java prints out by default: <strong><em>the exception type</em></strong> and <strong><em>message</em></strong>. The second line shows <strong><em>just the message</em></strong>. The rest shows a <strong><em>stack trace</em></strong>. The stack trace is usually the most helpful one <strong><em>because it shows where the exception occurred in each method that it passed through</em></strong>.</p><blockquote>On the OCA exam, you will mostly see the first approach.</blockquote><p>The stack trace <strong><em>shows all the methods on the stack</em></strong>. Every time <strong><em>you call a method, Java adds it to the stack until it completes</em></strong>. <strong><em>When an exception is thrown</em></strong>, it <strong><em>goes through the stack until it finds a method that can handle it or it runs out of stack</em></strong>.</p><h3>Summary</h3><ul><li>An exception indicates something unexpected happened.</li><li>A <strong><em>method can handle an exception by catching it</em></strong> or <strong><em>declaring it for the caller to deal with</em></strong>.</li><li>Many exceptions are thrown by Java libraries.</li><li>You can <strong><em>throw your own exception with code</em></strong> such as</li></ul><blockquote><strong>throw new Exception()</strong>.</blockquote><ul><li><strong><em>Subclasses of java.lang.Error</em></strong> are exceptions that a programmer <strong><em>should not attempt to handle</em></strong>.</li><li><strong><em>Subclasses of java.lang.RuntimeException</em></strong> are <strong><em>runtime (unchecked) exceptions</em></strong>.</li><li><strong><em>Subclasses of java.lang.Exception</em></strong>, but <strong><em>not java.lang.RuntimeException</em></strong> are <strong><em>checked exceptions</em></strong>.</li><li>Java requires <strong><em>checked exceptions to be handled or declared</em></strong>.</li><li>If <strong><em>a try statement has multiple catch blocks</em></strong>, <strong><em>at most one catch block can run</em></strong>.</li><li>Java looks for an exception that can be caught by each catch block<strong><em> in the order they appear, </em></strong>and the<strong><em> first match is run</em></strong>. Then execution continues after the try statement.</li><li>If both <strong><em>catch and finally throw an exception</em></strong>, the <strong><em>one from finally gets thrown</em></strong>.</li><li>The common runtime exceptions include:</li></ul><ol><li>ArithmeticException</li><li>ArrayIndexOutOfBoundsException</li><li>ClassCastException</li><li>IllegalArgumentException</li><li>NullPointerException</li><li>NumberFormatException</li></ol><p><strong><em>IllegalArgumentException</em></strong> and <strong><em>NumberFormatException</em></strong> are <strong><em>typically thrown by the programmer</em></strong>, whereas the <strong><em>others are typically thrown by the JVM</em></strong>.</p><ul><li>Common checked exceptions include:</li></ul><ol><li>IOException</li><li>FileNotFoundException</li></ol><ul><li>Common errors include:</li></ul><ol><li>ExceptionInInitializerError</li><li>StackOverflowError</li><li>NoClassDefFoundError</li></ol><ul><li>When <strong><em>a method overrides a method in a superclass or interface</em></strong>, it is <strong><em>not allowed to add checked exceptions</em></strong>. It is allowed to <strong><em>declare fewer exceptions</em></strong> or <strong><em>declare a subclass of a declared exception</em></strong>. <strong><em>Methods declare exceptions with</em></strong> the keyword<strong><em> throws</em></strong>.</li></ul><h3>Exam Essentials</h3><p>💡 <strong><em>Unchecked exceptions</em></strong> are also known as <strong><em>runtime exceptions</em></strong> and are <strong><em>subclasses of java.lang.RuntimeException</em></strong>.</p><p>💡<strong><em> All other subclasses</em></strong> <strong><em>of java.lang.Exception</em></strong> are <strong><em>checked exceptions</em></strong>.</p><p>💡 A <strong><em>try statement</em></strong> <strong><em>must</em></strong> have a <strong><em>catch or a finally block</em></strong>.</p><p>💡 <strong><em>Multiple catch blocks are also allowed</em></strong>, provided <strong><em>no superclass exception type appears in an earlier catch block than its subclass</em></strong>.</p><p>💡 The <strong><em>finally block</em></strong> runs <strong><em>last</em></strong> <strong><em>regardless </em></strong>of whether<strong><em> an exception is thrown</em></strong>.</p><p>💡 <strong><em>IllegalArgumentException</em></strong> and <strong><em>NumberFormatException</em></strong> are <strong><em>commonly thrown by the programmer</em></strong>. Most of the <strong><em>other runtime exceptions</em></strong> are <strong><em>typically thrown by the JVM.</em></strong></p><p>💡 The <strong><em>throws</em></strong> keyword is used in a <strong><em>method declaration</em></strong> to <strong><em>indicate an exception might be thrown</em></strong>.</p><p>💡 When <strong><em>overriding a method</em></strong>, the <strong><em>method is allowed to throw fewer exceptions than the original version</em></strong>.</p><p>💡 The<strong><em> throw</em></strong> keyword is used when you <strong><em>actually want to throw an exception</em></strong>.</p><p>💡 The <strong><em>throws</em></strong> keyword is used in a <strong><em>method declaration</em></strong>.</p><p>Hope this article is useful!!! 😃</p><p>Happy Learning!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32819f8ea9fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OCA Chapter 03 — Core Java APIs]]></title>
            <link>https://medium.com/@lakkuga/oca-chapter-03-core-java-apis-88266b49d25c?source=rss-ed774cb971e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/88266b49d25c</guid>
            <category><![CDATA[oca]]></category>
            <category><![CDATA[core-java-apis]]></category>
            <dc:creator><![CDATA[Lakshini Kuganandamurthy]]></dc:creator>
            <pubDate>Thu, 19 May 2022 14:32:49 GMT</pubDate>
            <atom:updated>2022-05-30T14:56:17.139Z</atom:updated>
            <content:encoded><![CDATA[<h3>Core Java APIs</h3><blockquote>Hi all!!!😃 This is an article to share some knowledge on core APIs in Java, every Java engineer should know!!!😅 Hope this will be of help for you all too!!! Ok, Let’s get started!!!💪</blockquote><p>The points cover the following topics :</p><ol><li>Operators and Decision Constructs</li><li>Creating and using arrays</li><li>Classes from the Java API</li><li>Java Data types</li></ol><h3>Creating and Manipulating Strings</h3><pre>String name = &quot;Fluffy&quot;; -------------statement 01<br>String name = new String(&quot;Fluffy&quot;);------------statement 02</pre><p>The “name” variable above is a reference type. We also know that <strong><em>reference types are created using the new keyword</em></strong>. But statement 01 does not have a new keyword in it right 😕 In Java, both the above code snippets create a String object. Both the ‘name’ reference variables point to the String object, “Fluffy”.</p><h4>Concatenation</h4><p>What does the code below output???</p><pre>System.out.print(&quot;1&quot; + &quot;2&quot;);</pre><pre>//output is 12</pre><p>Here, “1” is a String object and “2” is a String object. Using the ‘+’ operator, Java combines the two String objects. <strong><em>Placing one String before the other String and combining them together is called string concatenation</em></strong>.</p><h4>Rules for concatenation</h4><ol><li>If both operands are numeric, + means numeric addition.</li><li>If either operand is a String, + means concatenation.</li><li>The expression is evaluated left to right.</li></ol><p>Let’s look at an e.g considering the above rules.</p><pre>int three = 3;<br>String four = &quot;4&quot;;<br>System.out.println(1 + 2 + three + four);</pre><pre>//Output is : 64</pre><blockquote>First, we need to<strong> check the variable types here</strong>. We start with the third rule, and the first rule gives the result as 3 (1 + 2). Next, we have 3 + three, since three is of type int, the first rule applies and result is 6. Next is 6 + four, where four is of type String and second rule applies leading to the final result as “64” (the quotes for the String are only used in code and we don’t get them in output).</blockquote><p>The final point in concatenation is the<strong><em> use of += with String</em></strong>. Let’s follow the below e.g.</p><pre>String s = &quot;1&quot;;   // s currently points to object with value 1<br>s += &quot;2&quot;;        // s now points to another object with value 12<br>s += 3;       //  s now points to another object with value 123<br>System.out.println(s);  //123</pre><blockquote>In the above code, line 3 adds a number to “s” and the second rule is applied to get the result, 123. Second rule recap: A String + anything else means to use concatenation.</blockquote><p>❗️The 3 rules recap!!!</p><p>💡 use numeric addition if two numbers are involved.</p><p>💡 use concatenation otherwise (even when one String is involved).</p><p>💡 Evaluate from left to right.</p><h4>Immutability in Strings</h4><p>This is simply, <strong><em>Once a String object is created, it is not allowed to change</em></strong>. So, what do you really mean by “not allowed to change”. Here it is, <strong><em>it cannot be made larger or smaller and cannot change one of the characters inside it</em></strong>.</p><p>The following e.g. proves the above concept. Here, we are using another way to do String concatenation, the concat() method. Let’s check what this outputs???</p><pre>String s1 = &quot;1&quot;;<br>String s2 = s1.concat(&quot;2&quot;);<br>s2.concat(&quot;3&quot;);<br>System.out.println(s2);         //Output is 12</pre><pre>System.out.println(s1);        //Output is 1</pre><blockquote>Remember String objects are immutable 💡 Therefore, s1 points to the object with value 1, and s2 points to another object with value 12, here, “2” is added to the value of the object that s1 points to as in code, but this is considered a second object!!! if you try printing s1, it will still output 1, this is because String objects are immutable 😃 Line 3 adds a “3” but since it is not assigned to any variable(like s2), s2 still points to the object with value 12.</blockquote><h4>String pool</h4><p>Since Strings are everywhere in Java, they use up a lot of memory. That is, in certain production applications they may use, 25–40% of the memory in the entire program, and many strings are repeated in the program. Therefore, Java <strong><em>solves these issues by reusing common strings</em></strong>. Java does this, by allowing the String class to maintain a <strong><em>String pool, also known as the intern pool, a location in the JVM Heap memory</em></strong>. This collects all these strings.</p><p>The String pool <strong><em>contains only the literal values</em></strong>, that appear in our program. “name” is a literal and therefore goes into the String pool, but myObject.toString() (this method returns a String object but it is not a literal itself or what it returns!!!) line is not a literal, so it does not go into the String pool. <strong><em>Strings not in the string pool are garbage collected, like any other object!!!</em></strong></p><pre>String name = &quot;Fluffy&quot;;<br>String name = new String(&quot;Fluffy&quot;);</pre><blockquote>In line 01, JVM uses the String pool. “Fluffy” is a literal value and therefore, a String object with the value “Fluffy” <strong>is created in the String pool</strong>. Line 02 tells JVM explicitly, to create a new object with the value “Fluffy”. <strong>Therefore, this object will be created outside the String pool, in the heap</strong> (<strong>String pool is a location in the JVM heap memory area</strong>).</blockquote><h4>String Methods</h4><p>We will discuss 13 methods from the String class here, which are tested in the exam!!!</p><ol><li><strong>length()</strong></li></ol><p>The method length() <strong><em>returns the number of characters in the String</em></strong>. The following is the method signature:<strong> int length(),<em> which returns an int value, </em></strong>as in below e.g.</p><pre>String s = &quot;animals&quot;;<br>System.out.println(s.length());    //output is 7</pre><p>2.<strong> charAt()</strong></p><p>The method charAt() lets you query the string to find out what character is at a specific index. The method signature is as follows: <strong>char charAt(int index), <em>which returns a char value and takes the index as a parameter </em></strong>as in below e.g.</p><pre>String s = &quot;animals&quot;;<br>System.out.println(s.charAt(0));       //outputs a<br>System.out.println(s.charAt(6));      //outputs s<br>System.out.println(s.charAt(7));     // throws exception</pre><blockquote>Since indexes start counting with 0, charAt(0) and charAt(6) returns the “first” and the “last”(seventh) character in the sequence. But charAt(7) <strong>throws a java.lang.StringIndexOutOfBoundsException exception,</strong> as it asks for the “eighth” character in the sequence and there are only 7 characters present.</blockquote><p>3.<strong> indexOf()</strong></p><p>The method indexOf(), looks at the characters in the string and finds the first index that matches the desired value. This takes an individual character or a whole string as a parameter. We can also pass the index as a parameter.</p><p>Following are the method signatures :</p><p><strong>int indexOf(char ch)</strong>, <strong>int indexOf(char ch, index fromIndex)</strong>, <strong>int indexOf(String str)</strong>, <strong>int indexOf(String str, index fromIndex)</strong></p><p>Following e.g. demonstrates the above method signatures.</p><pre>String string = &quot;animals&quot;;<br>System.out.println(string.indexOf(&#39;a&#39;));           // 0<br>System.out.println(string.indexOf(&quot;al&quot;));          // 4<br>System.out.println(string.indexOf(&#39;a&#39;, 4));        // 4<br>System.out.println(string.indexOf(&quot;al&quot;, 5));       // -1</pre><blockquote>Unlike charAt(), <strong>the indexOf() method doesn’t throw an exception if it can’t find a match</strong>.<strong><em> </em>indexOf() returns –1 when no match is found</strong>. This is because indexes start with 0, when it returns -1, the caller knows that it can’t be a valid index. Thus signifies the caller that no match was found.</blockquote><p>4. <strong>substring()</strong></p><p>The method substring() also looks for characters in a string and it returns parts of the string based on the index passed as the first parameter, this is the starting index from which a substring is returned. There is an optional second parameter, which is the end index we might want to <strong><em>stop at</em></strong>. Notice we said “stop at” rather than “include.” Below is the method signatures:</p><p><strong>int substring(int beginIndex)</strong>, <strong>int substring(int beginIndex, int endIndex)</strong></p><p>Following e.g. demonstrates the above method signatures:</p><pre>String string = &quot;animals&quot;;<br>System.out.println(string.substring(3));                   // mals<br>System.out.println(string.substring(string.indexOf(&#39;m&#39;))); // mals<br>System.out.println(string.substring(3, 4));                // m<br>System.out.println(string.substring(3, 7));                // mals</pre><blockquote>The first print statement says to take the characters starting with index 3 through the end. The second print statement does the same thing: <strong>it calls indexOf()</strong> to get the index rather than hard-coding it. The third example says to take the characters starting with index 3 <strong>until, but not including</strong>, the character at index p4. The final print statement says to take the characters starting with index 3 until we get to index 7, <strong>since index 7 is the same as the end of the string</strong>, it is equivalent to the first print statement. Also, if the start and end indexes are the same, the substring() method returns an empty string. What if the endIndex is smaller than the startIndex, it will throw an exception, because Java knows perfectly well that it will never get to index 2 if it starts with index 3. Another e.g. is that the endIndex is larger than the length of the string. Java throws an exception because there is no eighth position in the string.</blockquote><blockquote><strong>emphasizing again!!!!</strong></blockquote><blockquote>The method returns the <strong>string starting from the requested index</strong>. If an end index is requested,<strong> it stops right before that index</strong>. Otherwise, <strong>it goes to the end of the string</strong>.</blockquote><p>5. <strong>toLowerCase() and toUpperCase()</strong></p><p>Following are the method signatures:</p><p><strong>String toLowerCase(String str)</strong>, <strong>String toUpperCase(String str)</strong></p><p>Following is an e.g. of the above method signatures:</p><pre>String str = &quot;animals&quot;;<br>System.out.println(str.toUpperCase());           // ANIMALS<br>System.out.println(&quot;Abc123&quot;.toLowerCase());     // abc123</pre><blockquote>toUpperCase() converts any <strong>lowercase characters</strong> <strong>to uppercase</strong> in the returned string. toLowerCase() converts any <strong>uppercase characters to lowercase</strong> in the returned string. These methods only convert the letters and not any other characters. Also, remember that <strong>strings are immutable</strong>,<strong> so the original string stays the same</strong>.</blockquote><p>6. <strong>equals() and equalsIgnoreCase()</strong></p><p>The <strong><em>equals() method</em></strong> checks whether <strong><em>two String objects contain exactly the same characters in the same order</em></strong>. The <strong><em>equalsIgnoreCase()</em></strong> method checks whether <strong><em>two String objects contain the same characters with the exception that it will convert the characters’ case if needed. </em></strong>The method signatures are as follows:</p><p><strong>boolean equals(String str)</strong>,<strong> boolean equalsIgnoreCase(String str)</strong></p><p>Following e.g illustrates how these two methods are used.</p><pre>System.out.println(&quot;abc&quot;.equals(&quot;ABC&quot;));               // false<br>System.out.println(&quot;ABC&quot;.equals(&quot;ABC&quot;));               // true<br>System.out.println(&quot;abc&quot;.equalsIgnoreCase(&quot;ABC&quot;));     // true</pre><blockquote>In the first statement, the values aren’t <strong>exactly the same (taking account of the case)</strong>. In the second statement, <strong>they are exactly the same</strong>. In the third statement, they differ only by case, but we called the method that <strong>ignores the differences in case</strong>.</blockquote><p>7. <strong>startsWith() and endsWith()</strong></p><p>The startsWith() and endsWith() methods look at whether the provided value matches part of the String. Method signatures are as follows:</p><p><strong>boolean startsWith(String prefix)</strong>,<strong> boolean endsWith(String suffix)</strong></p><pre>System.out.println(&quot;abc&quot;.startsWith(&quot;a&quot;));     // true<br>System.out.println(&quot;abc&quot;.startsWith(&quot;A&quot;));    // false<br>System.out.println(&quot;abc&quot;.endsWith(&quot;c&quot;));     // true<br>System.out.println(&quot;abc&quot;.endsWith(&quot;a&quot;));    // false</pre><blockquote>Java is basically doing a case-sensitive check on the values provided.</blockquote><p>8.<strong> contains()</strong></p><p>This method also looks for matches in the String. Not as particular as<br>startsWith() and endsWith() — <strong><em>the match can be anywhere in the String</em></strong>.</p><p>Following is the method signature:</p><p><strong>boolean contains(String str)</strong></p><p>Following e.g. illustrates the above method signature:</p><pre>System.out.println(&quot;abc&quot;.contains(&quot;b&quot;));        // true<br>System.out.println(&quot;abc&quot;.contains(&quot;B&quot;));       // false</pre><blockquote>Again, we have a case-sensitive search in the String. This is a convenience method instead of <strong>str.indexOf(otherString) != -1, </strong>e.g. in while loops<strong>.</strong></blockquote><p>9. <strong>replace()</strong></p><p>The replace() method does a simple search and replace on the string. There’s a version that takes char parameters as well as a version that takes CharSequence parameters. Following is the method signature:</p><p><strong>String replace(char oldChar, char newChar)<br>String replace(CharSequence oldChar, CharSequence newChar)</strong></p><pre>System.out.println(&quot;abcabc&quot;.replace(&#39;a&#39;, &#39;A&#39;));     // AbcAbc<br>System.out.println(&quot;abcabc&quot;.replace(&quot;a&quot;, &quot;A&quot;));    // AbcAbc</pre><blockquote>The first statement passes char parameters as in the first method signature and the second statement passes string parameters as in the second.</blockquote><p>10. <strong>trim()</strong></p><p>The trim() method removes whitespace from the beginning and end of a String. <strong><em>In the exam, whitespace consists of spaces along with the \t (tab) and \n (newline) characters</em></strong>. Other characters, such as \r (carriage return), are also included in what gets trimmed. Following is the method signature:</p><p><strong>String trim()</strong></p><pre>System.out.println(&quot;abc&quot;.trim());             // abc<br>System.out.println(&quot;\t   a b c\n&quot;.trim());   // a b c</pre><blockquote>The first statement prints the original string because there are <strong>no whitespace characters at the beginning or end</strong>. The second statement <strong>gets rid of the leading tab, subsequent spaces, and the trailing newline</strong>. <strong>It leaves the spaces that are in the middle of the string</strong>.</blockquote><h4><strong>Method Chaining</strong></h4><p>Calling multiple methods on the same String, as shown below:</p><pre>String start = &quot;AniMaL    &quot;;<br>String trimmed = start.trim();                 // &quot;AniMaL&quot;<br>String lowercase = trimmed.toLowerCase();     // &quot;animal&quot;<br>String result = lowercase.replace(&#39;a&#39;, &#39;A&#39;);  // &quot;Animal&quot;<br>System.out.println(result);                   //Animal</pre><p>Above code is just a series of String methods. Each time one method is called, the returned value is put in a new variable. There are 4 String values here.</p><p>In the exam, you’ll see code using a technique called <strong><em>Method Chaining, </em></strong>as in the e.g. below</p><pre>String result = &quot;AniMaL   &quot;.trim().toLowerCase().replace(&#39;a&#39;, &#39;A&#39;);<br>System.out.println(result);    //Animal</pre><p>This code is equivalent to the previous example and outputs the same result, Animal. It also creates <strong><em>4 String objects</em></strong>, because remember <strong><em>String is immutable</em></strong>. To read code that uses method chaining, <strong><em>start at the left and evaluate the first method</em></strong>. Then <strong><em>call the next method on the returned value of the first method</em></strong>. Keep repeating until the semicolon!!!</p><h4>StringBuilder class ❗️</h4><p><strong><em>Unlike the String class, StringBuilder is not immutable</em></strong>.</p><p>Consider the below code.</p><pre>StringBuilder alpha = new StringBuilder();<br>for(char current = &#39;a&#39;; current &lt;= &#39;z&#39;; current++)<br>    alpha.append(current);<br>System.out.println(alpha);</pre><p>First, a new StringBuilder object is instantiated and “alpha” variable pointed to this object. The call to append() adds a character to the StringBuilder object each time through the for loop and appends the value of “current” to the end of “alpha”. This code <strong><em>reuses the same StringBuilder object without creating an interim String each time</em></strong>.</p><p>In method chaining, when we chained String method calls, <strong><em>the result was a new String with the answer</em></strong>. Chaining StringBuilder objects doesn’t work this way. Instead, the StringBuilder changes its own state and returns a reference to itself! Follow the below e.g.</p><pre>StringBuilder sb = new StringBuilder(&quot;start&quot;);<br>sb.append(&quot;+middle&quot;);                    // sb = &quot;start+middle&quot;<br>StringBuilder same = sb.append(&quot;+end&quot;);  // &quot;start+middle+end&quot;</pre><p>The stack and heap representation for the above code is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*cLcizCQCcH28tJh7agbpQg.png" /><figcaption>stack and heap representation</figcaption></figure><p>Since StringBuilder objects are not immutable, the call to append() will add “+middle” text to “start” value. This <strong><em>returns a reference to sb, which is ignored</em></strong>. The call to append() again adds “+end” text to the current value of the StringBuilder object and<strong><em> returns a reference to sb</em></strong>. <strong><em>This time the reference is stored in a “same” variable, </em></strong>which implies that “<strong><em>sb” and “same” variables point to the exact same object and would print out the same value</em></strong>.</p><h4>How to create a StringBuilder???</h4><p>There are three ways to construct a StringBuilder as follows.</p><pre>StringBuilder sb1 = new StringBuilder();<br>StringBuilder sb2 = new StringBuilder(&quot;animal&quot;);<br>StringBuilder sb3 = new StringBuilder(10);</pre><p>The first says to create a StringBuilder containing an empty sequence of characters and assign sb1 to point to it. The second says to create a StringBuilder containing a <strong><em>specific value</em></strong> and assign sb2 to point to it. The final example <strong><em>tells Java that we have some idea of how big the eventual value will be</em></strong> and would like the StringBuilder to <strong><em>reserve a certain number of slots for characters</em></strong>.</p><h4>StringBuilder methods</h4><h4>insert()</h4><p>The insert() method adds characters to the StringBuilder at the requested index and returns a reference to the current StringBuilder.</p><p>The following is the method signature:</p><p><strong>StringBuilder insert(int offset, String str)</strong></p><h4>StringBuilder vs StringBuffer</h4><p>When writing new code that <strong><em>concatenates a lot of String objects together</em></strong>, <strong><em>you should use StringBuilder</em></strong>. StringBuilder was added to Java in Java 5. If you come across older code, you will see <strong><em>StringBuffer</em></strong> used for this purpose. <strong><em>StringBuffer does the same thing but more slowly because it is thread safe</em></strong>.</p><h4>Understanding equality using StringBuilder objects</h4><p>Do you remember that we used <strong><em>== to compare object references</em></strong> and this <strong><em>returns true when the object references refer to the same object (i.e. they point to the same memory location in the heap)</em></strong>.</p><p>Observe the code below.</p><pre>StringBuilder one = new StringBuilder();<br>StringBuilder two = new StringBuilder();<br>StringBuilder three = one.append(&quot;a&quot;);<br>System.out.println(one == two); // false<br>System.out.println(one == three); // true</pre><p>Here, <strong><em>“one” reference variable points to one StringBuilder object </em></strong>and<strong><em> “two” reference variable points to another Stringbuilder object</em></strong>. The reference variable “three” points to the same StringBuilder object that “one” points to, but the call to append() will add “a” to the empty sequence of the StringBuilder object that “one” points to. This is because<strong><em>, append() returns a reference to the current StringBuilder object and StringBuilder is not immutable</em></strong>, therefore, <strong><em>“one” and “three” points to the same StringBuilder object with a value, “a”</em></strong>. That is why the final print statement will print “true”.</p><p>wqwqwqqw</p><blockquote>This article is quite long, but I am sure you will get the necessary basics!!!😅</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88266b49d25c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Threads in Java]]></title>
            <link>https://medium.com/sliitwif/threads-in-java-7d0b0996cf43?source=rss-ed774cb971e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d0b0996cf43</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Lakshini Kuganandamurthy]]></dc:creator>
            <pubDate>Tue, 10 May 2022 18:16:40 GMT</pubDate>
            <atom:updated>2022-05-20T17:22:20.481Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>This was a very difficult topic for me to learn during my university days maybe because I thought it was hard and boring!!! Until recently, I found it more interesting. So, here you go, some knowledge I gained recently!!!</blockquote><blockquote>Believe me, it is gonna be easy!!! Let’s dive into the basics!!!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*45SdtkKQcW_53mDcgeInUg.png" /><figcaption>Intro image</figcaption></figure><p>It has always been a misunderstanding, that <em>threads are there to cut down time!!! For e.g. if there is a process running for 10 mins, there is no guarantee that you can use 10 threads to cut down the time to 1 min (to make the process run only for a minute).</em></p><p>Let’s prove this by an example. <em>This is not a real-world example and the process steps and durations are just assumed!!!</em></p><p>Say we have a 5 step process as follows :</p><ol><li>Validate takes 1s to complete.</li><li>Preparation takes 2s to complete.</li><li>Calculating the currency rate takes 5s to complete.</li><li>Updating the model takes 2s.</li><li>Saving to the database takes 1s.</li></ol><p>Therefore the total duration the process will run is 11s. Ok, since there are 5 steps, do you think it is possible to use 5 threads to cut down the time to, say (11s / 5 = 2s)??? <strong><em>Not at all, it is not possible to use 5 threads to cut down time from 11s to 2s.</em></strong> But why???</p><p><strong><em>This is because there are dependency steps or tasks in the process. </em></strong>It is impossible to save data before validating and preparing it, so the step, “saving to database” depends on both the tasks, “validating and preparing the data”.<em> </em><strong><em>Therefore, it is not practical to have a thread to perform the saving task since it depends on other tasks</em></strong><em> (because before completing those tasks, saving cannot be done). But, using threads we can perform certain tasks parallelly to cut down time to 7s or 8s from the original 11s. Such as we can have two threads running concurrently, one thread to perform preparation and validation tasks and another to perform calculating the currency rate, parallelly.</em></p><h4>The point is, We cannot use separate threads for each task and cut down processing time, if these tasks are dependent. There is no way that you increase the number of threads and cut down processing time drastically!!! This is of course not Multithreading!!!</h4><p>Then what does multithreading mean??? <strong>Multithreading means multitasking!!! </strong>There are two types of multitasking namely,</p><ol><li><strong>Process-based multitasking</strong> — We, software engineers, do enjoy listening to music while developing a cool app right!!! Maybe there is also a movie being downloaded at the same time or we want a break and we browse Facebook. Here, there are multiple processes running at the same time on our computer. In a given time, there are 3 or 4 processes running. If the movie download is paused for some time, will that stop the music we listen??? or terminate our browsing window??? Not at all, <strong><em>these tasks are all independent of each other.</em></strong> We can kill any task at any given time, which will not affect other tasks running parallelly. This is possible because the <strong><em>operating system runs multiple processes at the same time, which are also known as multiple programs.</em></strong></li><li><strong>Thread-based multitasking —</strong> Here, <strong><em>all the threads running belong to the same process </em></strong><em>or we can say the same main process running In the operating system (OS). In process-based, we saw that there were 3 different processes running in the OS. Therefore, here, one process is broken down into multiple tasks.</em></li></ol><blockquote>Let’s take the following e.g. there are 50 files to process and the tasks are to read the file and save the file to the database. This process takes 50 mins to complete. Let’s assume that the database supports multithreading (multiple threads running concurrently) i.e. two or more threads can insert the read file data to the database at the same time. When using two threads, we can cut down the time to probably 30 mins. How this really works is, that one thread takes a file, processes it, and saves it to the database. At the same time, another thread takes another file, processes it, and saves it to the database. This is possible because reading and saving each file is an independent task. <strong>No dependency among tasks</strong>, so therefore at most, <strong>we can use 50 threads to process the 50 files</strong> and cut down the time to 10 mins probably. But, there is no way that we can use 100 threads to cut down the time to 1s or 2. There is no point in using two threads for each file, maybe one thread to read the file and another to save it to the database, these cannot run parallelly because to save a file, it has to be read first!!! So, the saving task depends on the reading task!!! or simply it is a waste of resources for 2 threads to process the same file!!!</blockquote><h4>Therefore the point is, that we cannot always increase the number of threads to cut down the time drastically from mins to seconds.</h4><h4>Multithreading is possible in situations of independent tasks in a process.</h4><p>Ok, we discussed so much about the threads, but did we say what actually a thread is???</p><p><strong><em>A thread is a flow of execution</em></strong> and simply <strong><em>multithreading is defined as multiple flows of execution</em></strong>.</p><p>A single thread executes all the instructions in the flow of the program. If multithreading, at a certain point in the instruction flow, it may divide into multiple flows of execution as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*6_pzSNdA1O8_-2UoQHWABg.png" /><figcaption>demonstrating multithreading — multiple flows of execution</figcaption></figure><p>Hope, you all got an understanding!!! Now let’s see, how we can create a thread in Java!!!</p><p>Threads can be created in two ways in Java as follows :</p><ol><li>Extends Thread class</li><li>Implements Runnable interface</li></ol><p>No matter, how threads are created, the behaviour of threads will not change. But they have their pros and cons. Let’s take the e.g. shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*IXNW7ytstWBU_DShGc7dlg.png" /><figcaption>Demonstration for difference between Thread class and Runnable interface</figcaption></figure><p>The above diagram shows a simple inheritance, where Runner IS A Sportsman and Sportsman IS A Man and Man IS A Human. Therefore, a Runner IS A Human. The Runner is more specific than the Sportsman and the Sportsman is more specific than the Man and the Man is more specific than the Human. This is a simple explanation of inheritance!!!</p><blockquote>These are all considered Java classes by the way!!!</blockquote><p>Now, if we want to convert the Runner to a Thread, we create another inheritance relationship between the Runner and Thread classes as shown above.<strong><em> Then Runner extends Thread. This extension would break the relationship between Runner and Sportsman. </em></strong>Runner is no longer a Sportsman but IS A Thread. This implies that Runner is no longer a Human too!!! The multi-level inheritance relationship is broken, the moment Runner extends Thread!!!<strong><em> So, this is one disadvantage when creating threads by extending the Thread class.</em></strong></p><p>This is because <strong><em>Java does not support multiple inheritance</em></strong>, i.e. Java classes can only extend or inherit from one parent class at a time. <em>There can’t be classes inheriting multiple parent classes at the same time!!! Runner either has to inherit Sportsman OR Thread!!!</em></p><p>Creating a thread by implementing the Runnable interface has no such disadvantages as breaking relationships because <strong><em>Java supports multiple implementations. So, Runner can always implement the Runnable interface and other interfaces at the same time.</em></strong></p><p>Now, let’s discuss the actual Thread code, with Thread class methods!!!</p><p>Here, we have a <strong><em>class Printer that extends Thread class</em></strong>. Therefore, we will <strong><em>override the run() method of the Thread class</em></strong>, to print from 0–1000.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c6f7419fc4630415fc1801fe308a7cd/href">https://medium.com/media/0c6f7419fc4630415fc1801fe308a7cd/href</a></iframe><p>Following class has the main method, in which the Printer class is instantiated. We instantiate a Thread i.e., we create a thread. Then we call start() method, but there is no start() method in the Printer class. Printer inherits from Thread class, so start() method of the Thread class is called here.</p><p>If you remembered, JVM, when created or started, creates a non-daemon thread that runs the main method. Later, this main thread also prints from 0–100, as shown below in code. Upto line 5, there is only one thread running, which is the main thread. When you start the new Thread at line 10, there will be 2 threads running in the program. The newly created thread is a child thread of the main thread. But there is no guarantee that the moment we call the start() method on the newly created thread, it will start instantly. This is because the thread has to go through several steps for it to officially start running.</p><p>After start() method is called on the new Thread, (line 10 is just an instruction to the main thread similar to other instructions in the main method), it executes the remaining instructions of printing from 0–100.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a161556f7cc93cec057e2154418bc24c/href">https://medium.com/media/a161556f7cc93cec057e2154418bc24c/href</a></iframe><p>Ok, since you have understood the above code, let’s discuss a tricky interview question based on this scenario.</p><p>As you saw, the main thread starts a new thread which is the child thread of the main thread and it is supposed to print from 0–1000. After calling the start() method on its child thread, main thread continues to execute line 13 and prints from 0–100. During this time, the child thread would have started running and printing. Logically, 0–100 is printed fairly quicker than 0–1000.</p><blockquote>So the interview question is will the program or (more clearly the JVM) terminate after the main thread completes printing from 0–100 (say during this time, the Printer thread is printing somewhere around 200), this way child thread won’t be able to complete its job, or will the program wait till the child thread completes and then exit???</blockquote><p>Most developers think that JVM terminates or exits (i.e. the running application terminates) when the main thread exits. But this is totally wrong!!!</p><p>JVM terminates or exits only in either of the following 2 ways :</p><ol><li>When programmer explicitly invokes exit() method -&gt; System.exit()</li><li>When the last non-daemon thread exits.</li></ol><p>Here, we did not mention explicitly whether the new thread is a daemon or non-daemon thread, it will have the default behaviour.</p><blockquote>The default behaviour is that we already know that JVM, when started creates a non-daemon thread that runs the main method and is thus called the main thread. Therefore any threads created in the main method become the child thread of the main thread and inherit its daemon status. So, the new thread created at line 6 is also a non-daemon thread. So, the obvious answer is that the<strong><em> </em>JVM will wait till the new thread completes its job, printing from 0–1000, and then exit. Even though the main thread exits after printing 0–100, there is still a non-daemon thread running, so, JVM will exit once that thread completes 0–1000, and exits.</strong></blockquote><p>Phew!!! Hope you understood the basics we discussed so far. Let’s wrap up for now!!!</p><p>Happy Learning!!!</p><h3>References</h3><p><a href="https://www.youtube.com/watch?v=Y9JDbm8edOk&amp;list=PLD-mYtebG3X99o6vJ3uR5P6UcH3MQSWBH">https://www.youtube.com/watch?v=Y9JDbm8edOk&amp;list=PLD-mYtebG3X99o6vJ3uR5P6UcH3MQSWBH</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d0b0996cf43" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sliitwif/threads-in-java-7d0b0996cf43">Threads in Java</a> was originally published in <a href="https://medium.com/sliitwif">SLIIT Women In FOSS Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BFS and DFS]]></title>
            <link>https://medium.com/@lakkuga/bfs-and-dfs-6abde74daace?source=rss-ed774cb971e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6abde74daace</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[breadth-first-search]]></category>
            <category><![CDATA[depth-first-search]]></category>
            <dc:creator><![CDATA[Lakshini Kuganandamurthy]]></dc:creator>
            <pubDate>Fri, 15 Apr 2022 05:18:01 GMT</pubDate>
            <atom:updated>2022-05-17T06:25:38.771Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Not familiar??? Let’s discuss Breadth-First-Search (BFS) and Depth-First-Search (DFS) algorithms here!!!</blockquote><h3>DFS???</h3><p>Here, we do not explore vertices around the next level but go to the depth of the graph. We go deeper and explore the nodes connected to the source node, we started traversing, until the last node.</p><p>We often get fooled by looking at the node levels in a DFS graph, when traversing. We assume that if the nodes are located above each other, they are at different layers and not in the depth of the search. <strong><em>DFS is not traversing the layers of the graph but going deeper from a source node to the last node.</em></strong></p><blockquote>Therefore, do not get confused by looking at how the graph is drawn but consider the nodes connected to the source node and explore deeper into that path.</blockquote><blockquote>For a<strong> DFS</strong>, we <strong>cannot use a queue</strong> as the data structure!!! Why??? Because DFS means we go deeper from the source node/a specific node and traverse back (return to the same node). The clear rule is LIFO (Last-in-First-out), the element that enters last will be removed first. Therefore, the right candidate is the <strong>Stack</strong>!!!</blockquote><blockquote>But, the queue follows the FIFO (First-in-First-out) rule; the element that enters the first will be removed first. More applicable for the BFS. In BFS, all the nodes in the same level have to be explored first, before moving to the next layer /level.</blockquote><h4>Rules for DFS on an Undirected Graph</h4><ul><li>Traversing <strong><em>can start with any vertex</em></strong> (no specific rule saying that this should be the initial vertex/source node).</li><li>From the source node, <strong><em>traverse each adjacent vertices in that path till the last node</em></strong> (node that does not have an edge!!!) — assume the traversal as going deep down a tree branch!!!</li><li>When there is <strong><em>a node connected to two other nodes or more, any path can be taken</em></strong>, (no specific rule saying that traverse right then left!!!), i.e. <strong><em>any one node’s path</em></strong> can be followed till there are no adjacent, unvisited vertices of the last node.</li><li>When traversing a specific path in DFS, we always check for the <strong><em>adjacent unvisited vertices of the current node</em></strong>(plural of vertex, vertex means node).</li></ul><p>Let’s look at an example!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*SCy4ciTbz_8wJ6clJijpHg.png" /><figcaption>DFS Graph</figcaption></figure><h4>Steps for DFS Traversal</h4><ol><li>Start from any vertex, we will start from Vertex 0.</li><li>Initialize a Stack, and push node 0 to the Stack.</li><li>There are two paths that can be taken from node 0, <strong><em>take any one path</em></strong>, i.e. 1 or 3 (because these are the <strong><em>adjacent vertices</em></strong> to node 0).</li><li>We will take node 1’s path. Push node 1 to the Stack.</li><li>Node 1 has nodes 0, 3, 2, 6, and 5 as adjacent vertices. But <strong><em>we cannot go in node 0’s path, since it is already visited and pushed to the Stack</em></strong>. So, the options remaining are 3, 2, 6, and 5. We will take node 3’s path and push node 3 to the Stack.</li><li>Node 3 has nodes 0, 1, 2, and 4 as adjacent vertices. Nodes 0 and 1 are <strong><em>already visited and pushed to Stack</em></strong>. So the remaining vertices are 2 and 4. We will take node 2’s path. Push node 2 to the Stack.</li><li>Node 2 has nodes 1, 3, 4, and 5 as adjacent vertices, but 1 and 3 are visited and pushed to Stack. We will take node 4’s path and push it to the Stack.</li><li>Node 4 has nodes 3, 2, and 6 as adjacent nodes, but only node 6 is unvisited, so taking node 6’s path and pushing it to Stack.</li><li>Node 6 has nodes 1 and 4 as adjacent vertices but both are visited and already in the Stack. There are no other unvisited adjacent vertices to node 6 and we need to traverse backward.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/1*wP5EmkCyt-xV6r2hg6uWaQ.png" /><figcaption>Snap of the Stack before traversing backward</figcaption></figure><blockquote>When traversing backward, we will start from node 6 but how to continue??? We will use the Stack and pop out elements from it to traverse further in the graph!!! Here, upon each node, <strong>we have to check if that node has any adjacent unvisited nodes </strong>(to see if all the nodes have been traversed!!!).</blockquote><blockquote>Note: While popping out nodes from the Stack, during backward traversal (we use the stack to do this, because also to keep track of the traversal), did you see that you are popping out the last node you pushed to the stack!!! This is why DFS implementation follows the<strong> LIFO principle</strong>, and as a result, the <strong>Stack as its data structure</strong>.</blockquote><ol><li>Pop-out node 6 from the Stack, since it is the <strong><em>current top element </em></strong>of the Stack.</li><li>The next top element is node 4, we have to check if it has any unvisited adjacent vertices. Node 4 has nodes 2, 3, and 6 and all are visited. Therefore, we will pop out node 4 from the Stack.</li><li>The next top element in the Stack is node 2. Node 2 has <strong><em>node 5 as an adjacent vertex that has not been visited</em></strong>, therefore, node 5 will be pushed to the Stack.</li><li>The current top element of the Stack is node 5, are there any adjacent unvisited vertices of node 5??? No, then we need to traverse backward from here.</li><li>Pop-out node 5 from Stack.</li><li>The top element in the Stack now is node 2. Are there any adjacent vertices to node 2 which has not been visited??? No. Therefore, pop out node 2 from the Stack.</li><li>The top element is node 3, nodes 0, 1, 2, and 4, which are adjacent to it are all visited. So, pop out node 3 from the Stack.</li><li>Now, the top element is node 1, all adjacent vertices to it are visited and we will pop it out from the Stack.</li><li>Finally, node 0 is the only element and the top element in the Stack, Are there any adjacent vertices of 0 still unvisited??? No, so pop out node 0 from the Stack.</li></ol><blockquote>When the <strong>Stack becomes empty</strong>, it is the <strong>indication</strong> that we need to <strong>stop the DFS traversal.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*7bUZZzx7fs-2OGurOUfHkg.png" /><figcaption>Snap of Stack transition</figcaption></figure><p>So, one valid Depth-First-Search for the above graph is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*amXLlvk2RUes975jymfApw.png" /><figcaption>One valid traversal</figcaption></figure><blockquote>There can be alternative valid traversals for the above graph <strong>based on the path you choose to take</strong> e.g. initially, at node 0, if you choose to follow node 3’s path instead of node 1 (as in the example above), then the traversal will be <strong>0 3 ……</strong> and goes on!!!</blockquote><p>Hooray!!! Hope you understood the Depth-First-Search!!! Let’s look at BFS now!!!</p><h3>BFS???</h3><p>This is Breadth-First, where the <strong><em>graph is traversed layer by layer</em></strong>. <strong><em>All the nodes in each layer are explored before moving to the next layer</em></strong>.</p><p>When implementing BFS, <strong><em>the queue is used as the data structure</em></strong>. <strong><em>Queue follows the FIFO (First In First Out) rule</em></strong>. Why FIFO??? Let’s discuss the rules of BFS first!!!</p><h4>Rules for BFS on an Undirected Graph</h4><ol><li>Traversing can start with any vertex (There is no specific rule saying that this should be the initial vertex/source node).</li><li>From the source node/root node,<strong><em> we need to explore all the nodes connected to it </em></strong>(all adjacent vertices have to be explored).</li><li>The nodes connected to the initial node can be <strong><em>visited in any order.</em></strong></li><li>When exploring the nodes connected to a particular node, it has to be checked if that node is unvisited, to be inserted into the queue.</li></ol><blockquote>Note: Finding out <strong>adjacent vertices of any node</strong> is known as the <strong>exploration of that node</strong>!!!</blockquote><blockquote>There are 2 types of graphs, <strong>Directed and Undirected Graph.</strong></blockquote><blockquote><strong>Directed Graphs</strong> follow specific directions according to which the graph is traversed. Each vertex leads to the next based on a direction. Directions are specified on the graph!!!</blockquote><blockquote><strong>Undirected Graphs<em> </em></strong>do not have directions specified and can be traversed in any direction.</blockquote><p>Let’s check an example!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*SCy4ciTbz_8wJ6clJijpHg.png" /><figcaption>BFS Graph</figcaption></figure><h4>Steps for BFS Traversal</h4><ol><li>Start from any vertex, we will start from Vertex 0.</li><li>Initialize a Queue, and insert node 0 to the Queue.</li><li><strong><em>Now, we remove node 0 from the Queue, to mark it as “visited”.</em></strong></li><li>Then, we will explore the nodes connected or adjacent to node 0. In this case, nodes 1 and 3 are connected to node 0 and so are inserted into the queue. These nodes can be inserted in any order into the queue.</li><li>At the moment, we have nodes 1 and 3 in the queue, so, as per the FIFO rule (remove the node that was inserted first), <strong><em>node 1 will be removed from the queue and marked as “visited”.</em></strong></li><li>Now, we need to check the <strong><em>adjacent unvisited vertices</em></strong> of node 1. Node 1 is connected to nodes 0, 3, 2, 6, and 5. But <strong><em>node 0 is already visited</em></strong> and <strong><em>node 3 is already in the queue</em></strong>. Therefore, only nodes 2,6, and 5 will be inserted into the queue.</li><li><strong><em>Node 3 was inserted into the queue after node 1, and according to FIFO rule, it qualifies to be removed from the queue and marked as “visited”.</em></strong></li><li>Nodes 0, 1, 2, and 4 are adjacent vertices of node 3. <strong><em>But nodes 0 and 1 are visited and node 2 is already in the queue</em></strong>. Therefore only node 4 gets inserted into the queue.</li><li>Next, <strong><em>node 2 will be removed from the queue and marked as “visited”</em></strong>.</li><li>Nodes 1, 3, 4, and 5 are adjacent vertices of node 2. <strong><em>Since nodes 1 and 3 are already visited and nodes 4 and 5 are already in the queue</em></strong>, nothing has to be inserted into the queue. Therefore, <strong><em>the next element to be removed from the queue is node 6 and will be marked as “visited”.</em></strong></li><li>Adjacent vertices of node 6 are nodes 1 and 4. <strong><em>Node 1 is already visited and node 4 is already in the queue</em></strong>. Nothing has to be inserted into the queue, so we move to the next node that can be removed from the queue.</li><li>The next node to be<strong><em> removed from the queue will be node 5 and will be marked as “visited”.</em></strong></li><li>Adjacent vertices of node 5 are nodes 1 and 2. <strong><em>Since both nodes are visited</em></strong>, there is nothing to be inserted into the queue.</li><li>Finally, the only node remaining in the queue is <strong><em>node 4, which will be removed from the queue and marked as “visited”</em></strong>.</li></ol><blockquote>Now, that the<strong> queue is empty</strong> and <strong>it is the indication that we need to stop the BFS traversal.</strong></blockquote><blockquote>We <strong>keep track of “visited” nodes</strong> so that <strong>they are not revisited!!!</strong> To do that, we remove the nodes from the queue and mark them as “visited”!!!</blockquote><blockquote>Once removed, <strong>the adjacent, unvisited vertices of that node are inserted into the queue</strong>. Note that any adjacent vertices of that node that are unvisited but <strong>already in the queue</strong> must not be inserted into the queue again!!!</blockquote><p>The following diagram illustrates the status of the queue through BFS traversal!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*migYsMQH5Ct2MxC9GaMbIg.png" /><figcaption>status of queue</figcaption></figure><p>So, one valid Breadth-First-Search for the above graph is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*-FVW0S65Mx0d4Y2sDh3mCg.png" /><figcaption>One valid traversal</figcaption></figure><blockquote>There can be alternative valid traversals for the above graph <strong>depending on the order you insert the adjacent vertices of a node into the queue</strong>, e.g. initially, at node 0, if you choose to insert nodes 3 and 1 into the queue, in the order 3 and 1, then the traversal will be 0 3 1…so on!!!</blockquote><p>Hope you understood Breadth-First-Search!!!</p><p>If you are interested, please check out my <a href="https://github.com/Lakshikuga/Krish-training/tree/main/BFSDFS">GitHub</a> for the implementation of BFS and DFS!!!</p><p>Happy Learning!!!</p><h3>References</h3><ol><li><a href="https://www.youtube.com/watch?v=aMCI4AqVUug">https://www.youtube.com/watch?v=aMCI4AqVUug</a></li><li><a href="https://www.youtube.com/watch?v=vf-cxgUXcMk">https://www.youtube.com/watch?v=vf-cxgUXcMk</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6abde74daace" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String in Java is immutable]]></title>
            <link>https://medium.com/@lakkuga/string-in-java-is-immutable-a90f97067bd?source=rss-ed774cb971e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a90f97067bd</guid>
            <category><![CDATA[object-reference]]></category>
            <category><![CDATA[java-strings]]></category>
            <category><![CDATA[immutable]]></category>
            <dc:creator><![CDATA[Lakshini Kuganandamurthy]]></dc:creator>
            <pubDate>Sun, 10 Apr 2022 10:27:19 GMT</pubDate>
            <atom:updated>2022-04-17T05:42:29.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*cI8p7L4Ly__355VGxD7RmQ.png" /><figcaption>Java String</figcaption></figure><p>Ok, I know most of you all know this!!! I knew it too!!! But did we correctly understand the term <strong><em>“immutable”</em></strong> and do we know <strong><em>why Strings are immutable in Java???</em></strong></p><p>Ok, let’s dig in!!!</p><h4>What is immutability???</h4><p>In simple terms, <strong><em>Once an object is created, it cannot be modified or changed.</em></strong> A value and an object are two different terms in Java. <strong><em>Value</em></strong> is what <strong><em>an instance variable or a reference variable holds</em></strong>. <strong><em>An instance variable holds the actual value</em></strong> (based on the type) that e.g. a programmer provides. For e.g.</p><pre>int a = 123;<br>float s = 65.7;<br>String name = &quot;Lakshi&quot;;</pre><p>As you already know <strong><em>objects in Java</em></strong> are stored in the <strong><em>Heap area of the memory area in JVM</em></strong>. Refer to my <a href="https://medium.com/@lakkuga/java-a825ab31e444">article on JVM architecture</a>, for a better understanding. Therefore, a <strong><em>reference variable</em></strong> holds the <strong><em>memory address of the object it is pointing to, as its value. </em></strong>The figure below illustrates a reference variable “s”<strong><em>.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*ZzVPi8is3_Wsj_Kv-xqdTQ.png" /><figcaption>Illustration of a reference variable</figcaption></figure><p>Whereas an object is an <strong><em>instance of a class</em></strong> with many <strong><em>instance variables</em></strong> generally referred to as <strong><em>“properties”</em></strong>.</p><p><strong><em>String is a class in Java</em></strong>. Therefore, any variable declared with type “String” becomes a <strong><em>reference variable pointing to an instance of String class (i.e. String object)</em></strong>. As shown below, a <strong><em>variable “name”</em></strong> is <strong><em>assigned the value</em></strong> <strong><em>“John”</em></strong>. Later we change the <strong><em>value of the variable to “Jane”</em></strong>. So here, only the values of the reference variable, “name” is changed. The String object which is given the value “John” is never changed, when the “name” variable got modified to “Jane”.</p><pre>String name = &quot;John&quot;;<br>name = &quot;Jane&quot;;</pre><p>Confusing right??? Let’s dig in to see what happens in the stack and heap areas of the memory, for the code above!!!</p><p>As we said earlier, any object created in Java is stored in the Heap. When the <strong><em>“name” variable is assigned “John”,</em></strong> <strong><em>JVM creates an object in the Heap</em></strong> and <strong><em>sets its value to “John”</em></strong>(because, a String value is assigned, String is a class in Java, therefore a String object gets created). The <strong><em>“name” variable points to this object. </em></strong>This is illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*ry9bvohDS__xym8S5493zA.png" /><figcaption>Illustration of object reference</figcaption></figure><p>Later, <strong><em>when “name” is assigned “Jane”</em></strong>. This <strong><em>creates another String object and sets its value to “Jane”.</em></strong> Now, where does the “name” variable point to??? Yes, the <strong><em>“name” variable dereferences from “John” object and points to “Jane” object</em></strong>, as shown below.</p><p><em>Note that these are String objects which are given values “John” and “Jane”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*8youc42RFXoiG5W4ltQn8g.png" /><figcaption>Referencing with Objects</figcaption></figure><blockquote>So, did we change or modify the object??? No, but a new String object was created (Jane object) and the “name” variable starts pointing to the newly created object, i.e. the “name” variable now points to a different location in the heap (a different memory address). So, this implies that whenever you modify the value of the “name” variable, it creates a new Object with that value and “name” will point to that object thereafter!!! <strong><em>This is how String in Java is immutable!!!</em></strong></blockquote><blockquote>Just a reminder, note that both objects have different memory addresses, in the heap.</blockquote><p>Let’s see the reason why Java String was designed to be immutable!!!</p><h4>Why Java String is immutable???</h4><p>Observe the below code. These are three reference variables of type “String” having the same value “John”. We compare all three variables using the “==” and .equals() function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6358859b1a5bcf83ee5ddf85d7d0be32/href">https://medium.com/media/6358859b1a5bcf83ee5ddf85d7d0be32/href</a></iframe><p>This is represented in the Heap memory as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*pvA92XTDh7nHxV8p48U-nA.png" /><figcaption>Heap representation for he above code</figcaption></figure><blockquote><strong><em>The “==” compares the reference (memory address of the object pointing to) of the variables</em></strong>, since all the variables are pointing to the same object, the <strong>first 3 print statements will return “true”</strong></blockquote><blockquote><strong><em>The .equals() function compares the values of the objects, these variables point to</em></strong>, since all the variables point to the same object having the value “John”, <strong>the last 3 print statements too will return “true”.</strong></blockquote><p>Let’s say the String “John” occupies 4 bytes of heap memory. What if there were 1000 variables, assigned the value, “John”. There will be 1000 objects created in the heap with the value “John”. Therefore, it will occupy 4000 (4 x 1000) bytes of memory. Isn’t this a waste of heap memory, objects with the same value occupying this much space!!!</p><p>Yes, that is why Java uses a <strong><em>String pool to store String literals.</em></strong></p><h4>Java’s String pool</h4><p>A String pool is a storage area in the heap. Whenever a variable is declared with the type String (reference variable to a String object), a String object (to which the variable points) is created occupying space in the heap. Creating the same objects many times, in the heap, will reduce memory space and performance.</p><p>The string pool is maintained by the String class in Java. Therefore, the <strong><em>String class creates a pool of String literals</em></strong>, to decrease the number of String objects created in the JVM heap. Now, when a String literal is created (a String value assigned to the reference variable), JVM first checks the String pool for that literal. If the literal is already present in the pool, it returns a reference to the pooled instance (<strong><em>i.e. it will return the value stored in the reference variable that is already pointing to that literal, this will make the new reference variable start pointing to the object in the pool, this way the same object can be referenced by 1000s of variables saving heap space</em></strong>). If that literal is not present in the pool, JVM creates a new String Object (the literal as the value) in the String pool. <strong><em>It is also good to note that only distinct String objects are stored in the String pool!!!</em></strong></p><p>Also, note that there are 2 ways to create String Objects in the heap, in Java.</p><ol><li>Using String literal, e.g.</li></ol><pre>String str1 = &quot;Python&quot;;<br>String str2 = &quot;Data Science&quot;;</pre><p>2. Using the “new” keyword</p><pre>String str4 = new String(&quot;Java&quot;);<br>String str5 = new String(&quot;C++&quot;);</pre><p>Let’s consider the below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb34f35421191efb97bda16ea5d80573/href">https://medium.com/media/fb34f35421191efb97bda16ea5d80573/href</a></iframe><p>The heap and stack representations are as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*XjYI2qpcCm7uymKzyA2dSA.png" /><figcaption>Representation of heap and Stack when the “new” keyword is used</figcaption></figure><p>Here, whenever the “new” keyword is used to create String objects, we are asking JVM explicitly, to create a String object. Therefore <strong><em>JVM will create a String object with the value “John”, outside the String pool</em></strong> and “employee” will point to that object hereafter, as shown above.</p><p>So, when comparing “person” or “name” variables with “employee” using the “==”,<strong><em> will return false because the “employee” points to a different location (reference) in the heap now</em></strong>.</p><p>The .equals() function will anyway <strong><em>return true because all three variables point to objects with the same value, “John”.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*1SH_FmEcIdnseyy9_pIXSw.png" /><figcaption>Representation of Heap and Stack when the “new” keyword is used</figcaption></figure><p>Likewise when comparing<strong><em> “str1” and “str3” using “==”, will return true</em></strong>, because both refer to the same object. But <strong><em>“str1” or “str3” compared with “str5”, will return false</em></strong>, as “str5” points to the object explicitly created in the heap (using “new”).</p><blockquote><strong>Note that all the String objects created with the “new” keyword take place in the heap and not in the String pool.</strong></blockquote><blockquote>Also as said earlier, when “str1” is assigned “Python”, JVM checks the String pool, since it is not present, it will create the respective String object in the String pool. The same applies to “str2” assigned with “Data Science”. Later when “str3” is assigned “Python” again, JVM checks for the “Python” object in the String pool, since it is already present, it returns the reference of the pooled instance, i.e. str1, without creating a new String object in the String pool.</blockquote><h4>The String class is able to maintain a String pool, basically because String in Java is immutable.</h4><p>Emphasize again!!!</p><h4>Immutability does not mean you cannot change the value of the reference variable but means you cannot change the object created!!!</h4><h4>Java String is Thread-safe</h4><p>Because <strong><em>String is immutable</em></strong>, it is <strong><em>thread safe</em></strong> too. Let’s say there is a method that takes the “name” variable as a parameter as shown below. The “name” variable points to the “John” object in the heap.</p><pre>public class Application {</pre><pre>   public static void main(String args[]){<br>       givePromotion(&quot;John&quot;);<br>   }</pre><pre>   public void givePromotion(String name){<br>       //promotion code<br>   }</pre><pre>}</pre><p>A Java program can create many threads (non-daemon) when running. Assume that two threads are accessing the same method concurrently. If Java String was not immutable, when one thread is executing the givePromotion() method, another thread could modify the value of the String object from “John” to “Jane”. The executing thread takes the “name” (pointing to the same String Object but with a different value) as “Jane” and a different employee may get the promotion. This is illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*QFm5Wkfz35dJ6WpxYtQkVA.png" /><figcaption>Illustration if String object is not immutable</figcaption></figure><blockquote>Because String objects are immutable, one thread cannot modify the object created, when the other is executing the respective method. Therefore, same String object can be accessed by multiple threads concurrently.</blockquote><p>Phew!!! A lot to understand right!!! Take it slow and you’ll grab it!!!</p><p>Happy Learning!!!</p><h4>References</h4><ol><li><a href="https://www.youtube.com/watch?v=jK1Ik8q0lyM&amp;list=PLD-mYtebG3X8tf1M8mRly3CO7tlTfeeLW">(57) Why is immutability matters ? — YouTube</a></li><li><a href="https://www.javatpoint.com/string-pool-in-java">String Pool in Java — Javatpoint</a></li><li><a href="https://www.journaldev.com/797/what-is-java-string-pool">What is Java String Pool? — JournalDev</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a90f97067bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java is Pass by Reference as Value]]></title>
            <link>https://medium.com/@lakkuga/java-is-pass-by-reference-as-value-85432c2833dc?source=rss-ed774cb971e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/85432c2833dc</guid>
            <category><![CDATA[pass-by-reference]]></category>
            <category><![CDATA[pass-by-value]]></category>
            <dc:creator><![CDATA[Lakshini Kuganandamurthy]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 06:21:42 GMT</pubDate>
            <atom:updated>2022-05-20T01:09:26.616Z</atom:updated>
            <content:encoded><![CDATA[<p>It is confusing right??? For me too, it was!!! So let’s try to understand this together!!!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f92406812979da0c581d3490c52c9e09/href">https://medium.com/media/f92406812979da0c581d3490c52c9e09/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/561437cf2a5826a5ad97fd6844c9691d/href">https://medium.com/media/561437cf2a5826a5ad97fd6844c9691d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1b1b7ffb60fc9bea31c7f539d4daff4/href">https://medium.com/media/f1b1b7ffb60fc9bea31c7f539d4daff4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGfjSZaK-Uh6LUR7P-vmWg.jpeg" /><figcaption>How objects and reference variables are located in Stack and Heap</figcaption></figure><blockquote>Have more content!!! 😅</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85432c2833dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Daemon and Non-daemon threads in]]></title>
            <link>https://medium.com/@lakkuga/daemon-and-non-daemon-threads-in-ddc091fabacd?source=rss-ed774cb971e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddc091fabacd</guid>
            <dc:creator><![CDATA[Lakshini Kuganandamurthy]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 05:32:07 GMT</pubDate>
            <atom:updated>2022-05-20T01:10:18.246Z</atom:updated>
            <content:encoded><![CDATA[<h3>Daemon and Non-Daemon threads in Java</h3><p>This was a very confusing topic for me!!! After some digging, I was able to understand the concept and would like to share it with you all!!!</p><p>Let’s go step by step!!! First, let’s see what each term means and then debate how JVM deals with it!!!</p><h4>What are Non-Daemon threads???</h4><p>Non-daemon threads are <strong><em>user threads</em></strong> designed to do specific, complex tasks. These are <strong><em>high priority threads</em></strong> that run in the <strong><em>foreground</em></strong>. They are often referred to as “normal threads” that we see and use in day to day coding. Also, <strong><em>any thread created from the Main thread is a non-daemon/user thread</em></strong>. Non daemon / user threads are <strong><em>created usually by the Java application.</em></strong></p><h4>What are Daemon Threads???</h4><p>These are <strong><em>low priority threads</em></strong> that run in the <strong><em>background</em></strong>, which provide services to user threads running in the same Java application. Daemon threads are <strong><em>mostly created by JVM</em></strong> to perform background tasks and they run automatically e.g. garbage collection(gc), finalizer etc…</p><p>If a <strong><em>programmer wants to create a daemon thread</em></strong>, they can do so by using the <strong><em>setDaemon(true) method</em></strong>. This method sets the <strong><em>“daemon”</em></strong> status of the thread to<strong><em> “true”</em></strong> making the thread daemon. This method can only be called <strong><em>after creating the thread</em></strong> and <strong><em>before starting (using start() method) that specific thread</em></strong>. If the setDaemon() method is called while the thread is running, it will <strong><em>throw an IllegalThreadStateException</em></strong>. Observe the code snippet below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffcdd9f436c13e33d2e14ded80f6718c/href">https://medium.com/media/ffcdd9f436c13e33d2e14ded80f6718c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2162139c1ddb203878921f96d5a4273b/href">https://medium.com/media/2162139c1ddb203878921f96d5a4273b/href</a></iframe><p>Another important point to note is that any new thread spawned or created from a daemon thread also becomes a daemon thread because threads inherit the daemon status from the parent threads.</p><h4>Differences between Daemon and Non-Daemon threads</h4><p>Ok, let’s understand how JVM deals with these threads!!!</p><p>When you run your Java application using ‘java &lt;Name of .class file without the .class extension&gt;” e.g. java HelloWorld, the “java” in the command tells the operating system to create a JVM instance. JVM when started, creates a non-daemon thread which is also known as the “Main” thread. This thread looks for the main() method (public static void main(String args[])) and invokes it. The main() method is the entry point to your Java application.</p><p>Any threads created in the main method is said to be the child threads of the main thread. Therefore, any newly created threads inherit the “daemon” status of their parent thread. That is the reason all the threads created in the main() method, are non daemon by default, because main thread is non daemon.</p><blockquote>Have more content!!! 😅</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddc091fabacd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Docker and Container based Development]]></title>
            <link>https://medium.com/@lakkuga/introduction-to-docker-and-container-based-development-9a3c85608a4c?source=rss-ed774cb971e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a3c85608a4c</guid>
            <dc:creator><![CDATA[Lakshini Kuganandamurthy]]></dc:creator>
            <pubDate>Fri, 25 Mar 2022 15:17:29 GMT</pubDate>
            <atom:updated>2022-04-18T03:04:47.240Z</atom:updated>
            <content:encoded><![CDATA[<p>Is it too many words??? Docker??? Container??? I understand, so let’s dive into the topic!!!</p><p>Docker, we have come across this word multiple times around the internet or people around us saying this!!! Many people know Docker, because of its popularity in the software market!!! We might not know the word “Container” but basically, <strong><em>Docker is a Container.</em></strong></p><p>Let’s get into some history!!!</p><blockquote>In the past, software applications were deployed in physical servers, e.g. if the requirement was to have an application server, a database server and a web server, these were all 3 separate hardware setups.</blockquote><blockquote>The <strong><em>problems</em></strong> of having 3 separate hardware, includes <strong><em>occupying alot of space, need resources to maintain them, need of separate networks and operating systems, on top of everything the cost of implementing such hardware</em></strong>. It further creates the problem of these <strong><em>hardware resources not being utilized to the maximum</em></strong>.</blockquote><blockquote>The app server or the web server might not use 100% of its processing power or memory. The database server might not use 100% of its hard drive space. So ultimately, <strong><em>using all these hardware becomes a waste!!!</em></strong></blockquote><blockquote>Later, the hypervisor was introduced. As shown below in the diagram, there is a single high processing hardware, <strong><em>in which a hypervisor is installed</em></strong>. Wait, what is a hypervisor???</blockquote><blockquote>Hypervisor is a program that creates, runs and manages <strong><em>multiple virtual machines</em></strong> in <strong><em>a host machine</em></strong>. So here, the host machine is the high processing hardware. Virtual machines will each act as an app server, web server and the database server according to the requirement mentioned above. Each Virtual machine may have a different operating system installed in it and different applications installed in each of them.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*9lynFIl65zqN6GlxU1qXag.png" /><figcaption>A representation of the virtual servers using hypervisor</figcaption></figure><blockquote>Each virtual machine may take, for e.g. 20% , 30% and 10% processing power, respectively from the host machine. In total, only 50% of the host’s processing power has been utilized, therefore many more VMs such as a mail server can be added later as per the requirement, to utilize complete potential of the host’s processor/memory/hard drive. This way, it eliminates the problem of “<strong><em>wastage of resources”, </em></strong>we discussed earlier!!!</blockquote><blockquote>But did it solve all our problems that we had earlier???</blockquote><blockquote>No, because, still the architecture has 3 different operating systems that incurs licensing costs, not for linux but OS like Red Hat Enterprises etc.. We need to continuously update the operating systems and patch vulnerabilities. This leads to too much of maintenance on the virtual servers.</blockquote><blockquote>The next problem is, if we need another web server, we need to install a VM and an OS again. This takes ample amount of time. You may deploy a VM image in the host machine and install an OS to it but still, it might take time to configure the VMs. For, e.g. same hostname cannot exist within the same network.</blockquote><blockquote>So, this implies that problems are not solved completely!!! But we are better off!!!</blockquote><p><strong><em>Containers are a solution to all these problems!!!</em></strong> It solved the problem of maintaining multiple operating systems, starting VMs may take some time, as it has to boot up and the need to incur maintenance costs. The diagram below shows the architecture of a <strong><em>Container based system.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*9jAHtcRzi1MrDcd2KHtX2g.png" /><figcaption>Container based system</figcaption></figure><p>Most of us know Containers as Docker Containers!!! Here’s how it was found!!! A cloud paltform called dotCloud came up with a separate project known as Docker. It was incorporated as Docker Inc. but later was sold to Apache. Docker is an open source project. It was developed using GO.</p><blockquote>One point, I would like to stress, is that a docker container and a hypervisor cannot be compared to each other. A hypervisor is designed to maintain multiple VMs, each of which will have an operating system installed, where as a Docker container is usually installed on an operating system to maintain multiple applications. Therefore, <strong><em>Size of Docker Container != Size of Hypervisor</em></strong></blockquote><p>In a Container based architecture, there is no need for multiple VMs or multiple Operating systems. Therefore, we have more storage to install many more docker containers. The second advantage is, since there are no multiple operating systems, no more multiple licensing costs or multiple patching for vulnerabilities. Also, since there is only one OS, which is installed on a host machine, the OS is already booted and applications can start instantly.</p><p>So I hope, you understood the upside of Container based applications!!!</p><p>Let’s talk about the Docker Engine!!!</p><h3>Docker Engine</h3><blockquote>Docker Engine is <strong>not</strong> the Docker Project!!!</blockquote><p>This is a small unit. It is a core, around which components such as <strong><em>orchestration, registry, security, services</em></strong> are built.</p><p>Let’s look at the 2 most important components; orchestration and registry!!!</p><h4>Registry</h4><p>This is a place where<strong><em> docker images</em></strong> can be stored. For e.g. we can <strong><em>pull an image of an application</em></strong> such as mongoDB or MySQL from <strong><em>Docker hub</em></strong> and <strong><em>download the image</em></strong>, <strong><em>using docker pull </em></strong>or from a<strong><em> registry using docker image pull</em></strong>. Do some customization and push it back to the registry.</p><blockquote>Note : A set of images means a repository.</blockquote><blockquote>Also, if you are running multiple hosts, and you need a customized image pack, then you can point the hosts to that particular registry and download the cutomized images.</blockquote><blockquote>We can create repositories and make it private or public. Private repos can only be accessed by you but anyone can pull or download images from a public repo. But only you or the people with commit grants can publish/commit images to the public or private repo.</blockquote><h4>Orchestration</h4><p>A software application can be broken down into various micro-level services / processes such as http run time engine for web services, logging, authentication processes (OAuth) and other services etc… <strong><em>We can create different containers (e.g. docker containers) for these micro-level services. </em></strong>So, http service will be in one container, OAuth service will be another container etc…</p><p>During deployment of the application, e.g. if we have 3 hosts, we do not need to define these containers should point to this host!!! But, orchestration takes care of it. When these containers are deployed, the orchestration process collects all these modules (micro-level services)/containers and defines the hosts to point (which host to go to), the required dependencies, which container should execute first, in the application flow etc…</p><h4>Kubernetes???</h4><p>This is <strong><em>one of the tools used for the orchestration process</em></strong>. It is a software project initiated by Google and now it is open source. There are multiple different containers (container based applications) and docker containers are one of them, so there are different methodologies how orchestration is carried out in each of these container based applications.</p><h4>Myths Developers have about Containers</h4><ol><li>Docker is not persistent — That is, they think docker when shut down, every configuration and data are lost. This is not true!!! Dockers by nature are persistent, all the data and configurations are saved on shut down.</li><li>Docker can only be used for applications you are starting to build but not for legacy applications/ software applications already built. This may be partially true but not always. During the transition from physical servers to VMs installed on a hypervisor, legacy applications were installed into the VMs as .exe file (in Windows OS) or debian files (for Ubuntu or linux OS), but we cannot directly install these legacy applications in docker containers. Docker containers are not meant for this. Container based applications are mainly used in micro-service architecture. For e.g. for a small application, we create an independent docker container and run it. The http component (http transport)is created in a separate container and application runs. There is a high volume load to http or it is choking, it can’t serve further, so you can spin out a new container from the http module and redirect the application’s web traffic to it. Therefore, to get full fledged features of docker containers, the application should fit into the micro-service architecture. So, the belief that legacy applications are not supported by docker, does not mean it does not support but because they are not built based on the micro-service architecture. It is better if the application is redeveloped or redesigned or modified if the application is to be migrated to docker containers. It does not mean the legacy applications cannot be migrated into docker containers but we cannot use all the features that docker offers, because applications built to be used in a VM or physical servers are usually bundled together, e.g. http module, logging, service etc…</li></ol><p>Phew!!!! Finally, let’s talk about OCI!!!</p><h4>OCI (Open Container Initiative)</h4><p>This initiative was taken by Docker and other leading companies in the Container industry to define specifications for creating containers. They govern the container development. If an application was developed properly using containers, all containers usually comply with the OCI standards.</p><p>The docker engine is decoupled and they moved all vendor specific or platform specific code to the docker engine. The ultimate purpose of container based development or applications is the application should be platform independent and not vendor specific.</p><p>Too much??? Let me tell you the beauty of this type of development. When you want to modify the application’s code or introduce a new feature, you can rewrite and test. If all tests pass, the application will be pushed to docker registry. From the docker registry, it can be automatically pulled into production. This is known as continued integration!!!</p><p>Hope you all got a better understanding on Containers!!!</p><p>Happy Learning!!!</p><h3>References</h3><ol><li><a href="https://www.youtube.com/watch?v=cUiU8yDdQmw&amp;list=PLD-mYtebG3X9HaZ1T39-aF4ghEtWy9-v3&amp;index=1">Introduction to Docker and Container based development — YouTube</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a3c85608a4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Date Time APIs]]></title>
            <link>https://medium.com/@lakkuga/java-date-time-apis-847530ed74e0?source=rss-ed774cb971e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/847530ed74e0</guid>
            <dc:creator><![CDATA[Lakshini Kuganandamurthy]]></dc:creator>
            <pubDate>Wed, 23 Mar 2022 14:21:22 GMT</pubDate>
            <atom:updated>2022-05-16T17:58:19.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*Gmj5gICH5EjvRIskaiix3Q.jpeg" /></figure><p><em>What is this buzz about the Java 8 Date Time API? This seems to be an important topic in the Java world!!! So let’s dig in and get some idea!!!</em></p><h4>Why is it Java 8 Date Time API, what about the older version???</h4><p>Upto Java 7 version, there were certain drawbacks.</p><ol><li>When declaring the <strong><em>Date object</em></strong>, we need to import the package that has the implementation of the <strong><em>Date class. </em></strong>It is very confusing which package to import. The Java 7 version has many date packages such as java.util, java.sql etc. Therefore, it creates an ambiguity in the package selection when importing.</li><li>When Date object is printed (as shown above), the output gives the current date with the time and time zone. We should do some modifications if we want to display only date or time.</li><li>Similarly if we need the date in a specific format, you would have to use a class from a different package. E.g. <em>SimpleDateFormat</em> <em>class</em> from the <em>java.text.SimpleDateFormat package.</em></li><li>Existing classes such as the <em>Date (from java.util.Date package)</em> and <em>Calendar (from java.util.Calendar package)</em> are <strong>not thread-safe. </strong>Therefore, developers have to deal with concurrency issues in a multi-thread environment, when using these classes.</li><li>Has a <strong>poor Design</strong>. Default Date starts from 1900, month starts from 1 and day starts from 0, so no uniformity. Further, the Date and Calendar classes provide less direct methods for date operations.</li><li><strong>Difficulty in handling time zones</strong> using Date and Calendar classes. Developers have to write extra code to deal with various time zones.</li></ol><p><strong>The following are classes from the older version of Date Time API</strong></p><ul><li>java.util.Date class</li><li>java.sql.Date class</li><li>java.util.Calendar class</li><li>java.util.GregorianCalendar class</li><li>java.util.TimeZone class</li><li>java.sql.Time class</li><li>java.sql.Timestamp class</li></ul><p><strong>Classes used to format date and time in Java</strong></p><ul><li>java.text.DateFormat class</li><li>java.text.SimpleDateFormat class</li></ul><p>Let’s discuss some of the most common classes!!!</p><h3><strong>java.util.Date</strong></h3><p>This class represents date and time in java. It consists of constructors and methods to deal with date and time. It<strong> <em>implements</em> Serializable, Cloneable and Comparable&lt;Date&gt; interfaces</strong>. It is <strong><em>inherited</em></strong> by <strong>java.sql.Date, java.sql.Time and java.sql.Timestamp classes.</strong></p><p>Note : The following are the undeprecated Constructors and Methods of the java.util.Date class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EunrbTQxHLhT4I_4S0cdTQ.png" /><figcaption><strong>java.util.Date Constructors</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQvdCO7gHtD6lw_z4Gslzg.png" /><figcaption><strong>java.util.Date Methods</strong></figcaption></figure><p>Code snippets for util.Date</p><h3>java.util.Calendar</h3><p>The Calendar class is an abstract class that has methods to convert date</p><h3>java.sql.Date</h3><p>This class represents <strong>only Date</strong>, in java. It <strong><em>extends</em> the java.util.Date</strong> class. The sql.Date object is widely used in JDBC (Java Database Connectivity) because it represents the date that can be stored in a database.</p><p>Note: Some constructors and methods of the java.sql.Date class has been deprecated. The following are the undeprecated Constructors and Methods of the java.sql.Date class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ETaLckRKlUP34EYXPJzoQ.png" /><figcaption><strong>java.sql.Date Constructor</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97aR9HLIItIR_bqCtvU0eQ.png" /><figcaption><strong>java.sql.Date Methods</strong></figcaption></figure><p>The below e.g. shows printing the a) number of milliseconds from 01 January 1970, 00:00:00 GMT to present time (I mean the time I executed this code!!!) b) current date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Av8ByttMZnadnbctwEDHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*-xg35j4E3otEFSSQ2Li-pw.png" /><figcaption>Output when printing the current date</figcaption></figure><p>setTime() method of the java.util.Date class takes 1,000,000 milliseconds as a parameter, which means the time is set to 1,000,000 milliseconds after 01 January 1970, 00:00:00 GMT. Then the date corresponding to that time is printed.</p><p>Did you find something odd here? The java.util.Date class is used as the import and the Date printed has the date, time and time zone. It is because setTime() is a method of the java.util.Date class and that java.sql.Date class extends java.util.Date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtplPgXi8GgQ9juIBUciXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*lyxTFI5NzIpVgIGFmmYKRg.png" /><figcaption>Output of date</figcaption></figure><h3>Java 8 Date &amp; Time API</h3><p>Java 8 introduced many <strong><em>classes and interfaces in this API, to handle Date and Time more effectively with respect to convenience and performance</em></strong>. This is also known as Joda Time API, because, this API was developed by joda.org.</p><p>Observe the code snippets below to get an understanding of the classes and interfaces present in the Java Date Time API.</p><p><strong><em>LocalDate and LocalTime classes</em></strong> are present in the <strong><em>java.time package and print the current system date and time </em>as follows.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7a7dd372a325e7c5001873fcf41fb55/href">https://medium.com/media/f7a7dd372a325e7c5001873fcf41fb55/href</a></iframe><p>We can derive the day, month, and year from the current system date or derive the hour, min, second, or nanoseconds from the current system time as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/296c71a38833ed72b477620e65dc6fda/href">https://medium.com/media/296c71a38833ed72b477620e65dc6fda/href</a></iframe><h3>References</h3><ol><li><a href="https://www.youtube.com/watch?v=5Dgz-CWXe_0">Java 1.8 Version New Features|| Session — 36|| Date and Time API Introduction Part-1 by Durga Sir — YouTube</a></li><li><a href="https://www.youtube.com/watch?v=0WHFBSGY4Bk">Java 1.8 Version New Features|| Session — 37||Date and Time API Introduction Part-2 by Durga Sir — YouTube</a></li><li><a href="https://www.youtube.com/watch?v=lQr-gImaTTk">Java 1.8 Version New Features|| Session — 38|| Date and Time API Introduction Part-3 by Durga Sir — YouTube</a></li><li><a href="https://www.youtube.com/watch?v=B6YJMYchAH4">Java 1.8 New Features|| Session — 39 || Date and Time API Introduction Period &amp; Year — YouTube</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=847530ed74e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classes and Objects in Java]]></title>
            <link>https://medium.com/@lakkuga/classes-and-objects-in-java-c02601cce2fe?source=rss-ed774cb971e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c02601cce2fe</guid>
            <dc:creator><![CDATA[Lakshini Kuganandamurthy]]></dc:creator>
            <pubDate>Tue, 22 Mar 2022 14:13:03 GMT</pubDate>
            <atom:updated>2022-03-25T12:13:45.681Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a summary of Chapter 02 of the Head First Java 2nd edition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/0*UEpiK4fBRpvxmWt7.jpg" /><figcaption>Head First Java 2nd edition</figcaption></figure><h4>Everyone says Java is an Object Oriented language. So what benefits does that give???</h4><ul><li>It allows not messing around with code that was already tested, when adding a new feature to a Java application.</li><li>Data and methods that operate on that data are together in one class.</li><li>Reuse of the code in other Java applications.</li></ul><p>It brings far more advantages than the ones mentioned above, but, first let’s dive into some OO concepts!!!</p><p>In Java, everything goes in a class!</p><h4>So, what is a class in Java???</h4><p><strong><em>Class</em></strong> is a <strong><em>blueprint for an object</em></strong>. It tells the JVM, <strong><em>how</em></strong> to make an <strong><em>object of that particular type</em></strong> (<em>type is the class here</em>). For e.g. think of an architect who follows a design plan for a house. Here the <strong><em>architect is the JVM</em></strong> and the <strong><em>design, is the class </em></strong>he follows to create an <strong><em>object of type “House”.</em></strong></p><p>A class will have <strong><em>instance variables</em></strong> and <strong><em>methods</em></strong>. Below diagram represents a <strong>class</strong> in Java. Simply, a <strong><em>class is not an object </em></strong>but it is used to <strong><em>construct them</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*mA8YY2BmB5_i82v3iyW2Fw.png" /><figcaption>Class Diagram representation for a Button Class</figcaption></figure><h4>Many objects can be created from a class. Wait, so what is an object???</h4><p><strong><em>Object is an instance</em></strong> of a <strong><em>class</em></strong>. For e.g. An architect can build <strong><em>many houses</em></strong> using <strong><em>one design plan</em></strong>! Each object of the class can have its own, unique values for the instance variables of that class.</p><p>When identifying the instance variables and the methods for a class, make sure to remember this trick!!!</p><ul><li>Things an object knows about itself are called <strong><em>instance variables</em></strong>.</li></ul><p>Instance variables represent an object’s state, i.e. the data</p><ul><li>Things an object can do are called <strong><em>methods</em></strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*3uO-UYpZgOO3eCmPccVOfw.png" /><figcaption>Representation of what an object knows and can do</figcaption></figure><p>Ok, now we know that what are classes and objects but how do you really make an object from a class??? how do we use that object???</p><h4>Making the first Object</h4><p>There are 2 classes we will have to create, one class, for the <strong><em>type of object you want to use</em></strong> (e.g. Television) and another class to <strong><em>test the new class, the tester class. </em></strong>This is where we will put the main() method.</p><p>In the main() method, we will create and access objects of the new class type. To access the methods and variables of the created object, we will use a dot operator(.)</p><p>For e.g. the new class type is the Dog class, <strong><em>this is the type of object you want to use, </em></strong>which has instance variables and methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0f7147f2757be8584076bd5f4629ab2/href">https://medium.com/media/d0f7147f2757be8584076bd5f4629ab2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c71fe65db9a0a8248ca7bac23e7e435/href">https://medium.com/media/5c71fe65db9a0a8248ca7bac23e7e435/href</a></iframe><p>This is the tester class with the main() method. A Dog object is created and its methods and instance variables are invoked using the dot operator(.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c71fe65db9a0a8248ca7bac23e7e435/href">https://medium.com/media/5c71fe65db9a0a8248ca7bac23e7e435/href</a></iframe><p>The following code snippets explain that multiple objects can be created from one class and each object can have unique values for the instance variables of that class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdf8922e94015dde37b0f8359db85feb/href">https://medium.com/media/cdf8922e94015dde37b0f8359db85feb/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0e375ca6dfe69504e46bc7dab5b249b/href">https://medium.com/media/c0e375ca6dfe69504e46bc7dab5b249b/href</a></iframe><p>The main() method in the Tester class looks so much stacked up!!!</p><p>By the way, we have still not looked at a “fully Object oriented Java application”!!! Because, we are still asking the main() method to create and test all the objects. But in a <strong><em>true OO application, objects talk to other objects</em></strong>.</p><p>So let’s now look at a <strong><em>Guessing game </em></strong>application, where real OO is applied!!!</p><p>This application has 3 classes, a Player class, a GuessGame class and a GameLauncher class, this class holds the main() method. Here, only the GuessGame object is created and the startGame() method is invoked. <strong><em>Main class looks clean and clear!!!</em></strong></p><p>As we can see, there is a random number generated that the players have to guess. The Player objects are called in the GuessGame class and checked if any players guessed the number right. The main logic of the application goes in this class.</p><p>In the Player class, there is a guess() method which generates a random number for each player’s guess and displays that number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbb7eed7d12a5fa018be168c7b173c6a/href">https://medium.com/media/fbb7eed7d12a5fa018be168c7b173c6a/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c38d91491c4653c1b61ffe6c842980be/href">https://medium.com/media/c38d91491c4653c1b61ffe6c842980be/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26d05aaacbeaf5473e78415fefd66052/href">https://medium.com/media/26d05aaacbeaf5473e78415fefd66052/href</a></iframe><h4>Ok, let’s learn some interesting facts about Java!!!</h4><h4>Global variables and methods</h4><p>This is when we want a method or a variable to be available to all the classes in the application. But, there is no such a concept, known as <strong><em>“global”</em></strong> in Java OO Programs. By making a method <strong><em>“public” and “static”</em></strong>, it makes the <strong><em>method behave “global”</em></strong>, i.e. any code from any part of the application can access this method. If a variable is made <strong><em>“public”, “static” and “final”</em></strong>, the <strong><em>variable is a globally available constant</em></strong>. These are special cases in Java.</p><h4>Garbage collection in Java</h4><p>Each time an object is created in Java, it is stored in the Heap area of the memory. <strong><em>All the objects live in the heap irrespective of when, where and how it was created!!! </em></strong>The Java Heap is also called the Garbage-Collectible Heap.</p><p>When we create an object, Java allocates memory on the heap, according to how much that object needs. For e.g. an object with 15 instance variables may need more memory allocation than an object with only 2 instance variables.</p><p>But does this object holds this memory space forever??? Not at all!!!</p><p>Then how to get this object out of the heap when it is no longer used??? Java manages that memory. When JVM sees that an object can be never used again, that object becomes eligible for garbage collection, i.e. the object will be destroyed, releasing the memory it was holding.</p><p>Garbage collection is also needed <strong><em>when the heap is running low on memory</em></strong>, during this time, the Garbage collector will run, throwing out the unreachable objects thus freeing up memory. This free memory space can be reused.</p><h4>The .jar file</h4><p>There may be hundreds and thousands of classes in an application. When a Java application is delivered to the end user, it is impractical to deliver this huge bunch of individual files. Therefore, we can bundle the whole application into a <strong><em>.jar file</em></strong> (also known as Java archive).</p><p>The .jar file is based on the pkzip format. This .jar file includes a <strong><em>manifest</em></strong> that defines <strong><em>which class has the main() method</em></strong> that should be run in order to run the Java application.</p><p>There are much more interesting facts, which we will explore in future articles. Till then, train your brain with these facts!!!</p><h4>Train the Brain</h4><ul><li>Object Oriented programming allows to extend a program without having to touch previously tested, working code.</li><li>All the Java code is defined in a class.</li><li>An object <strong><em>knows</em></strong> things and <strong><em>does</em></strong> things.</li><li>Things an object knows about itself are called instance variables. They represent the state of an object.</li><li>Things an object does are called methods, they represent the behaviour of an object.</li><li>A class can inherit instance variables and methods from a more abstract superclass.</li><li>At runtime, a Java program is nothing more than objects <strong><em>talking</em></strong> to other objects.</li><li><strong><em>An object can take care of itself, you don’t have to know or care how the object does it!!!</em></strong></li></ul><p>Ok, phew!!! Alot is it??? We are reaching the end of this article!!! Hope you gained some OO knowledge!!!</p><p>Happy Learning!!!</p><h4>References</h4><ol><li>Head First Java 2nd Edition by Kathy Sierra &amp; Bert Bates.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c02601cce2fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>