<?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 Thishankahadugoda on Medium]]></title>
        <description><![CDATA[Stories by Thishankahadugoda on Medium]]></description>
        <link>https://medium.com/@thishankahadugoda?source=rss-45402ccc85a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FeP1jJCien3kbz5mpWOseQ.jpeg</url>
            <title>Stories by Thishankahadugoda on Medium</title>
            <link>https://medium.com/@thishankahadugoda?source=rss-45402ccc85a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 24 May 2026 04:28:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thishankahadugoda/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[Threads in Java]]></title>
            <link>https://medium.com/@thishankahadugoda/threads-in-java-39a27843d6cc?source=rss-45402ccc85a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/39a27843d6cc</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[extend]]></category>
            <category><![CDATA[threading-in-java]]></category>
            <category><![CDATA[runnable]]></category>
            <category><![CDATA[thread-life-cycle]]></category>
            <dc:creator><![CDATA[Thishankahadugoda]]></dc:creator>
            <pubDate>Thu, 11 Nov 2021 13:37:58 GMT</pubDate>
            <atom:updated>2021-11-11T13:37:58.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*BKtSYNe9kJLb65-cggTUaw.jpeg" /></figure><p>A lots of people think threads is used to cut down the time. that is not how it’s going to work. If you have some proper process which runs for 10 minutes so there is no guarantee you can use 10 threads to get cut down up to one minute. That is not how its going to work. Let’s take example to see why it’s not like that</p><p>We have process which has five steps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*F50B-DBOlmrPZn_tErcP7w.png" /></figure><p>All together we have 11 seconds of processes. Looking at this chart you will see you have five steps.can you we use five different threads and take this 11/5 to 2 seconds. No which is not possible. Why ? <strong><em>Because there are dependency tasks. </em></strong>so what is the mean by dependency tasks? For an example you can’t save the data to database before validating and the preparation. But you can do these two tasks parallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMNTuK3Jl4GUaIxiMu5Qhg.png" /></figure><p>Then you can use two different threads. then you can cut down the time little bit more than 11 seconds. <strong><em>There are no way you can increase the number of threads and cut down the process up to 1 seconds or two seconds that’s not multi-threading in other words you can’t use separate thread to each task and cut down processing time if those are dependent.</em></strong></p><h4><strong>Multi- threading means multiple processors / multi tasking. Multi tasking has a two types one is process based and another one is thread based.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04XYR1Zn0wIg3CWn5jaeHA.png" /></figure><p><strong><em>What are the differences between these two ?</em></strong></p><p>Sometime When you type code or when you type the document you , you listen to the music at the same time you download the some file from the internet. So that means you are doing the<strong><em> multiple things on the same time.</em></strong> <strong><em>In other words in the same given time there are three processors running on your computer.</em></strong> So if you stop downloading a file will it effect your music ? No will it effect to the what you whatever type ?no so that means these tasks are independent. <strong><em>You can kill any task at any given time which does not give any single effect to other tasks.</em></strong> So that means your operation system run multiple processors in same time which are multiple programs. So that’s called <strong><em>process based multi tasking</em></strong>.</p><p><strong>Then what is thread based multitasking ?</strong></p><p><strong><em>The main significant difference is in thread based multitasking is these threads are belongs same project or same main process which run in operating system</em></strong>.<strong><em> In process based example operating system has three different processes</em></strong> . As far as operating system concern there are three processor and in thread based multitasking as far as operating system concerns it can be a one process. So within that one process we can divide into multiple task. For an example let’s say you have 50 files to process on your project. So your task is read the file and save it into database. Let’s assume that 50 files takes 50 minutes to finished the job. If you use two threads then you can cut down the time probably for 30 minutes likewise you can increase it. You can do three threads so what it does is one thread is go take a file and process it and put it into database at the same time other thread will go and take file and read it and put it into database. Why?<strong> Because these tasks does not have any dependency. </strong>You can use 50 threads and cut down the time unto 5 or 10 minutes BUT there is no way to you can use 100 threads and take this time down to one second or sometime like that. In other words there is no way to you can so something within no time by just increasing the threads.</p><p>Why you can use more than 50 threads for 50 files ? Because you have a 50 files right so there is no point to two threads go and take to same file to and trying to process it. This example is get idea about threads and what are the limitation about threads.</p><blockquote><strong>As a conclusion there are two types of multitasking one is process based and other one is thread based. If its a process based those are independent from each other, you can kill any process at any time there is no effect on others but when you go the threads based those threads are belongs to one process itself.</strong></blockquote><blockquote><strong>what is the thread ? Threads is flow of execution. If you take one thread it’s keep executing all the things maybe multiple instruction you’re executing same time. But if it’s a multithreads so from certain point it go to multiple flow of execution.</strong></blockquote><h3>How create a thread ?</h3><p>There are two ways to create threads in java. <strong><em>One is you can extend Thread class and second way to create a thread is implements runnable interface.</em></strong></p><p>No matter how you create. The behaviour of the thread and what the thread does is won’t change. Lets take simple example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*vsVf1QQIgBhDvuhDNJU1pg.png" /></figure><p>We have human, we have man and from a man we have sport man , from a sportsman we have a runner. This mean tell us this is simple inheritance. what it tells runner is sportsman , sportsman is man and man is human. <strong><em>End of the hierarchy runner is human</em></strong>. In other words we create man from Human because man is more specific than the Human, we create sportsman from a man because sportsmen is more than specific than man and finally we create runner from a sportsmen because runner is more specific.</p><p>For the reasons if we want to convert this Runner into threads if we extends this into threads class then what happen is break runner and sportsmen relationship. ( runner is a sportsmen relationship in break it) so that means here onwards Runner is a thread.</p><p>In the previous inheritance, end of the hierarchy Runner is a Human which is perfect valid scenario to present. But movement we extend the runner from the Thread class , we break that relationship. This is one of the disadvantage in threads. Because java did not support multiple inheritance but java support multiple implementation so it’s always welcome to implement from the runnable interface and if you want give different behaviour implement from those interfaces as well.</p><p>Let’s assume this example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*ElPvmARwr08gVKIA8QlnUg.png" /></figure><p>We have class Printer that extends from Thread class and here we have to <strong><em>override run() Method</em></strong> and let’s print 0 to 1000. This is the thread class . In other class( main method ) inside the main method we create object from printer “p” and call the start() method using p.start(). We can see start method don’t have inside the printer class but printer come from a thread class and Thread class has a start method. The main thread will also printing 0 to 100. Now main thread start to new thread which is child thread which is supposed to print 0 to 1000 after start method calls main thread start to print 0 to 100.</p><p>So what is behaviour of this project (code) ?</p><p><strong><em>Will it terminate the project just after printing 0 to 100 that means child thread will not able to complete the job ?</em></strong> ( java terminate the program only two cases one is if someone call system.exist or when you kill the last non-deamon thread )<strong><em> in this case we didn’t mention new thread is deamond or non- deamon thread so It will have a default behaviour.</em></strong></p><p>The question is the movement it print the 0 to 100 what the output will see? Will the program will terminate or will the program will wait until the child thread complete its job?</p><h4>The Printer class extend the Thread class and It’s must override the run() method. Let’s see what happen when if we did not override the run method.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*317104W_K93mEmb2CvydFg.png" /></figure><p><strong><em>When we execute the above code it will execute without errors.</em></strong> So the point is <strong><em>you can call the start method and it is not must to override the run() method</em></strong>.<strong><em> in other words if its must to override run() method in your thread implementation class? No it’s not if you’re going with extend keyword</em></strong>.</p><h3>This is how it work.</h3><p>When you go to Thread class, Thread class has the run method. When you call the start() method in main class ( p.start() ) it go and see the printer class has start() method, but in this case <strong>p<em>rinter class don’t have start method </em></strong>so then it go to parent class ( Thread class because printer class extend from Thread class ).<strong><em> Thread class has start() method</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*uXdgkt3N7_6124PHLyix5Q.png" /></figure><p>Within the start() method , they invoke the run() method. When you invoke the run() method, it go and see do I have run() method in printer Class ? No so what it does is ,it has run method inside the Thread class as well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*VAM3ls-TPe6gCCGG_uc6rw.png" /></figure><p>It does not doing anything. In this case it’s empty method. So that’s why above code is working without errors. <strong><em>As a conclusion of this scenario it is not must to override the run method if you extend the thread class but if you not override the run method you are not doing anything</em></strong> . <strong><em>Because whatever the Job thread has to do has to go into run method so if you don’t have run method, there won’t have any job. This scenario valid if you extend the Thread class.</em></strong></p><h4>If you implement the Runnable Interface, you can see it like forcing us to override the run() method.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*pAVsVISRzZePczsuhlQfiQ.png" /></figure><p>So that’s the behaviour of the interface. If you are implementing any interface, you must override all the methods within the interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*N-wvpq7hyrIqRFHXHXXExQ.png" /></figure><p>Back to extends scenario</p><p>Here we do override the run method in extend Thread class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*MTJM-fq_ZMV2mppyLrA3Fw.png" /></figure><p>We can see<strong><em> both threads are printed</em></strong>. You can see here in<strong><em> Main class we call the start() method but we clearly see printer class don’t have start() method</em></strong>. When Printer Class don’t have start method , what it does is it goes to super class. That is standard inheritance practice. When it go to the parent class (Thread class ) , Thread class has the start method.in the start() method , it’s calling run() method. <strong><em>When it called the run method, it check, run method in printer class , if it has run method, then it will executed.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*uXdgkt3N7_6124PHLyix5Q.png" /></figure><p>If you see here , it do something before it go for run method like check threadStatus and it add to the group and finally it started. So there is nothing directly invoke within this start() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*VAM3ls-TPe6gCCGG_uc6rw.png" /></figure><p>In run() method, it’s asking to execute the target.run() so<strong><em> target is runnable object</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*7orMV0XeeqDYOkCquT4bjg.png" /></figure><p><strong><em>So target type is runnable. So that means of our printer class</em></strong>. So now executing run method on our printer class.<strong><em> So when we have run method on our printer class it will execute when we don’t have a run method in our printer class it goes normal way, it goes to the superclass</em></strong>.<strong><em>but it doesn’t do anything.</em></strong></p><p>Let’s assume this scenario</p><p>In main thread ( main class ) supposed to printed 0 to 100 and child thread ( thread class) supposed to printed 0 to 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYoEwhy-QhtEqJ0FKDAvow.png" /></figure><p>when we execute different times each execution has different orders. That brings up to another<strong><em> point whenever you start the thread there is no guarantee order of the thread. There is something called thread scheduler</em></strong>. So you start the thread and what is does is if its fulfilling all those things it will add your thread into thread scheduler. <strong><em>How the thread scheduler works is entirely depend on your JRE ( end of the scenario JVM) because JVM is a specification and JRE is an implementation. It’s depend on the JVM to JVM so that means if its working on windows machine totally different form if it’s working in Linux or macOS machine</em></strong>. The rule is when you start a thread there <strong><em>is no guarantee which order it will execute</em></strong>. That’s why you see above code given different output in different executing.</p><h3>Why we have called the start() method?</h3><p>What happened without calling the start method and directly invoke run method?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VO6dViiH7i2DPNGRKvoEVA.png" /></figure><p>Here we print the thread name main class Thread.currentThread().getName() using this method and thread class using currentThread().getName() method.</p><p><strong><em>You can clearly see now thread name is alway “main” and you can see other behaviour it always execute child before it execute the main. This mean we “only have one thread”. What really happening here when you invoke the run method , you are not giving the opportunity to create a new thread so as a result what happens is it just execute the normal method call.</em></strong></p><blockquote><strong>can we invoke run() method directly in multi-threading scenrio ? yes, but it will not create a new thread, it will execute from the parent thread.</strong></blockquote><h3>why it is forcing us to call for start method ?</h3><p>The reason is before start the thread it has to do many things like see w<strong><em>hether this thread is already exist , whether this thread is ready to run and it needs to register on the registers and adding to thread pools and so and so</em></strong>. We don’t have to do any of these things. JVM take care of everything when you call the start method.<strong><em> When you invoke the start method, it does this do all necessary things and it invoke the run method.</em></strong></p><p>Another scenario</p><h4><strong>What happens when override the start method in thread class ?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tr236e_xqaJoc4a1whzqjA.png" /></figure><p>When executed several time we can see here, override start method called <strong><em>first and printed “ this is start” then print always “ main”</em></strong>. Still we don’t see new thread being created. What we did here ? We<strong><em> simply violated OOP principles.</em></strong></p><p>Printer class called start method so what is usually do is it always give the chance to immediate class, so just print class has start method , then it will execute the that method so we block a being opportunity to create new thread. Why ?<strong><em> Because we are blocking is to invoke thread class start method. So it won’t create a new thread, it won’t do anythings, it won’t work.</em></strong></p><p>Another scenario</p><h4>Can we override the start method and still let you create the thread ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSENbPkbEX3YMYZTRwy4HQ.png" /></figure><p>what we did here is we called <strong><em>super.start() this will do the job</em></strong>. The we have another question ? What is order of printing ?</p><p>So you can see here, <strong><em>it will created new thread because we call the super.start() method</em></strong>. <strong><em>when we execute several times it will generate different results(different order).</em></strong> One movement it will print override method first, then child thread then main thread , another movement it will print child thread first then override start method print and then main thread.</p><h4>The real question is child thread print first, then print the override start() method. Why is this ?</h4><p>What we do exactly here is printer.start() it goes thread class and call the super.start() method. When you call the super.start() it go to parent class which is thread class and it will created thread and add it to thread pool. This time immediately that thread start to involve. That why we got child printed first.</p><p>Diffrent scenario</p><h4>What happen if you put this is start before the super.start() method?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8sz8NtnHnka2T7POxOkcg.png" /></figure><p><strong><em>We can do it. But it will print override method start method always first (“this is start”).</em></strong> Why this is tricky is many people think we can’t do it. Because <strong>super must be first argument of the method</strong>. <strong><em>Super must be fist line of method when we are invoke super constructor. But not for the super class method.</em></strong></p><p>Another scenario</p><h3>What happened overload the run method ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*XqJysVf2jTnKlRB8mFdBLg.png" /></figure><p><strong><em>The result will same. Nothing different. If we overload the run method but thread class start method will always invoke run method with no arguments.</em></strong></p><h3>If child thread do more job than the main thread ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w7eH3LaacMXzznQiDKsGRg.png" /></figure><p>When main thread done this job we can print something like this “main thread done” then we know main thread done it done the job . <strong><em>Main thread print 0 to 10 and child thread print 0 to 100 that means child thread do more job than the main thread.</em></strong></p><blockquote><strong>When we execute the above code we will see no matter main thread done this job ( main thread executed first before the child thread but still main thread allow to execute child thread to done it job), child thread still executing to complete the job.</strong></blockquote><h3>setDaemon thread</h3><p>What we do is <strong><em>setDaemon thread to child thread</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nh5QwFIBrDUc2KyuWTzb-A.png" /></figure><p><strong><em>When we execute again we can see main thread ended and child thread not reach to it target to complete the job.</em></strong> So<strong><em> that means when the child thread is the daemon thread, when the main thread is finished the job then the program will terminate</em></strong>.</p><p>But question is why child thread not finished , the movement main thread finished the job ? B<strong><em>ecause child thread print more lines after main thread executed you can see the output. So reason is we printing it here, how the system.out is works like stream, in thread they force print this , print this .. like that , so there is other process it take and print into console. The movement your thread is end it will process unto some addition print lines. </em></strong>Whenever you terminate the main thread, child thread is process up to some additional values.</p><blockquote><strong>As a conclusion when your child thread is daemon thread, the program won’t wait until your thread complete the job. When you want program waits until complete the job , then you thread should be non-daemon thread. Program always terminate last non-daemon thread terminate.</strong></blockquote><h3>Creating thread using implement Runnable interface</h3><h4>If you implement the Runnable interface you must override the run method</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*NPlPDFnv1xBJRS72uMz9Qw.png" /></figure><p>We can see here currentThread() method not working ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*KgDQVXtjq1UEix3yX2Db3g.png" /></figure><p>Because<strong><em> currentThread() method belongs to Thread class, but when you come from Runnable interface you don’t have that behaviou</em></strong>r.</p><h4>Another point is we clearly see start () method is not working ?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*WakcA2NR7OP5yngzkDInZQ.png" /></figure><p><strong><em>It’s same like start method not belongs to Thread class.</em></strong></p><p>When we implement the Runnable interface, it doesn’t contain any implemented methods. In previous case we extend from Thread class , what happen is our class is extend from a Thread class and Thread implement the Runnable. So end of the scenario it’s coming from Runnable. However what we did is we have intermediate class which called Thread and Thread class implemented all useful methods from Runnable Interface. But now in the this case we don’t have this intermediate Thread class so we don’t have someone to implement this start method.</p><h4>When we go to Runnable interface its like single abstract interface.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*hl3sTtIcAP5Qr4yHLcgaIQ.png" /></figure><p><strong><em>It only have run method. It does not have any other method. There is no way we get the start method</em></strong>.</p><p>What can we do now?</p><p>We can create objects from the Thread class and pass runnable instance for that and instead of print.start() we can call thread.start()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*anueWzjb1d4wiepDb7qjoA.png" /></figure><p>What happen here is,<strong><em> we have Printer class and that class implement the Runnable interface, we create Thread class instance here and when we create the instance we pass our instance from the Runnable interface. That means we pass “p” instance.</em></strong></p><p>What happen when we execute the program ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RvG8AqlQtVzdWkPvZ9OAfg.png" /></figure><p>We can see here it will create child thread and main thread. We get the output, that is mixed with two threads.</p><p>We create Thread class instance and we pass Runnable interface to that. S<strong><em>o that means Thread class has more than one constructor. So Thread class has multiple constructors. It has eight constructor.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*XulvNmz5YErOEW7plD8nxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ol6jpmfN0S4m-ZYUP78_Pw.png" /></figure><blockquote><strong>Every thread in JVM it has the stack. Each method that execute by that thread create frame inside that stack</strong>.</blockquote><h3>Thread priority</h3><blockquote><strong>Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases, the thread scheduler schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses. Note that not only JVM a Java programmer can also assign the priorities of a thread explicitly in a Java program.</strong></blockquote><p><strong><em>The Maximum thread priority is a 10. If you deal with index then 99.9 % times it starts with 0 (zero). But thread priority is not index. Thread priority is value. Thread priority always start with one (1) and end with 10. Normal priority we consider as 5.</em></strong></p><p><strong><em>Default thread priority is always 5 is wrong. Let’s see why default priority is not 5.</em></strong></p><h4>Set the thread priority</h4><p>Here we set the thread priority for child thread to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zVfCMk9AqDprfPd9Eiu20Q.png" /></figure><p><strong><em>That means lowest priority give the child thread and main thread will be finish the job before child thread</em></strong>.</p><p><strong><em>Here we set the thread priority 10 to child thread (maximum thread priority )</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DXlTsZl3-JClqvrQMbD5gw.png" /></figure><p>We give child thread to maximum priority that means child thread executed before main thread executed. Because we give higher priority to child thread.</p><h4>Print the thread priority</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVukeu4LIZ7a8hhoAeBL4g.png" /></figure><p>In above code we print thread priority using getPriority() method for both main and child threads. We can see main thread is 5 and child thread got 10. This is where confusion start default thread priority is 5 .</p><h4>Now stop the setPriority() method assign value 10 to child thread</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTh4ySYarDyESXuwBXdrJw.png" /></figure><p>When we execute the above code, <strong><em>both </em>child and main thread are printed “5”</strong>.</p><p><strong><em>See what happened before we create thread and set thread priority to main thread 1</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zh2F-7IcNqdUPh3i5mMImg.png" /></figure><p><strong><em>Now we will see main thread and child thread get 1 value.</em></strong></p><h4>Before setPriority set to main thread, print the main thread value</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWRNGc7JUKo6XG-RMVxeYA.png" /></figure><p>Now we can clearly see, <strong><em>before we set the setPriority() to main thread it will has value 5 and after assign value to main thread priority both child and main thread got value 1. If we set main thread priority to 7 then, we can clearly identify before assign setPriority() method it will print 5 and after assign setPriority to 7 both thread will print value 7.</em></strong></p><blockquote><strong>Every thread what we created is default priority is 5 is wrong. The rule is any application, main thread default priority is 5, because no one is created thread, system will created thread so it set the priority to five. There after any thread you created, it get inherit parent thread value. There is no rules “always thread priority is five” .</strong></blockquote><h3>Passing the setPriority() method to out of boundary value</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XogEDnnkLyBD13QltNQTkQ.png" /></figure><p><strong><em>There we passing the setPriority() method to 11 and we got exception called “ IllegalArgumentException</em></strong>”</p><h4>What happened if the two thread carrying the same priority.</h4><p>If main thread set to priority 7 then we don’t need to set priority to child thread because child thread inherit priority from main thread. The output is nothing much difference. <strong><em>because when we give two thread to same behaviour there is no way to predict</em></strong>.</p><h3>Thread life cycle</h3><p><strong>When you just defined the thread , we call it is new thread.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2sbLU0IuFdd69IkBX9TOQ.png" /></figure><p>When thread is start, <strong><em>it goes to ready state( runnable state)</em></strong>.processor assign some task, then <strong><em>thread become running state</em></strong>. After running state when the <strong><em>run() is over, then this thread going to be a dead</em></strong>. This is like usual life. <strong><em>When thread goes to dead state, there is no way to come back that means thread is over.</em></strong> But intermediately there are multiple other steps also for example wait or block state. There are few methods we can call that methods and with that methods thread goes to block state (temporarily hold state).</p><p><strong><em>There is very much possibility from running state it can go back to ready state and then go back to running state. It can go back and forth between running and runnable state. But when it goes to dead, it done.</em></strong></p><h3>Join method</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZzTJoGjR59fH6NGu8THaw.png" /></figure><p>There are two threads , thread1 and thread2.<strong><em> Thread1 is waits for thread2 to finish his job. That means thread1 is depend on thread2. In other words thread1 want to result of thread2, to continue thread1 process. Its is not like thread2 want to give result to thread1. so thread1 is call the join method using thread2.join(). </em></strong>These is the where some confusion comes ? Thread1 who waiting until thread2 process and thread1 is going to call the join method but its like thread2.join()</p><p>We can pass <strong><em>join() method to milliseconds not only that we can give join() methods to some milliseconds + some nanoseconds . If you can call the join method these three types. If you call join method without specifying any time that is forever.</em></strong></p><p>If that given time period thread2 is finish the job, thread1 can continue rest of the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUPQIz96Dhs_hEWwLq2mpg.png" /></figure><p>In thread call the join method, runnable state thread become the wait state. In above example thread1 is call the join method on thread2. So thread1 is finish job in certain point and waiting for thread2 to finish the job.</p><p><strong><em>There is rules in thread, if any thread goes to waiting state there is no way directly go to the running state. So end of that ( that means end of the waits state) it has to go to runnable (ready) state.</em></strong></p><p>As I mention above, thread1 is call the join method on thread2, thread1 is going to wait state, <strong><em>there are three ways to thread1 is going to ready state from waiting state,</em></strong></p><p>1. Thread2 is finish the job</p><p>2. Time out occur ( join method we pass the certain time period to complete the job, if time is passed, then thread1 is going to Ready state)</p><p>3. Got interrupted</p><p>Let’s see some example :</p><p>There is two thread main and child thread, these two threads print some values. What we going to do here is <strong><em>after thread.start() method, main thread is waits until child thread complete the job. So main thread decide that call the join method on child thread.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeD78oaas3xIfcUsWrENZA.png" /></figure><p>We can clearly see, main thread until waiting child thread complete the job<strong><em>. so that means child thread executed first then main thread is executed.</em></strong></p><p>Now we call the sleep method to child thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U81WoqR9tXzM2DzPjmakJw.png" /></figure><p>So we pass 250 milliseconds to sleep method, that means every iteration it takes to 250 milliseconds to print the value. Result is same as above, child thread execute first no matter how longs takes time after that main thread is executed.</p><p>Here is the different scenario, we pass 5000 milliseconds to join method. That means <strong><em>main thread will wait only 5 seconds to child thread to complete the job.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCIk4AJSL7-Zvg101QvYIg.png" /></figure><p>Child threads has 50 iteration and each iteration takes 250 milliseconds so that means c<strong><em>hild threads takes 10 seconds to complete the job, but main threads call join method and passing 5000 milliseconds (5 seconds) to wait until child thread complete the job.</em></strong></p><p>That’s the reason why we got output like this. Main threads takes 5 seconds wait , that time period child thread execute half way but when the time out main thread will execute after main thread finish the job rest of the child thread finish the job.</p><h3>Yield , sleep. and interrupt</h3><h3>Yield method</h3><p><strong><em>Yield method is no much useful because the movement use this method, you’re not used of multi threading</em></strong>.</p><blockquote><strong>Why yield method is exist ? Because if you want to like kind of debugging scenario , if you want to give more chance to particular threads that the where yield method comes</strong>.</blockquote><h4>How this works</h4><p><strong><em>If you have two different threads, any thread can call yield method</em></strong>. The <strong><em>movement yield method called, that thread give hint( signal ) to the thread scheduler to saying like “I am giving chance to other threads”. It doesn’t tell to which threads give chance( not specific thread). If the thread scheduler give chance another thread, then that particular thread who the called yield method go to the waiting state. Then other threads will be execute, but there is no guarantee that particular threads gets the chance.</em></strong></p><p>For example there are three threads , t1,t2 an t3 so t1 call the yield method and either t2 or t3 get chance to execute the thread and t1 go to wait state, if t2 get chance, after t2 executed there is no guarantee again t1 get chance to execute. its probably t3 thread get chance to execute. Because t1 is usual agin in the wait state. After t3 execute t1 get chance but its uptown thread scheduler.</p><h4><strong>The whole point of yield method is give the chance to other method.</strong></h4><p><strong><em>Yield is native method. Because it’s not implemented within the java.</em></strong></p><p>Let’s see in practical ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfLGd52SsUb3QgqpC9rvkQ.png" /></figure><p>The child thread call the yield method, that means child thread give chance to other threads( main thread). So main thread will complete the job first after that child thread execute. ( in this case we have two threads if one thread will excite then other will execute after that, but if we have more than two threads, threads scheduler will decide that which thread will execute)</p><h3>Sleep method</h3><p><strong><em>Sleep method what it does is it can wait certain given time. Sleep method has two different method signatures one is sleep with number of long milliseconds so that method is native method that’s not implemented within java, second method is not native method its implemented with java it has two arguments long milliseconds and int nanoseconds</em></strong>. its same as thread.join method.</p><p><strong><em>When call the sleep method we have to pass time to sleep method, otherwise sleep method is call forever that means thread will become dead state. So sleep method have two signatures</em></strong></p><p>When we call the sleep method what<strong><em> sleep method does is thread will go to the waiting state for a certain given time period. So how is come back ? Either given time period is expired or interrupted.</em></strong></p><p>In java threads we have method called interrupt, <strong><em>the movement we execute the interrupt method, what ever the thread is waiting state is coming back. That’s why when you call the sleep method, you have to catch checked exception called interruptException.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ds-Z5CfScOfFkmdHky-Cfg.png" /></figure><p>We call the sleep method in child thread in each iteration it will waits 100 milliseconds.</p><p>What happed if we interrupt this process ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ET3nXLmhO59FzmaGXzJSA.png" /></figure><p>In here we don’t wait to the 5000 milliseconds we call interrupt method in that child thread. We can see<strong><em> main thread will completed the job and it got the interrupted exception.</em></strong> So <strong><em>interrupt only works for one sleep method, that’s the reason why after interrupt method called we got interrupted exception and child thread back to sleep</em></strong>.</p><p>Let’s see another example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wLZitvSIGr-KXsYlcYNzg.png" /></figure><p>When the thread (child thread) get the chance it wait for 5 seconds. In above code we don’t interrupting. When execute the program we can see main thread print first and after 5 seconds child thread get the chance to execute.</p><h3>What happened call the interrupt method without using sleep method ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jF7Lmv5k5yaPLHTAQ39bIQ.png" /></figure><p><strong><em>In this case we did not call the sleep method in child thread, but we call the interrupt method in child thread. In other words call interrupt method which is not sleep. So we can see here main thread and child thread both will execute. No error occurs. Nothing happened. Doesn’t Do any harm</em></strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39a27843d6cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Know Your Variables- Summary of Chapter 03 of Head First Java]]></title>
            <link>https://medium.com/@thishankahadugoda/know-your-variables-summary-of-chapter-03-of-head-first-java-6e20368a1732?source=rss-45402ccc85a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e20368a1732</guid>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[head-first]]></category>
            <category><![CDATA[reference-type]]></category>
            <category><![CDATA[primitive-data-types]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Thishankahadugoda]]></dc:creator>
            <pubDate>Fri, 15 Oct 2021 17:58:19 GMT</pubDate>
            <atom:updated>2021-10-15T17:58:19.821Z</atom:updated>
            <content:encoded><![CDATA[<p>Variables come in two flavours, <strong><em>Primitive and reference</em></strong>. Variable can used as <strong>object state</strong> (Instance variable) , as <strong>local variable( variable declared within a method</strong>), <strong>as arguments</strong>( values sent to a method by calling code) and finally<strong> as return types</strong>( value sent back to the caller the method).</p><p><strong>Java cares about type</strong>. For example if you put a floating point numbers into integer variable, unless you acknowledge to the compiler that you might lose precision( everything after decimal point). Variable divided into two types such as primitive and reference types and<strong> primitives hold fundamental values </strong>( simple bit pattern) including integers, booleans and floating point numbers. <strong>Object reference hold reference to object</strong>.</p><p><strong>Variable must have a type and have a name.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*sIRL78khs-FIfyIVZcH_Nw.jpeg" /></figure><h3><strong>Primitive Types</strong></h3><p>There are <strong><em>eight primitive types variable</em></strong> such as <strong>boolean, char, byte, short, int, long , double and float.</strong></p><p>A variable is just <strong><em>cup ( a Container)</em></strong> . It holds something. It has <strong>a size and a type</strong>. In java primitives come in different sizes and those sizes have names. When you declared a variable in java, you must <strong>declared it with specific type</strong>. Each <strong>primitive variable has a fixed number of bits</strong> ( cup size). The sizes for the six numeric primitives in java are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*FZ0YSF8YuIyZ966F5si6XA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*hW33Otf4YBTCDvYunanoDQ.jpeg" /></figure><h3><strong>Be sure the value can fit into variable</strong></h3><p>You <strong>can’t put a large value into a small cup</strong>. If you want to do that, you will lose some. You will get spillage. The compiler tries to help prevent this if it can tell from your code that something’s not going fit in the container( variable/ cup) you’re using.for example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*xaWPxulEnrVmYbrrVvslqw.jpeg" /></figure><p><strong><em>Why this doesn’t work ?</em></strong></p><p>After all, the value of x is 24 and 24 is definitely small enough to fit into bye, but all the <strong><em>compiler cares about is that you’re trying to put a big things into small thing</em></strong>, and there’s possibility spilling.Don’t expect the compiler will know what the value of x is, even if happen to be able to see it literally in your code.</p><p>The compiler won’t let you put a value from a large cup into a small one. But what about other way- putting <strong>small value into large cup so its work no errors</strong>. The <strong>compiler always error on the side of safety.</strong></p><h3><strong>Back away from that keyword!!!</strong></h3><p>There<strong> are rules in java when you declared name of variables</strong>. You can name a class, variable and method according to the following rules.</p><p>1. The name <strong><em>must start with letter, underscore(_) or dollar sign($)</em></strong>, but <strong><em>can’t start a name with a number</em></strong>.</p><p>2.After <strong><em>first character, you can use numbers as well</em></strong>.( don’t start with a number)</p><p>3.it can be anything you like, subject to those two rules but just so long as it isn’t one of <strong><em>java’s reserved words</em></strong>( java reserved words means java can use specific keywords when creating a program).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*I4r6nRMDNapxJq9FTbgPgQ.jpeg" /></figure><h3><strong>Reference Variable</strong></h3><p>There is actually no such thing as an Object variable. There is only object reference variable. It doesn’t hold the object itself, but it <strong><em>hold something like pointer to address</em></strong>. JVM knows how to use the reference to get to the object. Object reference variable is full of bits representing a way to get to the object. we can use <strong><em>dot operator on a reference variable</em></strong>.</p><p><strong>Ex: dog.bark();</strong></p><p>An object reference is just another variable value ( something that goes in a cup, only this time, the value is a remote control).</p><p>The<strong> <em>three steps of object declaration, creation and assignment</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*FtWn7GanwGUxlqtN0lz2HA.jpeg" /></figure><p><strong><em>1. Decalare a reference variable</em></strong></p><p><strong>Dog myDog = new Dog();</strong></p><p>Tells the JVM to allocate space for a reference variable and names that variable “myDog”. The reference variable is for of type Dog.</p><p><strong><em>2. Create an Object.</em></strong></p><p><strong>Dog myDog = new Dog();</strong></p><p>Tells the JVM to allocate space for a new dog object on the heap.</p><p><strong><em>3. Link the object and the reference</em></strong></p><p><strong>Dog myDog = new Dog();</strong></p><p>Assigns the new dog to the reference variable myDog in other words programs to remote control.</p><p>Note:</p><p><strong><em>All references for a given JVM </em></strong>will be the <strong>same size </strong>regardless of the objects they reference, but <strong>each JVM might have different way</strong> to representing references. So<strong> references on one JVM may be smaller or larger than references on another JVM.</strong></p><h3><strong>Life on the garbage- collection heap</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HBf808BceDNNJa1GYM69fg.jpeg" /></figure><p>Declare <strong>two Book reference variables</strong> and<strong> create two new Book objects</strong>, <strong>assigns the Book objects to the reference variables</strong>. The <strong>two Book objects are</strong> now living on the <strong>heap.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cR5L5uaaURAq2heTLqEvQ.jpeg" /></figure><p>Declare a <strong>new Book Reference variable</strong>.rather creating new, third Book object, assign the value of variable “c” to variable “d” so this means take the bits in “c” , make a copy of them and stick thatchy into “d”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OX8CsNVqpClrb_eTHQqHgg.jpeg" /></figure><p>Assign the value of variable b to variable c. So that means the bits inside variable b are copied and that new copy is stuffed into variable c.</p><h3><strong><em>Life and death on the heap</em></strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wwznYBePC2hrmfm6bRihA.jpeg" /></figure><p>The <strong>two Book objects are now living on the Heap</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5xUqetvXTtBB-iJ9ABKu1g.jpeg" /></figure><p>Assign the value of variable c to variable b.he bits inside variable c are copied and that new copy is stuffed into variable b. Both variables hold identical values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGJ4qXTZhM0A8BkdRK_Mcw.jpeg" /></figure><p>Assign the value null to variable c. This means c a null reference and it doesn’t refer to anything.</p><h3><strong>Array is like a tray of cups</strong></h3><p>1. Declare an int array variable. An array variable is a remote control to an array object.</p><h3><strong>Int [] numbers;</strong></h3><p>2.create a new int array with a length of 7 and assign it to the previously declared int [] variable “numbers”.</p><h3><strong>numbers = new int [7] ;</strong></h3><p>3. Give each element in the array an int value.( elements in an int array are just int variables)</p><h3><strong>numbers[0] =2;</strong></h3><h3><strong>numbers[1] =4;</strong></h3><p>… like this pattern</p><p>Arrays are <strong>always objects</strong>, whether they’re declared to hold primitives or object reference. But you can have an array object that’s declared to hold primitive values.in other words, the <strong>array object can have elements which are primitives, but array itself is a never primitive</strong>.</p><p>Every <strong>element in an array is just a variable.</strong> In other words one of eight primitive variables types or a reference variable.</p><h3><strong>Make an array of reference type</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*VFK7kFYlkaQj0us-mO0ONA.jpeg" /></figure><p>1. Declare a Dog array variable.</p><p><strong>Dog [] pets;</strong></p><p>2.create a new Dog array with a length of 7, and assign it to the previously- declared Dog[] variable “pets”.</p><p><strong>pets = new Dog[7];</strong></p><p>3. Create new Dog Object and assign them to the array elements.( element in a Dog array are just Dog reference variables)</p><p><strong>pets[0] = new Dog();</strong></p><p><strong>pets[1] = new Dog();</strong></p><p>Note:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*q18PX0xQb87izKGMgESxzA.jpeg" /></figure><p>Dog d1 = new Dog();</p><p>d1.name = “Murphy”;</p><p>We created a Dog object and used the dot operator on the reference variable d1 to access the name variable.</p><p><strong>Dogs in Dog array</strong></p><p>When the Dog is in an array, we don’t have an actual variable name (like <em>d1). </em>Instead we use array notation and push the remote control button (dot on an object at a particular Index (position) in the array:</p><p>Dog[] myDogs = new Dog[3];</p><p>myDogs[O] = new Dog() ;</p><p>myDogs[O].name = “Murphy”;</p><p>myDogs[O] .bark();</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e20368a1732" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A trip to Objectville -Summary of Chapter two of Head First Java]]></title>
            <link>https://medium.com/@thishankahadugoda/a-trip-to-objectville-summary-of-chapter-two-of-head-first-java-22189b332849?source=rss-45402ccc85a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/22189b332849</guid>
            <category><![CDATA[class]]></category>
            <category><![CDATA[head-first]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Thishankahadugoda]]></dc:creator>
            <pubDate>Thu, 14 Oct 2021 11:02:33 GMT</pubDate>
            <atom:updated>2021-10-14T11:02:33.419Z</atom:updated>
            <content:encoded><![CDATA[<p>When you design the class, think about the objects that will be created from that class type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JkAQ9cb5iaAorLFN7pbyg.jpeg" /></figure><p><strong>Things the object knows</strong></p><p><strong>Things the object does</strong></p><p>Things an object knows about itself are called <strong><em>instance variable</em></strong>. They represent object’s state (data) and can have unique values for each object of that type.</p><p>Things an object can do are called <strong><em>methods</em></strong>. When you design the class , think about the data an object will need to know about itself and also design methods that operate on that data.objects to have methods that read or write the values of the instance variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*UF3hKKqWeh1n7I9UCefsyQ.jpeg" /></figure><p>So objects have instance variable and methods, but those instance variables and methods are designed as part of the class.</p><p><strong><em>What’s the difference between a class and an object?</em></strong></p><p>A class is <strong>not an object</strong>(but its used to construct them). A class is a <strong>blueprint </strong>for an object.it tells the virtual machine how to make an object of that particular type. For each object Mae from the class can have its own values for the instance variables of that class. For example Button class to make dozens of different buttons and each button might have its own colour, size, shape, label and so on.</p><h3><strong>Making first object</strong></h3><p>To making object we need <strong>two classes</strong>. One class for the type of object want to use (Dog, Alarm, Car, etc.) and another class to test new class. The tester class is where we put main method and in that main() method we create and access objects of new class type. The tester class has only one responsibility is try out the methods and variables of your new object class type. In other words one class will be real class ( the class whose objects we really want to use) and other class will be the tester class so only the test class will have main method and its sole purpose is to create objects of your new type(not the tester class) and then use the dot operator(.) to access the methods and variables of new objects.</p><p><strong>The Dot operator (.)</strong></p><p>The dot operator give access the an object’s state and behaviour( instance variable and method).</p><ol><li><strong><em>Write your class</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*aoqYxr4JMk2-Lio2RzxBkQ.jpeg" /></figure><p><strong><em>2.Write a tester class</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6yrLmajE8Ntu0UMel4fXg.jpeg" /></figure><p><strong><em>3.In tester class, make an object and access the object’s variable and method.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4wuANLSZ8fwjudKTxWdCA.jpeg" /></figure><p><strong><em>The main method</em></strong></p><p>If you are in main method, you are not really in objeczville. it’s fine for a test program to run within the main method, but in a true Object oriented application, need objects talking to other objects.</p><h3><strong>The two uses of main :</strong></h3><p>1. To test your real class</p><p>2. To launch/start your java application</p><p>A real java application is nothing but object calling to other objects.</p><h3><strong>Java takes out the Garbage</strong></h3><p>Each time an object is created in java , it goes into area of memory known as <strong><em>Heap</em></strong>. <strong><em>All objects </em></strong>are <strong>stored</strong> in the Heap area. The java heap is actually called the Garbage-collectible heap.when you created object, java allocates memory space on the according to how much that particular objects needs. How do you get an object out of heap when you’re done with it? Java manages that memory for you.. when the JVM can see that an object can never used anymore, that <strong><em>object become</em></strong><em> </em><strong><em>eligible for garbage collection</em></strong> and if you are running low memory, the garbage collector will run , throw out the unreadable objects and free up the space. So that space can be reused.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22189b332849" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic of java — Summary of chapter one Head first Java]]></title>
            <link>https://medium.com/@thishankahadugoda/basic-of-java-summary-of-chapter-one-head-first-java-b9f868e7eb66?source=rss-45402ccc85a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9f868e7eb66</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[head-first]]></category>
            <dc:creator><![CDATA[Thishankahadugoda]]></dc:creator>
            <pubDate>Wed, 13 Oct 2021 17:35:41 GMT</pubDate>
            <atom:updated>2021-10-14T04:05:37.183Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basic of java — Summary of chapter one of Head first Java</h3><p>The way Java works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtfsyKkjg15j80qCD785Wg.jpeg" /></figure><p>Compiler convert source code file into byte code on a virtual machine using java compiler.</p><p><strong><em>Code structure in Java</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*KOqTIVd_FY7jlC3a985l9g.jpeg" /></figure><p><strong><em>What goes in a Source file?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ggHftHiu7Eht3tl3yZOhCw.jpeg" /></figure><p>A source code file( with the .java extension) hold one class definition.the class represent a piece of programme, although a very small application might need just a single class and class must go within a pair of curly braces.</p><p><strong><em>What goes in a Class?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*2BG2hmYCbuhg29Td78h21w.jpeg" /></figure><p>A class has one or more methods. For example the Dog class has bark method, will hold instruction for how the Dog should bark.methods should declared inside a class.</p><p><strong><em>What goes in Method</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*kLsROUUGGxInHasgvm4gMQ.jpeg" /></figure><p>Within a curly braces of method, write your instructions for how that method should be performed. Method code is a basically a set of statements.</p><p><strong><em>Anatomy of a class</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*IwvGd28n-EEkPQP2GWyOIQ.jpeg" /></figure><p>When the JVM starts running, JVM looks for class that in command line, then is starts looking for specially written method that looks like</p><p>Then, JVM runs everything between curly braces of main method. Very java application has to have at least one class and at least one main method(not one main per class, just one main per application).</p><p>In Java, everything goes in a class, your source code file(with .java extension) the compiler will convert it into class file (with .class extension) when you run the program.running a java program means telling the JVM to load the class and starts executing its main() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXZk3SF7G5jMpUN3Uou4ew.jpeg" /></figure><p>Java is a strongly-typed language, that means cannot allow variables to hold data of the wrong type.This is a crucial safety feature.</p><p><strong><em>Syntax Fun</em></strong></p><ol><li>Each statement must end in a semicolon.</li></ol><p><strong><em>x= x+1;</em></strong></p><p>2. A single-line comment begin with two forward slashes.</p><p><strong><em>//this is the comment</em></strong></p><p>3. Most white spaces does not matter.</p><p>4. Variables are declared with a name and type.</p><p><strong>int age; //type:int, name:age</strong></p><p>5. Classes and methods must be defined within a pair of curly braces.</p><p><strong>public void go() {</strong></p><p><strong>//code goes here</strong></p><p><strong>}</strong></p><p><strong><em>Why does everything have to be in a class?</em></strong></p><p>Java is an object oriented programming language( OOP) so everything in java is an object and class is blueprint for an object.</p><p><strong><em>Do we need to put a main method in every class we wrote?</em></strong></p><p>Nope. A Java program might use a lot of classes, but we might only have one main method, the one that starts the program running. We might write test classes through that have main method for testing other classes.</p><p><strong><em>System.out.print Vs System.out.println</em></strong></p><p>System.out.println inserts a newline while System.out.print keep printing to same line. If you want each thing print out to be on its own line use println. If you want to everything stick together on one line, use print</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9f868e7eb66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambda Expression and Functional Interface]]></title>
            <link>https://medium.com/@thishankahadugoda/lambda-expression-and-functional-interface-dfb7207705b5?source=rss-45402ccc85a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfb7207705b5</guid>
            <category><![CDATA[functionalinterface]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-functional-interface]]></category>
            <category><![CDATA[lambda-expressions]]></category>
            <dc:creator><![CDATA[Thishankahadugoda]]></dc:creator>
            <pubDate>Sun, 10 Oct 2021 20:09:19 GMT</pubDate>
            <atom:updated>2021-10-10T20:09:19.430Z</atom:updated>
            <content:encoded><![CDATA[<p>Lambda expression were added in java 8. A <strong><em>lambda expression</em></strong> is a short block of code which takes in parameters and returns value.Lambda expression is used to provide the clear and concise way to represent one method interface using an expression. Therefore lambda expression is used to provide implementation of an interface which has functional interface. It saves a lot of codes.</p><p>Why came up a concept called<strong> <em>lambda expression</em></strong>?</p><p><em>1. Introduce a functional programming behaviour to java.</em></p><p><em>2.Code should be more simple to understand</em></p><p>You can convert <strong><em>any method to lambda expression</em></strong> so you need to understand basic method characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cl9s5f38KCeMoa9L-DYiww.jpeg" /></figure><p><em>1.Scope modifier(access modifier or static )</em></p><p><em>2.Return type or (void — not return type)</em></p><p><em>3. Parentheses</em></p><p><em>4.Method name</em></p><p><em>5. May have parameters or not</em></p><p><strong><em>Rule of Lambda expression</em></strong></p><p>No modifiers(access)</p><p>No return type</p><p>No method name</p><p>Convert the above method to lambda expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*JbfNKW6z1InkGNI04FRf4w.jpeg" /></figure><p>If code have one line then we can make it more simple (Remove curly braces).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0AgrsgXNhzzL-ofKbIKndg.jpeg" /></figure><p>Here make it more simple</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlI5f76AuLMgqR3LZw0saQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JhhIzSl7U_MzQ0B5RlidQ.jpeg" /></figure><p>We need integer type variable, but sometime compiler can detect (guess) what is the data type of the variable so we can called this type inference, that means we don’t have to tell what is the data type of this variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wn6LXMxr0oHqhudAAOyKJg.jpeg" /></figure><p>If we have only single arguments(parameter), then we don’t have to use parentheses(), then this will become something like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXBhfFSN5rVzdx5SDSzWvQ.jpeg" /></figure><p>In following code, we have two arguments so we cannot remove the parentheses, but we can remove return keyword, because compiler can identify this has to be return therefore no need to write return keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBMioQynbmLdtefr9eoz2Q.jpeg" /></figure><p>In conclusion, lambda expression is <strong><em>more simple way to write a same method</em></strong>. If you know java normal method, you can convert to the lambda expression.in lambda expression have three rules, first one is if you have one line of code, you don’t have to use curly braces.second rule is if compiler can guess the data type, you don’t have to use the data type as well we called this type inference. final rule is if compiler guess its going to be return you don’t have to specify the return type as well. When these rule together we called Lambda expression.</p><p>To called the lambda expression, we need to <strong><em>Functional interface</em></strong>.</p><p>There is method called <strong><em>SAM (Single abstract method)</em></strong> and this concept not introduce java 8, but this concept in functional interface. So SAM and functional interface means single abstract method that’s means your interface can only have single abstract(unimplemented) method.keep in mind not single method.it can only contain single abstract method so that means it can have more than one methods but which should not be abstract.</p><p>In other words, functional interface have <strong><em>multiple method</em></strong>, but <strong><em>only have single abstract method</em></strong>, other methods are not should be abstract method.</p><p>Any given interface if its has only one single abstract method, we called Functional Interface. So advantage is we can use lambda expression along with this functional interface.</p><p>In early days we had a concept, we have an interface, we have a class to implement that interface and then we call that class. So now we remove all those intermediate parts and now we have interface which is functional interface and we just called that functional interface through the lambda expression without having a separate implementation.</p><p>Note: if you have functional interface then you have single abstract method, you have one default method and some other static method so this is fine as long as single abstract method but after you want to change and add other method to functional interface, then all the Lambda expression will fail. Because this is not functional interface anymore. In java has concept called Fail-pass they introduce new annotation called Functional Interface.</p><p>What Functional Interface annotation does is if you put this annotation top of the class, compiler knows this is functional interface that means compiler knows this class can only have a single abstract method.</p><p>This is the example of Functional Interface and that has Single abstract method.Functional interface has any number of default or static methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*69aH8SoISUqGENzCsr8P8Q.jpeg" /></figure><p>But when we add another abstract method, compiler will show error message because functional interface only have single abstract method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*0qFJY0enTHsD300t_cnfQw.jpeg" /></figure><p>here the example of classic interface named “Loan” and that extends from functional interface called “Account”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*8cBxXGuqMj7Fvbz4lekTUg.jpeg" /></figure><p>In “Loan” interface have two abstract methods but its fine because it’s not functional interface (Its classic interface). “Loan” interface extends from “Account” functional interface so extends means more subset of previous one.But if add functional interface annotation in “Loan” interface then compiler will show error and it says multiple non-overriding abstract method. so if you used functional interface annotation both interface and second functional interface can used only<strong><em> overriding method </em></strong>of first interface. in this case “Loan” functional interface can only used “Account” functional interface abstract method otherwise it will show error. In other words “Loan” interface can access its parent interface ‘Account” so Account interface is functional interface and its methods comes “Loan” Interface.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfb7207705b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Casting in Java]]></title>
            <link>https://medium.com/@thishankahadugoda/type-casting-in-java-cb78f675239a?source=rss-45402ccc85a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb78f675239a</guid>
            <category><![CDATA[type-narrowing]]></category>
            <category><![CDATA[casting]]></category>
            <category><![CDATA[type-casting]]></category>
            <dc:creator><![CDATA[Thishankahadugoda]]></dc:creator>
            <pubDate>Tue, 05 Oct 2021 19:17:30 GMT</pubDate>
            <atom:updated>2021-10-05T19:17:30.827Z</atom:updated>
            <content:encoded><![CDATA[<p>In java, Type Casting is a method or process that convert a data type into another data type in both ways manually and automatically. The automatic conversion is done by the compiler and manual conversion done by the programmer.In java, we can cast both reference and primitive data types. By using casting, data can not be change but only the data type is changed.(type casting is not possible for a Boolean data type.</p><p>There are main<strong><em> Two types</em></strong> of Casting in java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*ybW-BCN6sHWTkx_XsNG2gw.jpeg" /></figure><p>1.Widening Type Casting</p><p>2.Narrowing Type Casting</p><p><strong><em>Widening Type Casting</em></strong></p><p>Converting a lower data type into a higher one is called Widening type casting.its also known as implicit conversion or casting down.it happens automatically when a converting from a narrower range data type to a wider range data type(converting a lower data type like an int to a higher data type like a double).widening casting have <strong><em>two conditions</em></strong>,</p><p>1. Compatibility to the data types. For example data types such as numeric are compatible with numeric data types, but they are not compatible with boolean, char or string data types.in the same way String is not compatible with a boolean data types.</p><p>2.if the target type must be larger than the source type. (Ex: 4 bytes to a larger data type 8 bytes)</p><p>Widening casting follow the order of convention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*06Yf6s_KsyXbaA29zHp7Mw.jpeg" /></figure><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*L3B5y-N8cocmNvoUkgr4MQ.jpeg" /></figure><p><strong>Output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*PBzchgtq6irHKZpW-mQbyw.jpeg" /></figure><p><strong><em>Narrowing Type Casting</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*b6lCZRTI5i0omhzrAVWVOw.jpeg" /></figure><p>Converting a higher data type into a lower one is called Narrowing Type casting.its also known as explicit conversion or casting up.this is done manually by the programmer and need to do the casting using the “()” operator.if do not perform casting then the compiler reports compile-time error.</p><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*aM8BUUZbYvu0ZqiWN2P52A.jpeg" /></figure><p>In the above code, we converted the double data type into int data type and the decimal part of the value is lost after the type casting.</p><p><strong><em>byte casting(Additional to refer)</em></strong></p><p>Here we add two byte value and result will assign into another byte variable but compiler will indicates the error for following code. if we used “+” operator minimum in int type. Therefore if we used operator that will return integer type so we need to casting for the get proper result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*vw687pq4y5YeJUUHcpPD_g.jpeg" /><figcaption>without type casting</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*MHr6AjyWr7f1SFCtwJ4lTQ.jpeg" /></figure><p>In numbering system in circular progression which mean in byte highest value is 127 and lowest value is -128 (byte range -128 to 127). if you imagine numbers are in circle after 127 next value is -128, for example assign 129 to byte variable, compiler knows that exceed the limit and then counting start from -128 and goes two digit two get the answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EcwljHnmPrqrObrcRe3Rxg.jpeg" /></figure><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*Qik7vZz3nFK0IS1wEViu_Q.jpeg" /></figure><p>here the byte “c” variable get 130 and its exceeded byte range therefore it starts counting from -128 and answer is -126.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb78f675239a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BigDecimal]]></title>
            <link>https://medium.com/@thishankahadugoda/bigdecimal-6a90e8c069ec?source=rss-45402ccc85a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a90e8c069ec</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[floating-points]]></category>
            <category><![CDATA[bigdecimal]]></category>
            <dc:creator><![CDATA[Thishankahadugoda]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 19:29:35 GMT</pubDate>
            <atom:updated>2021-10-05T10:49:05.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*zaGzjvPFapQ7ldJ8mDCAEg.png" /></figure><p><strong>BigDecimal </strong>is a class that belongs to<strong><em> java.math</em></strong> package. We use float and double primitive data types for decimal numbers but there is one problem with these primitive types. Float and double that these types should never be used for <strong><em>precise value</em></strong>, such as currency.</p><p>The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing and format conversion. In addition to class gives its user complete control over rounding behaviour.</p><p>In java, BigDecimal consist of a random precision integer scale and a 32 bit integer scale.If positive or zero, the scale is number of digits to the right of the decimal point. If less than zeroth unscaled value of the number is multiplied by ten to the power of the negation of the scale.</p><p>Here the main reason why used the BigDecimal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*dfjMWfnlseVS7Nht5UiU-Q.jpeg" /></figure><p>In this case, we used firstly double primitive data type to subtract two numbers and we got answer with additional decimal point numbers. Second we used BigDecimal class type object to assign the values and we got exactly answer.</p><h3><strong>Features of BigDecimal</strong></h3><ol><li><strong><em>Scaling and Rounding modes</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*Dyhv4iBa0VUYpZY4oPsLBA.jpeg" /></figure><p>One of the biggest reason to used BigDecimal is scale the numbers.scaling is how many numbers there after decimal point(Number of digit after decimal point). In BigDecimal class have overloaded method called “setScale()” and we can used that method to scaling the values. setScale() method have two parameters and first one is int value o how many numbers are scaling and second parameter is rounding. In rounding mode there are 8 types are established.</p><p><strong><em>2. No overloaded operators is allowed</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*zms6JKFBXJIGS2uoml6ULg.jpeg" /></figure><p>In java arithmetic operators like +,-,*,/ not permitted with objects. So these operators are not allowed in BigDecimal. Therefore BigDecimal class provided methods such as add(), subtract(), multiply(), and divide() in addition to class is provided max(), min() and compareTo() method too.</p><p><strong><em>3. Use compareTo() to compare BigDecimal numbers, Not used equals()</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*mCvjbrUJUc7UfkZRQTbNRQ.jpeg" /></figure><p>Don’t used equal() method to compare two BigDecimal numbers. Only equal method is true both value and scale of two BigDecimal Numbers.</p><p>If two numbers are equal compareTo method will return<strong><em> 0</em></strong> or if first number is greater than second number it will return <strong><em>1</em></strong> and second number greater than first number it will return<strong><em> -1</em></strong>.</p><p><strong><em>4. BigDecimal numbers are immutable</em></strong></p><p>We can create BigDecimal objects following ways</p><p>1. BigDecimal b1 = new BigDecimal(d)</p><p>2.BigDecimal b2 = BigDecimal.valueOf(d)</p><p>If you use new BigDecimal() However, then BigDecimal will try to represent the double value as accurately as possible.This will usually result in a lot more digits being stored than what you want.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a90e8c069ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How computer deal with Floating point numbers | Decimal to IEEE 754 Floating point Representation]]></title>
            <link>https://medium.com/@thishankahadugoda/how-computer-deal-with-floating-point-numbers-decimal-to-ieee-754-floating-point-representation-20d845436c9f?source=rss-45402ccc85a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/20d845436c9f</guid>
            <category><![CDATA[ieee-754-standard]]></category>
            <category><![CDATA[floating-points]]></category>
            <category><![CDATA[single-precision]]></category>
            <category><![CDATA[ieee754]]></category>
            <dc:creator><![CDATA[Thishankahadugoda]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 11:04:43 GMT</pubDate>
            <atom:updated>2021-10-05T09:16:51.273Z</atom:updated>
            <content:encoded><![CDATA[<p>There are some exception cases in programming languages, computer gives wrong answers to some mathematical formula. If you calculate some numbers computer give some unexpected answers. Therefore programmers faced some unexpected bugs and they try to solve these bugs takes a lot of times.</p><p>In computer, there is standard called IEEE 754, this is standard computer used to represent the floating points.</p><p>IEEE 754 has 3 basics components :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OifU8-R05ZRImyFL7RiJg.jpeg" /></figure><p><strong><em>1. Sign bite</em></strong></p><p>This is the simple as the name,1 bit is assigned for the sign and 0 represents a positive number and 1 represents a negative number.</p><p><strong><em>2.The Exponent</em></strong></p><p>The exponent field needs to represent both positive and negative exponents. A <strong><em>bias </em></strong>is added to the actual exponent in order to get the stored exponent. Single precision(32 bit) takes 8 bit is assigned for the range named exponent while Double precision(64 bit) takes 11 bit is assigned for the ranged named exponent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPXz1FTCDh7_a3bdTOMHTQ.jpeg" /></figure><p><strong><em>3.Mantissa -</em></strong></p><p>This is for the fractional part in other words mantissa is part of a number in scientific notation or floating point number, consisting of its significant digits.</p><p>IEEE 754 numbers are divided into <strong>three based on above three components </strong>such as Single precision , double precision and long double precision.</p><p>This is how generally IEEE 754 standards to guiding to represents floating points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Lv66SB84aVyQOPtaxEvR8w.jpeg" /></figure><p>Let takes example how this works.</p><p><em>Convert value 9.1 into IEEE standard 32 bit floating point binary</em></p><p><strong>Step 1 : Determine the sign bit ( 0 if positive, 1 if negative)</strong></p><p>Sign bit = 0</p><p><strong>Step 2 :convert decimal value to pure binary value( including fractional part)</strong></p><p>Common approach is repeatedly half in the whole number part and repeatedly doubling fractional part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*2c5BVELZD5ptZ1DtFIEXBw.jpeg" /></figure><p>in this above picture, as you noticed that value of 0.2 comes up again, in which case recurring bit pattern so there is no need to keep going and remember this fractional part read in top to bottom.</p><p><strong>Step 3</strong> : <strong>Normalise to determine the mantissa and the unbiased exponent( place the binary point after leftmost 1)</strong></p><p>In this case decimal point is reposition three places to the left to get point back where it was would have to float it three places to the right. So now we have the value of exponent. this is the Scientific notation in 9.1 is represented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*X-DTlwHGleL8JiSQpnwjHA.jpeg" /></figure><p><strong>Step 4: Determined the Biased exponent (add 127 then convert to an unsigned binary integer)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*vzeik8yk1icalF3b0Uk0gw.jpeg" /></figure><p><strong>Step 5 : remove the leading 1 from the mantissa ( remove the leftmost 1)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*m-HuTTgzWNYw4OxLKPzm_g.jpeg" /></figure><p>The mantissa is always going to be 1 for any real number that we want to represent in this format so there is no need to store it.</p><p>This is the final result of 9.1 value represent in IEEE 754 standard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*IWNz9ORcGDQq01gTOk9Dlg.jpeg" /></figure><p>But some cases we do additional steps to convert value to IEEE 754 standard format.</p><p><strong>Step 6 : Round mantissa up or down if necessary</strong></p><p>In mantissa includes a recurring bit sequence which mean it’s too long to be stored with a finite number of bits.therefore simply chop the mantissa at 23 bits to make it fit.simply chopping the mantissa is effectively rounding it down but in reality a computer will round to the mantissa either up or down to the nearest value.</p><p>If you want to round mantissa properly, first need to identify what is 24th bit and then if it’s 0, then we can simply chopped but if its 1 , then we need to add 1 to the mantissa</p><p>in this case, 24 bit is 1 and we need to add 1 to the mantissa to floating point rounding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*Vd-IfGdfhh3zPSB4gc2Y5A.jpeg" /></figure><p>the final result of the IEEE 754 standard is now little bit difference than above one. this is so called<em> </em><strong><em>floating point rounding</em></strong><em> </em><strong><em>error</em></strong> in computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*C3bchxNd2vaZjvB0ywnUTg.jpeg" /></figure><p>Now we convert this 9.1 IEEE 754 standard into decimal format</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*lWGVXjLri-hZ4H8QZJanrQ.jpeg" /></figure><p><strong>Step 1: Determine the sign in decimal</strong></p><p>Sign = +(positive) because starting bit is<strong> 0</strong></p><p><strong>Step 2: determine the exponent.</strong></p><p>Exponent part have 8 bit and it starts from second bit and goes up to 9th bit.</p><h3><strong>10000010 = 130</strong></h3><p><strong>Step 3 : remove the exponent bias</strong></p><p><strong>127 </strong>is the bias we add to the exponent part(in single precision).</p><h3><strong>130- 127 = 3</strong></h3><p><strong>Step 4 : convert mantissa to decimal</strong></p><p>We have 23 bit mantissa and to convert it into decimal it’s easy to use excel sheet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*_UF4SLmWGMVKeiUYl7ms6w.jpeg" /></figure><p>So exponent value is <strong>0.137500048</strong></p><p><strong>Step 5: add 1 to the mantissa include the sign bit</strong></p><h3>1.137500048</h3><p><strong>Step 6 : calculate the final result</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*WXfIHgKGWTQuiyvN8U6uFw.jpeg" /></figure><p>Now we realise that first we convert 9.1 into binary and that binary code we convert into back to floating point we got not 9.1 but rather than 9.100000384. this is happened because of rounding what we have done. This is floating pint rounding errors we faced in programming language. In java as a solution we used<strong> BigDecimal</strong> instead of Float and double values.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20d845436c9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why division by ZERO is NOT infinity?]]></title>
            <link>https://medium.com/@thishankahadugoda/why-division-by-zero-is-not-infinity-731e00d29594?source=rss-45402ccc85a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/731e00d29594</guid>
            <category><![CDATA[divide-by-zero-errors]]></category>
            <category><![CDATA[undefined]]></category>
            <category><![CDATA[divide-by-zero]]></category>
            <category><![CDATA[inifinity]]></category>
            <dc:creator><![CDATA[Thishankahadugoda]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 20:20:59 GMT</pubDate>
            <atom:updated>2021-09-28T20:20:59.202Z</atom:updated>
            <content:encoded><![CDATA[<p>In Maths we consider division by zero as infinity. Why computer do not take division by zero as an infinity ?</p><p>If computer wants to 10/2, how computer do this is computer subtract 10 by 2 until it hit the zero or go beyond the zero.</p><p>It takes five times and results is 10/2 is 5. That how the computer do the division. Same way if computer wants multiplication, it do the additions.</p><p>Now the problem is?</p><p>10/2 =5 15/3 = 5 but same way working other way round so 5*2 =10, 5*3 =15 that’s how this works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3GBG4ycWzhVuc1oh8mMTA.jpeg" /></figure><p>If we says 1/0 = infinity and same way we can say 2/0= infinity</p><p>If you apply the same logic other way round infinity *0 =1 and infinity * 0 =2 .. but this is not possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*SxS9WfKV8QX7wdEYCtqQXw.jpeg" /></figure><p>Therefore we do not consider any number divide by<strong> zero as infinity.</strong></p><p>Here is answer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*QGBGn8Iw2F4k8l-dkyjTTQ.jpeg" /></figure><p>When we trying to reach zero , 0.1,0.01,0.001 as we go towards to zero, the result will go upwards. Same way reach to zero by negative side the results should go downwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ODrZwsIznXr6afkjaPJPXw.jpeg" /></figure><p>These two are never going to meet each other because these two go in two different ways. As results we consider as any number divide by Zero is <strong>Undefinable(Undefined</strong>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=731e00d29594" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JVM, JRE & JDK]]></title>
            <link>https://medium.com/@thishankahadugoda/jvm-jre-jdk-d060567438d8?source=rss-45402ccc85a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d060567438d8</guid>
            <category><![CDATA[jvm-architecture]]></category>
            <category><![CDATA[jdk]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <category><![CDATA[jre]]></category>
            <dc:creator><![CDATA[Thishankahadugoda]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 17:57:54 GMT</pubDate>
            <atom:updated>2021-10-05T07:29:33.622Z</atom:updated>
            <content:encoded><![CDATA[<p>Virtual means not is the reality. So virtual machine is the machine but is not real, in other words visualisation of a computer system. Virtual machine can be divided into two parts such as System based virtual machine and Application based virtual machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CD24rpgFUUmtuuVLzPjaIA.jpeg" /><figcaption>two types of virtual machines</figcaption></figure><p><strong>System based Virtual machine (SVM)</strong></p><p>System based virtual machine is one or multiple hardware creates multiple environments to work. These environments are completely independent.</p><p>Example: Xen, Hypervisor</p><p><strong>Application based Virtual machine(AVM)</strong></p><p>Application based virtual machine is don’t have any hardware device to involve, but may have application or software which helps to create environment/platform to run some kind of language and it convert to different language(output) to understand. This types of vm also called as process based virtual machine.</p><p>Examples: JVM, CLR(common language runtime- dot.net programme to creates virtual environments), PVM</p><blockquote><strong>High-level view of JDK,JRE &amp; JVM</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*YZmbhgkYMaId-rvBI8CmPw.jpeg" /></figure><p><strong>Java Virtual Machine(JVM)</strong></p><p>JVM is completely specifications and it says how this should be done.JVM is application based Virtual machine. We cannot installed JVM because its doest not exits.when download the JRE, JVM comes with JRE.when install JRE, JRE will deploy the all codes which can create JVM for particular platform. For example JRE on a windows machine the JRE will deploy the all codes which required to create JVM for windows environments. Therefore JVM is platform dependent.</p><p>How JVM works is read the class file and convert it to which your operating system is understand.</p><p>The moments start the java program, then creates JVM instance on computer. The moment when program exists then JVM will die.Therefore JVM only exist computer until run the program. If you are executing three different program on your computer, on the same time three JVM instance have created.</p><p><strong><em>JVM Architecture</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTIdnpIbZM6c65jzQVB1cg.jpeg" /><figcaption>Main components in JVM</figcaption></figure><p>In JVM architecture there are three main components inside the JVM such as ClassLoader, memory area and executing engine.</p><h3><strong>ClassLoader</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWNg49z3IsxvjrtbheV0RA.jpeg" /><figcaption>Three characteristics of ClassLoader</figcaption></figure><p>The classLoader main responsibility is taking the class and loading into memory area. classLoader mainly have three characteristics such as loading, linking and initialisation. There are two types of classLoader in JVM,</p><p>1. Boostrap classLoader</p><p>2. Custom define classLoader</p><h3><strong><em>Loading</em></strong></h3><p>The main responsibility of loading is taking class file and put into memory.When JVM reading class file, class files has following features such as,</p><p>1.Fully qualified class names</p><p>2.Variables information</p><p>3.Immediate parent information</p><p>4.Whether class file is class or interface or enums</p><p>Fulfils the these conditions then class file is loaded to Memory Area.Each and every class when is loaded, JVM does creates object from class type and put it into heap.</p><p>Example:</p><p>We have two class called Employee and Manager.</p><p><strong><em>Employee em = new Employee();</em></strong></p><p>“em” is the object in employee class and when JVM is load Employee class, it creates object from class type and assign class information to that “<strong>em</strong>” variable and storing into heap. This is happen very first time loading into JVM.</p><p>So Manager class referring to Employee class JVM not created additional object from class type because it’s already created. Therefore only very first time JVM created objects from its class type.</p><h3><strong>Linking</strong></h3><p>Linking have three steps,</p><p>1.Verification</p><p>2.Preparation</p><p>3.Resolution</p><p><strong><em>Verification</em></strong></p><p>In java has byte code verifier in JVM, It will check whether the particular class will safely execute or not. Therefore the reason why Java is safely execute any environments.</p><p>How it works?</p><p>When loading Java class, there is sub program called byte code verifier. It will verify whether that particular class come from valid compiler, the class has correct structure and that class has correct formatting.if any of these conditions are not satisfied, JVM throw runtime exception called Verifier Exception.</p><p><strong><em>Preparation</em></strong></p><p>Preparation means if you are using any instance level variable or static variable in your class, preparation part will assign default value for that variables. But not assign to initial values.</p><p><strong><em>Resolution</em></strong></p><p>JVM, cannot understand the codes that we write when we are developing the application, so JVM does before reach to machine level JVM replacing those symbolic links with direct links.</p><h3><strong>Initialisation</strong></h3><p>Initialisation means assign real value to variables. In initialisation part, there is rule that every class must initialise before its active use.</p><p>What are the <strong>active use of class</strong>?</p><p>1. <strong>new</strong> Keyword- if you use new keyword, this is consider as active class.</p><p>2.class has particular <strong>static method</strong>- without creating an object invokes the static method.</p><p>Example: Employee class have particular static method called verifier employee so we can use manager class to verifier method without creating object. Employee.verifier();</p><p>3.assign <strong>values to static field</strong>. Ex: Employee.code = “k”;</p><p>4. <strong>Main method</strong>- if class is initial and has main method then this class consider as active class.</p><p>5.<strong>getInstance</strong>(Reflection) -if you use reflection method to load the class(getInstance type) this is consider as active class.</p><p>6.<strong>instance subclass</strong>-</p><p>Example: if you used manager class which exchange from employee, you are not creating object from employee, but you are creating object from manager that case it will create object from employee class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hNa2PQjPlvp_LwAD5QNFkQ.jpeg" /></figure><p><strong>Initialising process</strong></p><p>There are four ways to java can initialise its class.</p><p>1. new Keyword</p><p>2.clone method</p><p>3. Reflection API — getInstance()</p><p>4.Java.IO.ObjectInputStream- with this class we can create new object.</p><p><strong>Default constructor</strong></p><p>If class has no constructor compiler will create no argument constructor called as default constructor.</p><p>If you create two class with same name(identical name) JVM will load only <strong>one class</strong>. Because always class loader take unique class name.</p><p>So these cases JVM will take first class-path as to class to load (priority is what comes first).</p><p>But completely different when we give JVM parameters JVM arguments to execute- that case JVM will take <strong>last one</strong>.</p><p>Conclusion- if its a class-path it take the first one and it its an arguments it take last one.</p><h3><strong>Memory Area</strong></h3><p>When loading the classes. All classes are storing into memory area. Mainly memory area divided into five components such as Method area, Heap area, stack, PC register and native method area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoMJoccr8bd7kdjWMP9u2w.jpeg" /></figure><p>For each and every JVM, only have one method area and heap area but stack, PC register and native method area are created<strong> per thread.</strong></p><p><strong>Method area </strong>— class files are loaded to method area.</p><p><strong>Heap area </strong>— Hold the objects(all the objects are storing here)</p><p><strong>Stack</strong>- Keep the method information(local variables).</p><p><strong>PC register</strong> — hold the information for next execution but not native methods</p><p><strong>Native method area</strong>- provide facility to hold native methods</p><p><strong><em>Data types in JVM</em></strong></p><p>There are two types of data types in JVM.</p><p>1. <strong>Primitive types</strong> — holds the value of data</p><p>2.<strong>Reference types</strong>- holding the references not holding values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IKP9KvC3vF5UU1QwH2MbQ.jpeg" /></figure><p><strong><em>Word Size</em></strong></p><p>Word-Size is a just a based we need to assign value into the word-size to explain that we cannot measure word-size.The length of the word size is decided by the particular platform and there are two rules to define the length of word-size.</p><p>1. Particular word should be able to hold any primitive datatypes.</p><p>2.two of words should be carry long value.</p><p>Therefore , the word size should be at least 32 bits.</p><h3><strong>Java Runtime Environment (JRE)</strong></h3><p>JRE is an implementation and it says how is does in particular environments. JRE is platform-dependent, because JRE is on windows machine is totally different in JRE in macOS machine. JRE provide the class libraries and other resources that a specific java program needs to run.</p><p><strong><em>JRE consist of ?</em></strong></p><p>JRE is composed a variety of supporting software tools and features. such as</p><ol><li><strong><em>Deployment solutions</em></strong></li></ol><p>included as a component of the JRE installation are deployment technologies like java web start and java plugin that improve on the activation of application and offer advanced support for future java updates.</p><p><strong>2.Developement toolkits</strong></p><p>The JRE also contains toolkit to designed to help developers to further developing their UI.</p><p><strong>3.Language and Utility libraries</strong></p><p>consist with the JRE are java.lang and java.util packages that are fundamental for the design of java applications.</p><p>example: collections Framework, Concurrency utilities</p><h3><strong>Java Development Kit (JDK)</strong></h3><p>The Java Development Kit is a software development environment used for developing java applications and applets.The JDK includes tools for developing and testing programs written in the java programming language and running on the Java platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d060567438d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>