<?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 Sachintha Punchihewa on Medium]]></title>
        <description><![CDATA[Stories by Sachintha Punchihewa on Medium]]></description>
        <link>https://medium.com/@snishajith?source=rss-48a72e47d70c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F8DaypReCz2u0OSuVnP8vQ.jpeg</url>
            <title>Stories by Sachintha Punchihewa on Medium</title>
            <link>https://medium.com/@snishajith?source=rss-48a72e47d70c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 21:10:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@snishajith/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[Generics In java]]></title>
            <link>https://medium.com/@snishajith/generics-in-java-aef53d0423e8?source=rss-48a72e47d70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/aef53d0423e8</guid>
            <dc:creator><![CDATA[Sachintha Punchihewa]]></dc:creator>
            <pubDate>Thu, 16 Dec 2021 03:42:44 GMT</pubDate>
            <atom:updated>2021-12-16T03:42:44.923Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wNGxHlTCsH9zU90WDouoDQ.gif" /></figure><h4>What is Generics Type</h4><p>A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept.</p><p>This is a non-generic Box class that operates on objects of any type. It needs only to provide two methods set, which adds an object to the box, and get, which retrieves it.</p><pre>public class Box {<br>    private Object object;<br><br>    public void set(Object object) { this.object = object; }<br>    public Object get() { return object; }<br>}</pre><h4>Generic version of Box class</h4><p>A generic class is defined with the following format,</p><pre>class name&lt;T1, T2, ..., Tn&gt; { <br>    / * ... * /<br> }</pre><p>The type parameter section, mark by angel brackets (&lt;&gt;), follows the class name. It specifies the type parameters ( also called type variables) T1, T2,…, and Tn.</p><p>To update the Box class to use generics, you create a generic type declaration by changing the code “public class Box” to “public class Box&lt;T&gt;”. This introduces the type variable, T, that can be used anywhere inside the class.</p><pre>public class Box&lt;T&gt; {<br>    private T t;<br><br>    public void set(T t) { this.t = T; }<br>    public t get() { return T; }<br>}</pre><p>As you can see, all the Objects are replaced by T. A type variable can be any non-primitive type you specify, any class type, any interface type, any array type, or even another type variable.</p><h4>Note: The same technique can be applied to create generic interfaces.</h4><h3>Type Parameter Naming Conventions</h3><ul><li>E — Element (used extensively by the Java Collections Framework)</li><li>K — Key</li><li>N — Number</li><li>T — Type</li><li>V — Value</li><li>S,U,V etc. — 2nd, 3rd, 4th types</li></ul><h3>Invoking and Instantiating a Generic Type</h3><p>To reference the generic Box class from within your code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer,</p><pre>Box&lt;Integer&gt; integerBox;</pre><p>You can think of a generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you are passing a type argument. You pass the Integer type argument to the Box class.</p><p><strong>Note: type Parameter and Type Argument are different.</strong></p><ul><li>Box&lt;T&gt; is a type parameter</li><li>Box&lt;String&gt; box is type argument.</li></ul><h3>Multiple Type Parameters</h3><p>A generic class can have multiple type parameters. For example, the generic OrderedPair class, which implements the generic Pair interface,</p><pre>interface <strong>Pair</strong>&lt;K, V&gt; {<br>    public K getKey();<br>    public V getValue();<br>}</pre><pre>class <strong>OrderedPair</strong>&lt;K, V&gt; implements Pair{<br><br>    private K key;<br>    private V value;<br><br>    public OrderedPair(K key, V value) {<br>        this.key = key;<br>        this.value = value;<br>    }<br><br>    @Override<br>    public Object getKey() {<br>        return null;<br>    }<br><br>    @Override<br>    public Object getValue() {<br>        return null;<br>    }<br>}<br><br><br>public class Box{<br>    public static void main(String[] args) {<br>        Pair&lt;String, Integer&gt; p1 = new OrderedPair&lt;String, Integer&gt;(&quot;Even&quot;, 8);<br>        Pair&lt;String, String&gt;  p2 = new OrderedPair&lt;String, String&gt;(&quot;hello&quot;, &quot;world&quot;);<br>    }<br>}</pre><h3>What are Raw types in generics?</h3><p>A raw type is the name of the generic class or interfaces without any type arguments.</p><h3>What are Bounded type parameters?</h3><p>There can be times when we want to restrict the type that we pass to the parameterized type as type arguments. When that time we have to restrict for getting only Numbers instance or its subclasses. This is why bounded type parameters are there.</p><p>To declare a bounded type parameter list the type parameters’ name, followed by the extend keyword.</p><pre>public class Box&lt;T&gt; {<br><br>    private T t;          <br><br>    public void set(T t) {<br>        this.t = t;<br>    }<br><br>    public T get() {<br>        return t;<br>    }<br><br>    public &lt;U <strong>extends Number</strong>&gt; void inspect(U u){<br>        System.out.println(&quot;T: &quot; + t.getClass().getName());<br>        System.out.println(&quot;U: &quot; + u.getClass().getName());<br>    }<br><br>    public static void main(String[] args) {<br>        Box&lt;Integer&gt; integerBox = new Box&lt;Integer&gt;();<br>        integerBox.set(new Integer(10));<br>        integerBox.inspect(&quot;some text&quot;); // <strong>error: this is still String!</strong><br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aef53d0423e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Methods Common to All Objects]]></title>
            <link>https://medium.com/@snishajith/methods-common-to-all-objects-644f39367009?source=rss-48a72e47d70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/644f39367009</guid>
            <dc:creator><![CDATA[Sachintha Punchihewa]]></dc:creator>
            <pubDate>Thu, 16 Dec 2021 03:41:37 GMT</pubDate>
            <atom:updated>2021-12-16T03:41:37.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*3n9mvT1FZBn2l-tLMzV6sg.png" /></figure><p>Although an object is a concrete class, it is designed primarily for an extension. All of its nonfinal methods like equals, hashCode, toString, clone and finalize have explicit general contracts because they are designed to be overridden. It is the responsibility of any class overriding these methods to obey their general contracts.</p><h4>Obey the general contract when overriding equals</h4><p>Each instance of the class is inherently unique. This is true for classes such as Thread that represent active entities rather than values. The equals implementation provided by the object has exactly the right behavior for these classes.</p><ul><li>Each instance of the class is inherently unique. This is true for classes such as Thread that represent active entities rather than values. The equals implementation provided by Object has exactly the right behavior for these classes.</li><li>A superclass has already overridden equals, and the superclass behavior is appropriate for this class. For example, most Set implementations inherit their equals implementations from AbstractSet, List implementation from AbstractList, and Map implementations from AbstractMap.</li></ul><p>So when do we want to override equals? It is when a class has a notion of logical equality that differs from mere object identity and a superclass has not already overridden equals. This is usually the case for value classes. A value<br>class is simply a class that represents a value, like an integer or a string. A<br>A programmer who compares references to value objects using the equals method expects to find out if they are logically equivalent, not if they relate to<br>the same object. Not only is it necessary to override the equals method in order to Programming expectations allow instances to serve as a card key or set Items with predictable, desirable behavior.</p><p>Here are a few final caveats:</p><p>Always override hashCode when you override equals.</p><p>Don’t try to be too clever. If you simply test fields for equality, it’s not hard to adhere to the equals contract. If you are overly aggressive a bad idea to take any form of aliasing into account. For example, the file class shouldn’t attempt to equate symbolic links referring to the same file.</p><p>Don’t substitute another type for Object in the equals declaration. It is not uncommon for a programmer to write an equals method that looks like this and then spends hours puzzling over why it doesn’t work properly.</p><pre>// Broken - parameter type must be Object!<br>    public boolean equals(MyClass o) {<br>...</pre><p>The problem is that this method does not override Object. equals, whose argument is of type Object, but overloads it instead. It is unacceptable to provide such a “Strongly typed” equals method even in addition to the normal one because it can cause Override annotations in subclasses to generate false positives and provide a false sense of security.</p><p>Consistent use of the Override annotation, as illustrated throughout this item, will prevent you from making this mistake. This equals method won’t compile, and the error message will tell you exactly what is wrong.</p><pre>// Still broken, but won’t compile<br>    @Override <br>    public boolean equals(MyClass o) {<br>      ...<br>    }</pre><h3>Always override hashCode when you override equals</h3><p>You must override hashCode in every class that overrides equals. If you fail to do so, your class will violate the general contract for hashCode, which will prevent it from functioning properly in collections such as HashMap and HashSet. Here is the contract, adapted from the Object specification.</p><ul><li>When the hashCode method is invoked on an object repeatedly during the execution of an application, it must consistently return the same value, provided no information used in equal comparisons is modified. This value need not remain consistent from one execution of an application to another.</li><li>If two objects are equal according to the equals(Object) method, then calling hashCode on the two objects must produce the same integer result.</li></ul><p>The key provision that is violated when you fail to override hashCode is the second one: equal objects must have equal hash codes. Two distinct instances may be logically equal according to a class’s equals method, but to Object’s hashCode method, they are just two objects with nothing much in common. Therefore, Object’s hashCode method returns two seemingly random numbers instead of two equal numbers as required by the contract.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=644f39367009" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency Programming]]></title>
            <link>https://medium.com/@snishajith/concurrency-programming-e1bd9dca8ff0?source=rss-48a72e47d70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1bd9dca8ff0</guid>
            <dc:creator><![CDATA[Sachintha Punchihewa]]></dc:creator>
            <pubDate>Wed, 17 Nov 2021 13:02:33 GMT</pubDate>
            <atom:updated>2021-11-17T13:02:33.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1L0miQJarJhfyh-hYFimSQ.png" /></figure><h3>Multitasking and parallel programming</h3><p><strong>Multitasking</strong> is the concurrent execution of multiple tasks. (also known as a process) <strong>over a certain period of time</strong>. ( Not same time )</p><p>But today it can be done several tasks at the same time because these days computers have more than one processor. It is called parallel <strong>programming</strong>. Because it can be done several tasks at the same time. ( more than one execution unit) duel core, also parallel programming can be put inside <strong>multitasking</strong>.</p><p>Multitasking can be seen in single processors as well as multiple processors.</p><h3>Multi-core (dual-core)</h3><ul><li>A single processor with two or more independent processing units.</li></ul><h3>Concurrent Execution</h3><p>It can be done sometime or for a certain period of time. ( out of order or partially) finally, the output will be the same.</p><p>Can be there in parral programming and multitasking.</p><h3>What is process-based multitasking and thread base multitasking</h3><h4>What is a process</h4><p>Self-contained execution environment. Mean by “private set of basic runtime resource. A memory will be allocated for a process to run a program (an app ) privately that cannot involve other processes. ( A process simply mean an app ) run multi-application at once called process-based multitasking.</p><h4>What is thread</h4><p>A process can have at least one thread. It is needed to run a process (app). To execute the app’s code. This is a <strong>lightweight process. </strong>Thread also has its own space relative to a process. ( multiple threads can have multi-tasks ( several tasks ) it is called thread-based multitasking)</p><h4>process-based multitasking</h4><p>When playing games we can listen to a song. While we can do many things.</p><h4>Thread based multitasking</h4><p>Inside a program, there can be many threads that do several tasks for a certain period of time.</p><h3>There are two ways to create threads in Java</h3><ol><li><strong>Implementing Runnable</strong></li><li><strong>Extending Thread</strong></li></ol><p>below is the example with Thread class and Runnable interface</p><pre>public class HelloThreadDemo {<br>    public static void main(String[] args) {<br>        Thread myThread1 = new Thread(new RunnableInterface());<br>        myThread1.start();<br>        System.<em>out</em>.println(Thread.<em>currentThread</em>()+&quot;This is still from the main thread&quot;);<br><br>        ThreadClass myThread2 = new ThreadClass();<br>        myThread2.start();<br>    }<br>}<br><br>class RunnableInterface implements Runnable{<br><br>    @Override<br>    public void run() {<br>        System.<em>out</em>.println(&quot;I am being executed by MyThread :&quot;+ Thread.<em>currentThread</em>());<br>    }<br>}<br><br>class ThreadClass extends Thread{<br>    @Override<br>    public void run() {<br>        System.<em>out</em>.println(&quot;I am being executed by MyThread2 :&quot;+ Thread.<em>currentThread</em>());<br>    }<br>}</pre><ul><li>Usually, when we create local variables inside a method they will be stored in the stack memory because every thread has been allocated for a new stack separately. that’s the reason why we cannot communicate between that local variable inside another method.</li></ul><h3>Thread class Constructors</h3><ol><li><strong>Thread</strong>()</li><li><strong>Thread</strong>(String str)</li><li><strong>Thread</strong>(Runnable r)</li><li><strong>Thread</strong>(Runnable r, String str)</li><li><strong>Thread</strong>(<strong>ThreadGroup</strong> group, <strong>Runnable</strong> target)</li><li><strong>Thread</strong>(<strong>ThreadGroup</strong> group, <strong>Runnable</strong> target, String name)</li><li><strong>Thread</strong>(<strong>ThreadGroup</strong> group, <strong>Runnable</strong> target, String name, long stackSize)</li><li><strong>Thread</strong>(<strong>ThreadGroup</strong> group, <strong>String</strong> name)</li></ol><h3>Methods</h3><p><strong>run()</strong></p><p>the run method is an abstract method that is in the Runnable functional interface. That Runnable functional interface has been implemented in the Thread class. So when we create a class using the Thread class we have to override the <strong>run() </strong>method which has come from the Runnable interface. and inside that run() method we can define the code that we want to execute.</p><p>The same we can apply implementing the runnable interface to a particular class. in that also we have to implement the <strong>run() </strong>method to the class.</p><p>Finally, when we run the Thread class or the class which implemented the Runnable interface we have to make an object and have to call the start method. <strong>NOT: </strong>We do not execute the run() method when we want to execute the thread class or runnable interface because if we execute the <strong>run() </strong>method there will not be created a new thread rather than our main thread. so keep in mind we have to call the start method otherwise it will behave like a normal object.</p><p><strong>start()</strong></p><p>start the thread calling run() method</p><p><strong>join()</strong></p><p>wait for a thread to join</p><p><strong>yield()</strong></p><p>A hint to the scheduler that the current thread is willing to yield its current use of a processor.</p><p><strong>getPriority()</strong></p><p>return the thread priority</p><p>isAlive()</p><p>check whether the thread is still running or not</p><p><strong>sleep()</strong></p><p>Thread.sleep() method can be used to pause the execution of the current thread for a specified time in milliseconds.</p><pre>public class SleepThreadDemo {<br>    public static void main(String[] args) {<br><br>        new Thread(()-&gt;{<br>            for (int i = 0; i &lt; 1000; i++) {<br>                System.<em>out</em>.println(Thread.<em>currentThread</em>().getName() + &quot; &quot;+ i);<br>            }<br>        },&quot;my Thread&quot;).start();<br><br>        try{<br>            Thread.<em>sleep</em>(2000);<br>        }catch (InterruptedException e) {<br>            e.printStackTrace();<br>        }<br><br>        for (int j = 0; j &lt; 1000; j++) {<br>            System.<em>out</em>.println(Thread.<em>currentThread</em>().getName() + &quot; &quot; + j);<br>        }<br>    }<br>}</pre><p>If we want us to execute the myThread first without executing the main thread we are able to add Thread.sleep() method with some specific time period.</p><p>There is another overloaded method sleep(long millis, int nanos) that can be used to pause the execution of current thread for specified milliseconds and nanoseconds. The allowed nanosecond value is between 0 and 999999.</p><h3>Thread priority</h3><p>Thread priority in Java is <strong>a number assigned to a thread that is used by the Thread scheduler to decide which thread should be allowed to give more time period. Note: it is not telling which thread should run first.</strong></p><p>All Java threads have a priority in the range <strong>1–10</strong>. priority ie. priority by default is 5.</p><h3>Thread lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*Zq-sazCmqqvrU5HIpxgbzA.png" /></figure><h3>Synchronize keyword in java Thread</h3><p>The synchronization is mainly used to</p><ol><li>To prevent thread interference.</li><li>To prevent consistency problems.</li></ol><h4>types of synchronization</h4><ol><li>Synchronized method.</li><li>Synchronized block.</li><li>Static synchronization.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1bd9dca8ff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streams API]]></title>
            <link>https://medium.com/@snishajith/streams-api-17a07ea509dd?source=rss-48a72e47d70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/17a07ea509dd</guid>
            <dc:creator><![CDATA[Sachintha Punchihewa]]></dc:creator>
            <pubDate>Mon, 15 Nov 2021 13:16:49 GMT</pubDate>
            <atom:updated>2021-11-15T13:16:49.185Z</atom:updated>
            <content:encoded><![CDATA[<h4>Collections + Lambda + Stream API</h4><ul><li><strong>To store a group of objects as a single entity we go for a collection.</strong></li><li><strong>To process objects of collections, we go for a stream.</strong></li></ul><p>Stream API provides some methods that we can process the data in the Collection.</p><h3>How does Stream process the data</h3><ul><li>Streams provide two mechanisms to process data.</li></ul><ol><li>Filter</li><li>Map</li></ol><p>Two methods introduced by Stream API are called filter() and map() to manipulate Collection data.</p><h3>Difference between filter() and map()</h3><ul><li><strong>Filter method</strong></li></ul><p>Java stream provides a method <strong>filter()</strong> to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*DaBE8-iJ_RVudbiTD0UvwA.png" /></figure><pre>public class Methods {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = Arrays.<em>asList</em>(1,2,3,4,5,6,7,8,9,10);<br><br>        numbers.stream().filter(n -&gt; n % 2 == 0).forEach(System.<em>out</em>::println);<br>  }<br>}</pre><ul><li><strong>map method</strong></li></ul><p>The <strong>map()</strong> function is a method in the Stream class that represents a functional programming concept. In simple words, the map() is used to transform one object into other by applying a function. That’s why the Stream. map(Function mapper) takes a function as an argument.</p><p>An operation is done to the every element and add to another collection or we can use for another purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*lcPOasa-W8MEaQUQv554Mg.png" /></figure><p><strong>Example,</strong></p><pre>public class Methods {<br>    public static void main(String[] args) {<br>        List&lt;Integer&gt; numbers = Arrays.<em>asList</em>(10,20,30,40,50);<br><br>        numbers.stream().map(i -&gt; i + 5).forEach(System.<em>out</em>::println);<br><br><br>    }<br>}</pre><ul><li>In map whatever data have in the source and apply update/modify finally store those into the target.</li><li>In the filter, data will be reduced.</li></ul><h3>How Stream API works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwQC0NYN4za71wKM18Q3Yw.png" /></figure><ul><li>filter() and map() mainly deals with Lambda Expression. Lambda is very important when working with Stream API.</li><li>Collection is to present gourp of data/objects as single entity.</li></ul><pre>List&lt;Integer&gt; arrayList = Arrays.<em>asList</em>(10,20,30,40,50);<br>arrayList.stream().filter(num -&gt; num%2 == 0).collect(Collectors.<em>toList</em>());</pre><p>The above peace of code returns a list.</p><p>Using forEach(). this takes consumer interface and it doesn’t return anything only for consuming. below example,</p><pre>List&lt;Integer&gt; arrayList = Arrays.<em>asList</em>(10,20,30,40,50);<br>arrayList.stream().filter(num -&gt; num%2 == 0).forEach(e -&gt; System.<em>out</em>.println(e));</pre><ul><li>We can directly access method from methods using <strong>:: sign.</strong></li></ul><pre>forEach(e -&gt; System.<em>out</em>.println(e)) <strong>// before using ::</strong></pre><pre>forEach(System.<em>out::</em>println); <strong>// after using ::<br>// From this sign it directly access the variable value pass by forEach.</strong></pre><ul><li>filter() method takes predicate functional interface</li><li>map() method takes consumer functional interface</li></ul><h3>How Stream API process a collection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5owzzgouU9xJkrjrj-7fw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17a07ea509dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collection and Generics I]]></title>
            <link>https://medium.com/@snishajith/collection-and-generics-i-3090b1737df8?source=rss-48a72e47d70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3090b1737df8</guid>
            <dc:creator><![CDATA[Sachintha Punchihewa]]></dc:creator>
            <pubDate>Fri, 29 Oct 2021 05:34:51 GMT</pubDate>
            <atom:updated>2021-11-04T04:05:25.250Z</atom:updated>
            <content:encoded><![CDATA[<ul><li><strong>A collection is a group of objects.</strong></li><li><strong>A collection framework is a group of classes and interfaces.</strong></li></ul><h3>Why do we need the Collection framework?</h3><p>When we need to store 100 numbers. We need to create 100 variables. That is difficult. To overcome this let’s move on to an array. When we store data in an array we have to give the array data type and fixed value. When going to get the values from the array for each value we have to mention<strong> int[0]; </strong>like this. Also, an array can hold homogeneous data (The same data type ). but what if we can use an object array? is it good? it can hold all the data types so, we can fix our problem using an object array? no there are some problems.</p><ul><li>Value is fixed when defining an array.</li><li>When we store more value than fixed array size it will throw an exception or if we store less amount of given array size the rest of the space will be wasted.</li><li>An array is not growable by nature and it doesn’t have a data structured ready-made methods.</li></ul><h3>To overcome the above problems we have the Collection framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*LtfjgOigRB1sCHAMcHigMA.png" /></figure><ul><li>In every collection, there are certain types of methods available in manipulating data.</li></ul><h3>Difference between Collection and Collections?</h3><ul><li>The collection is an interface that comes under the collection framework.</li><li>Collections is a class that is in java.util.Collections. It gives some certain methods to manipulate the Collection interface’s objects to perform some operation.</li><li>The Collection interface is the root interface. Others are child interfaces of Collection. Whatever methods are available in the Collection root interface will go to child interfaces with the help of inheritance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*kb2FQW47ckuds1_Y5mTNcg.png" /></figure><h3>List Interface</h3><ul><li>The list can store a group of elements of the object.</li><li>When we add data to List its order makes insertion order. The way we store data holds the data that is called insertion order.</li><li>Duplicates also are allowed.</li></ul><p><strong>List interface can be divided into some classes that we are using when programming.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*kkdbAobOXGHyGlNok5uaWA.png" /></figure><ul><li>Above mentioned<strong> Stack ( C ) &amp; Vector ( C ) </strong>classes are legacy classes that are coming from the beginning of java.</li></ul><h3>Set Interface</h3><ul><li>Insertion order is NOT allowed.</li><li>Duplicates are NOT allowed.</li><li><strong>LinkedHashSet </strong>&amp; <strong>HashSet </strong>are<strong> </strong>implemented in this <strong>Set </strong>interface.</li></ul><h4>Differences List &amp; Set</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AzOARdq59wCiPjZ_BrDaHQ.png" /></figure><h3>Queue Interface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*iQa0wJY3tNXEQa1cc5pOFw.png" /></figure><ul><li>First In First Out ( FIFO ).</li><li>This interface is implemented from <strong>Priority Queue Class.</strong></li><li>ex. The first added email will be sent first and the last added email will be sent last.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*ZgZqkm9Mcci8rjWcApXIGg.png" /></figure><h3>Map Interface</h3><ul><li>This Map interface is NOT derived from the Collection interface. This is a different interface. bu, this also comes under the Collection framework.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*6LGElX_y9xdiF1C_6_e0rg.png" /></figure><h4>When do we need to go for a map?</h4><ul><li>From the map interface also we can represent groups of objects. bu, those objects will be key-value pairs.</li><li>Key and value both are objects.</li><li>Keys cannot be duplicated, which means we can run the program by duplicating the keys. but, what happens internally is, it gets the duplicate last added element as <strong>key &amp; value pair.</strong></li><li>Values can be duplicated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*GyWyntG_YEM216jbWFtZCA.png" /></figure><h3>If we want to represent a set of objects as a single entity we for the Collection API. So what are the methods in Collection to manipulate those objects?</h3><h4>Some of the methods are available in the Collection interface. These all methods are abstract methods, which means these methods should be implemented using sub-classes or interfaces.</h4><pre>methodsOfCollection.add(Object o);<br>methodsOfCollection.addAll(Collection c);<br>methodsOfCollection.remove(Object o);<br>methodsOfCollection.removeAll(Collection c);<br>methodsOfCollection.retainAll(Collection c);<br>methodsOfCollection.clear();<br>methodsOfCollection.isEmpty();<br>methodsOfCollection.size();<br>methodsOfCollection.contains(Object o);<br>methodsOfCollection.containsAll(Collection c)<br>methodsOfCollection.toArray();</pre><p>These methods are implemented in all other sub interfaces and classes, so in those classes and interfaces also we can find these methods out. but, not in the Map subclasses cause it doesn’t implement from the Collection interface.</p><p>Rather than these abstract methods available in the Collection interface, there are other methods that are specified to the particular sub-classes and interfaces in the Collection API. like below,</p><p><strong>List interface methods.</strong></p><pre>list.add(Object o);<br>list.addAll(index,Collection c);<br>list.remove(index);<br>list.get(index);<br>list.set(index, Object o);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3090b1737df8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a HashSet checks for duplicates: hashCode() and equals()]]></title>
            <link>https://medium.com/@snishajith/how-a-hashset-checks-for-duplicates-hashcode-and-equals-5e2082b35d9f?source=rss-48a72e47d70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e2082b35d9f</guid>
            <dc:creator><![CDATA[Sachintha Punchihewa]]></dc:creator>
            <pubDate>Wed, 27 Oct 2021 12:05:51 GMT</pubDate>
            <atom:updated>2021-10-27T12:05:51.090Z</atom:updated>
            <content:encoded><![CDATA[<p>When you put an object into a HashSet, it uses the object’s hashcode value to determine where to put the object in the Set. But it also compares the object’s hashcode to the hashcode of all the other objects in the HashSet, and if there’s no matching hashcode, the HashSet assumes that this new object is not a duplicate. In other words, if the hashcode is different, the HashSet assumes there’s no way the objects can be equal.</p><p>So you must override hashCode() to make sure the objects have the save value. But two objects with the same hashCode() might not be equal ( more on this on the next page), so if the HashSet finds a matching hashCode for two objects one you are inserting and one already in the set the HashSet will then call one of the object’s equals() methods to see if these HashCode matched objects really are equal.</p><p>And if they are equal, the HashSet knows that the object you are attempting to add is a duplicate of something in the Set, so the add doesn’t happen.</p><p>You don’t get an exception, but the HashSet’s add() method returns a boolean to tell you (if you care) whether the new object was added. So if the add() method returns false, you know the new object was a duplicate of something already in the set.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e2082b35d9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What makes two objects equal?]]></title>
            <link>https://medium.com/@snishajith/what-makes-two-objects-equal-3a85801cd085?source=rss-48a72e47d70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a85801cd085</guid>
            <dc:creator><![CDATA[Sachintha Punchihewa]]></dc:creator>
            <pubDate>Wed, 27 Oct 2021 11:17:50 GMT</pubDate>
            <atom:updated>2021-10-27T11:17:50.363Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reference equality</h3><p><strong>Two references and one object on the heap</strong></p><p>Two references that refer to the same object on the heap are equal. If you call the hashCode() method on both references, you will get the same result. If you don’t override the hashCode() method, the default behavior (remember, you inherited this from class Object) is that each object will get a unique number ( most versions of java assign a hashcode based on the object’s memory address on the heap, so no two objects will have the same hashCode).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*8id-hesMvhZ3wrUNIdDK8A.png" /><figcaption>reference from head first java book</figcaption></figure><h3>Object equality</h3><p><strong>Two references, two objects on the heap, but the objects are considered meaningfully equivalent.</strong></p><p>If you want to treat two different Customer objects as equal ( for example if you decided that two Customers are the same if they have matching name variables) you must override both the hashCode() and equals() methods inherited from class Object.</p><p>As we said above, If you don’t override hashCode(), the default behavior (from Object) is to give each object a unique hashcode value. So you must override hashCode() to be sure that two equivalent objects return the same hashcode. But you must also override equals() so that if you call it on either object, passing in the other object, always return true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*zVzPTvv2UfmKmCIR-ypNXQ.png" /><figcaption>reference from head first java</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*tEKS890aL97_b5mvRMm1Ng.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a85801cd085" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading and Socket programming]]></title>
            <link>https://medium.com/@snishajith/multithreading-and-socket-programming-a7573c6d30c7?source=rss-48a72e47d70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7573c6d30c7</guid>
            <dc:creator><![CDATA[Sachintha Punchihewa]]></dc:creator>
            <pubDate>Tue, 26 Oct 2021 11:12:07 GMT</pubDate>
            <atom:updated>2021-10-26T11:12:07.800Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multithreading programming</h3><h3>A TCP port</h3><p>A TCP port is just a number. A 16-bit number that identifies a specific program on the server.</p><h3>Socket programming</h3><p>It is a programming concept that makes use of sockets to establish connections and enables multiple programs to interact with each other using a network.</p><p>Sockets provide an interface to establish communication using a network protocol stack and enable programs to share messages over the network.</p><h3>Java multithreading</h3><p>Java has multiple threads but only one Thread class. A thread is a separate thread of execution. That means a separate call stack. Every Java application starts up the main thread. The thread that puts the main() method on the bottom of the stack. The JVM is responsible for starting the main thread ( and other threads, as it chooses, including the garbage collection thread). As a programmer, you can write code to start other threads of your own.</p><p>When we run a normal java program that we are not creating a thread but how the program is being run? it’s because the JVM puts the main thread into the program which is our main method when our main method starts the main thread will be created. that’s what we need at least the main method to run the program.</p><p>when running another thread the main thread will be temporarily frozen while the new thread starts running. The JVM switches both threads until both threads&#39; tasks will be finished.</p><h3>How to launch a new Thread</h3><p><strong>There are two ways of making java threads</strong></p><ol><li>Java Runnable interface</li><li>Thread class</li></ol><p>why these two are there? specially Runnable interface because java is not supported by multiple inheritance so we cannot take the Thread class extends if we have already extended another class. that’s why mainly the Runnable interface is there. Runnable thread has only one method which is <strong>public void run();</strong> it is a contract.</p><pre>public class MyRunnable implements Runnable{<br>    @Override<br>    public void run() {<br>        System.<em>out</em>.println(Thread.<em>currentThread</em>());<br>    }<br>}<br><br>class MainClass {<br>    public static void main(String[] args) {<br>        System.<em>out</em>.println(Thread.<em>currentThread</em>());<br>        Runnable threadJob = new MyRunnable();<br>        Thread myThread = new Thread(threadJob);<br><br>        myThread.start();<br>        System.<em>out</em>.println(&quot;Back in main&quot;);<br>    }<br>}</pre><p>Runnable is in java.lang package, so you don’t need to import it.</p><p>Runnable has only one method to implement,<strong> public void run() </strong>with no arguments. This is where you put the JOB the thread is supposed to run. This is the method that goes at the bottom of the new stack.</p><p>Then we have to pass the new Runnable instance into the new Thread constructor. This tells the thread what method to put on. the bottom of the new stack. In other words, the first method that the new thread will run.</p><p>You won’t get a new thread of execution until you call start() on the thread instance. A thread is not really a thread until you start it before that it’s just a thread instance, like any other object, but it won’t have any real ‘threadness’.</p><h3>The three states of a new thread</h3><ol><li>New</li></ol><p><strong>Thread t = new Thread(r);</strong></p><p>A thread instance has been created but not started yet.</p><p>2. Runnable</p><p><strong>t. start();</strong></p><p>when you start the thread it will move to the runnable state. This means the thread is ready to run and just waiting for its big chance to be selected for execution. At this point, there is a new call stack for this thread.</p><p>3. Running</p><p>This is the state all threads lust after! Currently running thread. only the JVM thread scheduler can make that decision. you can sometimes influence that decision, but you cannot force a thread to move from unable to running. In the running state, a thread ( and only this thread) has an active call stack, and the method on the top of the stack is executing.</p><h3>Typical runnable / Running</h3><p>Typically, a thread moves back and forth between runnable and running, as the JVM thread scheduler selects a thread to run and then kicks it back out so another thread gets a chance.</p><h3>What is “write once run anywhere”</h3><p>SO what does this mean to write once run anywhere? It means that to write platform-independent Java code, your multi-threaded program must work no matter how the thread scheduler behaves. That means that you can&#39;t be dependent on, for example, the scheduler making sure all the threads take nice, perfectly fair, and equal turns at the running state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*8x6Cpy5Vce4Cf-g0V47cdA.png" /></figure><h3>Summary</h3><ul><li>Every thread in java has its own call stack.</li><li>A thread needs a job to do. A Thread’s job is an instance of something that implements the Runnable interface.</li><li>The Runnable interface has just a single method, run(). This is the method that goes on the bottom of the new call stack. in other words. it is the first method to run in the new thread.</li><li>To launch a new thread, you need a Runnable to pass to the Thread’s constructor.</li><li>A thread is in the new state when you have instantiated a thread object but have not yet called start().</li><li>The scheduler is the one who can decide which thread runs first and should come to the runnable state.</li><li>A thread is in the NEW state when you have instantiated a Thread object but have not yet called start();</li><li>When you start a thread by calling the Thread object’s start() method a new stack is created, with the Runnable’s run() method on the bottom of the stack. The thread is now in the RUNNABLE state, waiting to be chosen to run.</li><li>A thread is said to be RUNNING when the JVM’s thread scheduler has selected it to be the currently running thread. on a single processor machine. there can be only one currently running thread.</li><li>Sometimes a thread can be moved from the RUNNING state to a BLOCKED state. A thread might be blocked because it’s waiting for data from a stream or because it has gone to sleep, or because it is waiting for an object’s lock.</li><li>We cant reuse a Thread object once a thread’s <strong>run() </strong>method has been completed, the thread can never be restarted. In fact, at that point the thread moves into a state we haven’t talked about-dead. In the dead state, the thread has finished its run() method and can never be restarted.</li></ul><pre>public class MyRunnable implements Runnable{<br>    public static void main(String[] args) {<br>        MyRunnable runner = new MyRunnable();<br>        Thread alpha = new Thread(runner);<br>        Thread beta = new Thread(runner);<br>        alpha.setName(&quot;This is Aplha..&quot;);<br>        beta.setName(&quot;This is Beta&quot;);<br>        alpha.start();<br>        beta.start();<br>    }<br><br>    @Override<br>    public void run() {<br>        for (int i = 0; i &lt; 10; i++){<br>            String threadName = Thread.<em>currentThread</em>().getName();<br>            System.<em>out</em>.println(threadName + &quot; is running...&quot;);<br>        }<br>    }<br>}</pre><pre>/* ------output------<br>    * This is Beta is running...<br>This is Aplha.. is running...<br>This is Beta is running...<br>This is Aplha.. is running...<br>This is Beta is running...<br>This is Aplha.. is running...<br>This is Beta is running...<br>This is Aplha.. is running...<br>This is Beta is running...<br>This is Aplha.. is running...<br>This is Beta is running...<br>This is Aplha.. is running...<br>This is Beta is running...<br>This is Aplha.. is running...<br>This is Beta is running...<br>This is Aplha.. is running...<br>This is Beta is running...<br>This is Aplha.. is running...<br>This is Aplha.. is running...<br>This is Beta is running...<br><br>Process finished with exit code 0<br><br>    * */</pre><p>Will the threads take turns? will you see the thread names alternating? How often will they switch? With each iteration? After iterations?</p><p>You already know the answer — we don’t know! It’s up to the scheduler, and on your OS, with your particular JVM, on your CPU, you might get very different results.</p><h3>What is Synchronize keyword in java threads?</h3><p>The synchronized keyword means that a thread needs a key in order to access the synchronized code. To protect your data (like a bank account) synchronize the methods that act on that data.</p><p>We need to make sure that once a thread enters to a method it must be allowed to finished the method before any other thread can enter.</p><p>simply we use the synchronize keyword to avoid accessing a one object by more than one thread. if we add the synchronized keyword to our method it let access for a thread at a time. so that other thread should be wait till current working thread inside accessing the method finishes the work.</p><h3>The deadly side of synchronizatoin</h3><p>Thead deadlock happens when you have two threads, both of which are holding a key the other thread wants. There’s no way out of this scenario, so the two theads will simply sit and wait. and wait. and wait.</p><p><strong>All it takes for deadlock are two objects and two threads.</strong></p><p>A simple deadlock scenario,</p><p>Therea are Thread A , B. and also there are foo method and bar. both are synchronized.</p><ol><li>Thread A enters a synchronized method of object foo, and gets the key.</li><li>Thread A gois to sleep holding the foo key.</li><li>Thread B enters a synchronized method of object bar, and gets the key.</li><li>Thread B tries to enter a synchronized method of object foo, but can’t get that key ( because A has it ) B goes to the waiting lounge, until the foo key is available. B keeps the bar key.</li><li>Thread A wakes up ( still holding the foo key ) and tries to enter a synchronized method on object bar, but can’t get that key because B has it. A goes to the waiting lounge, until the bar key is available ( it never will be )</li><li>Thread A can’t run until it can get the bar key. but B is holding the bar key and B can’t run until it gets the foo key that A is holding and…</li></ol><h3>Summary</h3><p>You can name a thread using setName() method. All threads get a default name, nut giving them an explicit name can help you keep track of threads, especially if you are debugging with print statement.</p><p>Two or more threads accessing the same object can lead to data corruption if one thread, for example, leaves the running state while still in the middle of manipulating an object’s critical state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7573c6d30c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serialization — I/O]]></title>
            <link>https://medium.com/@snishajith/serialization-i-o-a368e39827cf?source=rss-48a72e47d70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a368e39827cf</guid>
            <dc:creator><![CDATA[Sachintha Punchihewa]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 11:55:03 GMT</pubDate>
            <atom:updated>2021-10-25T11:55:03.985Z</atom:updated>
            <content:encoded><![CDATA[<h3>Serialization — I/O</h3><h3>if you want your class to be serializable, implement Serializable interfae</h3><p>The Serializable interface is known as a marker or tag interface, because the interface doesn’t have ny methods to implement. Its sole purpose is to announce that the class implementing it is, well serializable. In other words, objects of that type are saveable even if the subclass doesn’t explicitly declare implement Serializable. If you superclass is Serializable, you are too.</p><p>Serializable interface in <strong>java.io.*; </strong>package.</p><h3>Why we implement Serializable interface to Encapsulated class?</h3><pre>import java.io.Serializable;<br><br>public class Customer implements Serializable {<br>    private int width;<br>    private int height;<br><br>    public Customer(){<br>    }<br><br>    public Customer(int width, int height) {<br>        this.width = width;<br>        this.height = height;<br>    }<br><br>    public int getWidth() {<br>        return width;<br>    }<br><br>    public void setWidth(int width) {<br>        this.width = width;<br>    }<br><br>    public int getHeight() {<br>        return height;<br>    }<br><br>    public void setHeight(int height) {<br>        this.height = height;<br>    }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Customer{&quot; +<br>                &quot;width=&quot; + width +<br>                &quot;, height=&quot; + height +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>Because when we work with objects in java we have to save and retrieve these objects. So to do that we have to do some operations in those operations it is one part is called Serialize when coding. that’s why we have to implement Serializable interface to our encapsulated class. otherwise whatever goes to writeObject() method must implement Serializable or it will fail at runtime.</p><p>Serializable is in the java.io package, so you need to import the package.</p><p>No methods to implement, but when you say “implements Serializable”, it says to the JVm, “it’s OK to serialize objects of this type”</p><h3>transient keyword</h3><p>If you want an instance variable to be skipped by the serialization process, mark the variable with transient keyword.</p><pre>public class Customer implements Serializable {<br>    <strong>transient</strong> private int width;<br>    private int height;<br>}</pre><p><strong>transient says, “don’t save this variable during serialazation, just skip it”</strong></p><p>So why would a variable not be serializable? It could be that the class designer simple forgot to make the class implement Serializable. Or it might be because the object relies on runtime-specific information that simple can’t be saved. Although most things in the Java class libraries are threads, or file objects. They are all dependent of ( and specific to) a particular runtime ‘experience’ . In other words, they are instantiated in a way that’s unique to a particular run of your program, on a particular platform, In a particular JVM. once the program shuts down, there’s no way to bring those things back to life in any meaningful way. they have to be created form scratch each time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a368e39827cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Risky Behavior ( Exception handling )]]></title>
            <link>https://medium.com/@snishajith/risky-behavior-exception-handling-726cbbe769cf?source=rss-48a72e47d70c------2</link>
            <guid isPermaLink="false">https://medium.com/p/726cbbe769cf</guid>
            <dc:creator><![CDATA[Sachintha Punchihewa]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 08:19:43 GMT</pubDate>
            <atom:updated>2021-10-25T08:19:43.286Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is an Exception in java</h3><p>An exception is a normal thing. we have to handle the exceptions in java. it means something risky thing happens in our code. however, we have to solve it. An exception is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TgmPvroXeoyN7wbj.png" /></figure><p>We call as unckeck exceptions for Error &amp; RuntimeExcetions. Rest of the all others are called check exceptions. If there is a checked exception in our program we should follow a rule called catch or specify. for others not must if we want also we can apply this rule to others exceptions also rather than checked exceptions. if there is a checked exception in our program compiler will check if we have obey to the catch or specify rule if NOT compiler will ask us to make it up by saying a compile time error, otherwise it won’t compile.</p><h3>What is Error and Exception</h3><p><strong>Error</strong></p><p>simply error means we can’t revocer it, why I say it it is something like errors that comes with unhandlable things, Stack overflow error and outOfMemoryError something like this kind of errors we cannot handle it at all. just because we can’t handle the error we should not saying just doing nothing at least we should give a message to the user because from an error it has less of recovering.</p><p><strong>Exception</strong></p><p>For a exceptions we have to do many things handling an exception in java.</p><p>If we won’t get an unchecked exception we should catch or specify that exception. ex: class.forName(“Drive”); in Sql they have implemented the Driver class using specify exception that’s why when we are gonna use that driver class they say us to there is a risk thing please catch or specify. they have also returned <strong>classNotFoundError.</strong></p><p>If we catch a risky method it is okay we can handle it but think what happens if we speficy a Exception in method declaration what will happen? It just propagate to our super class method and ask also it to please use this catch or specify rule for your calling method. However if we proporgate our exception to the highest hirrachy of our program what happens? finally it comes to the main method and from that also if we throws an exception by specifying. so that from inside the JVM have to catch or specify the calling method by thread.</p><p><strong>PrintStackTrace</strong></p><p>Usually when an exception comes we are handling it try of catch method inside the catch we have seen something like printStackTrace? what it would be? it simply does going on stack which is in our memory area and get what is the thing happening outthere if it cannot find anything related to the exception it prints the stackTrace with all the evidence that he found out.</p><p><strong>Note : </strong>if the process finished with exit code 0 and 1, what is the meaning of this? if it prints without having any error it prints 0 and when it comes to 1 there is something went wrong with the code. so we have to check it.</p><p><strong>Throwable</strong></p><p>Java Throwable is a class, it have divided into two parts called Error and Exceptions. like mentioned the above Errors are not handled by us.</p><p><strong>Unckeck and checked</strong></p><p>We also catch an uncked exception but it nothing happens because if there is something to happen we can’t do anything to stop it.</p><p><strong>Thread and propargate</strong></p><p>remember if there is a situation jvm catch the error the execution thread will stop that means the system will stop. If we explicitly catch or specify the error the thread will not be stopped at all.</p><h3>You can’t put bigger baskets above smaller baskets</h3><p>Well, you can but it won’t compile. Catch blocks are not like overloaded methods where the best match is picked. with catch blocks, the JVM simply starts at the first one and works its way down until it finds a catch that’s broad enough (in other words, high enough on the inheritance tree) to handle the exception. if your first catck block is catck(Exception e), the compiler knows there’s no point in adding any other. the’ll never be reached.</p><h3>Rules of Exception Handling</h3><ol><li>You cannot have a catch or finally without a try.</li><li>You cannot put code between the try and the catch</li><li>A try MUST be followed by either a catch or a finally</li><li>A try with only a finally (no catch) must still declare the exception. ( because you have a finally, even though there’s no catch. But you cannot have a try by itself)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=726cbbe769cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>