<?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 Kalpa Sandaruwan on Medium]]></title>
        <description><![CDATA[Stories by Kalpa Sandaruwan on Medium]]></description>
        <link>https://medium.com/@kalpa752mohotti?source=rss-4c466850c72a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-80nWnXuKK1Cxw3-</url>
            <title>Stories by Kalpa Sandaruwan on Medium</title>
            <link>https://medium.com/@kalpa752mohotti?source=rss-4c466850c72a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:39:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kalpa752mohotti/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[Head First Java (Chapter 18)Distributed Computing]]></title>
            <link>https://medium.com/@kalpa752mohotti/head-first-java-chapter-18-distributed-computing-54531d18e47c?source=rss-4c466850c72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/54531d18e47c</guid>
            <category><![CDATA[servlet]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[chapter-18]]></category>
            <category><![CDATA[mir]]></category>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Kalpa Sandaruwan]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 17:20:46 GMT</pubDate>
            <atom:updated>2022-07-18T17:20:46.429Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, Today I am going to explain the important points of Head First Java chapter 18. I am mainly focusing on remote deployment with RMI.</p><p>Think about how we get an object on one machine to call a method on another machine? We can’t do it directly. But when we use RMI we can do it.</p><h4>What is RMI?</h4><p>RMI means remort method invocation. It is an API. it provides a mechanism to create distributed applications in java. This RMI allows an object to invoke methods on an object running in another JVM.</p><p>When we are going to design a remote method call we need four things. Those are Server, Client, Server helper, and Client helper. Let’s see how to create these things.</p><p>1. Create client and server apps. The server app is the remote service that has an object with the method that the client wants to invoke.</p><p>2. Create client and server ‘helpers’. They’ll handle all the low-level networking and I/O details so your client and service can pretend like they’re in the same heap.</p><h4>The role of the ‘helpers’</h4><p>The helper responsible is doing the communication. These helpers make it possible for the client to act as though it’s calling a method on a local object. The client helper doesn’t have any client-expecting logic. The client helper contacts the server transfers information about the method call and waits for a return from the server.<br>The server helper receives the request from the client helper and unpacks the information about the call, and then invokes the real method on the real service object.</p><p>In RMI, the client helper is a ‘stub’ and the server helper is a ‘skeleton’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*hI2BFWwiKwOvS5S2UhPZuA.png" /></figure><h4>How the method call happens</h4><p>The client object calls doBigThing() on the client helper object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*sAYybujdKRThMYcEhilacw.png" /></figure><p>The client helper packages up information about the call and ships it over the network to the service helper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*jvcGmKsC5TrkmmiMuxeHPg.png" /></figure><p>The service helper unpacks the information from the client helper, finds out which method to call (and on which object) and invokes the real method on the real service object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*ywjZQ5fVbpy7iMus4ODvrg.png" /></figure><h4>Making the Remote Service.</h4><p>These are the steps for making a remote service.</p><p><strong>Make a Remote Interface.</strong><br>This remote interface defines the methods that a client can call remotely. Both the Stub and actual service will implement this.<br> We can do this using the following steps.<br> 1. Extend java.rmi.Remote<br> 2. Declare that all methods throw a RemoteException.<br> 3. Be sure arguments and return values are primitives or <br> Serializable.</p><p><strong>Make a Remote Implementation.</strong><br>This class does the real work. It has the real implementation of the remote methods defined in the remote interface. It’s the object that the client wants to call methods on.<br> We can do it using the following steps.<br> 1. Implement the Remote interface<br> 2. Extend UnicastRemoteObject.<br> 3. Write a no-arg constructor that declares a RemoteException<br> 4. Register the service with the RMI registry.</p><p><strong>Generate the stubs and skeletons using rmic.</strong><br>These are the client and server helpers. You don’t have to create these classes or ever look at the source code that generates them.</p><p><strong>Start the RMI registry </strong><br>Bring up a terminal and start the rmiregistry. The simplest way is to start it from your ‘classes’ directory.</p><p><strong>Start the remote service</strong><br>Bring up another terminal and start your service. This might be from a main() method in your remote implementation class, or from a separate launcher class.</p><p><strong>Code- Remote interface</strong></p><pre>import java.rmi.*; <br>public interface MyRemote extends Remote {<br>  public String sayHello() throws RemoteException; <br>}</pre><p><strong>Code- Remote Service</strong></p><pre>import java.rmi.*; <br>import java.rmi.server.*; <br>public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {</pre><pre>public String sayHello() {<br>  return “Server says, ‘Hey’”;  <br>}</pre><pre>public MyRemoteImpl() throws RemoteException { }</pre><pre>public static void main (String[] args) {<br>  try {<br>      MyRemote service = new MyRemoteImpl();  <br>      Naming.rebind(“Remote Hello”, service);<br>      } catch(Exception ex) {<br>          ex.printStackTrace();  <br>      }  <br>   }<br> }</pre><h4>How does the client get the stub object?</h4><p>The client is responsible for taking the stub object. since that’s the thing the client will call methods on. And that’s where the RMI registry comes in. , in the process of deserializing an object, if RMI can’t find the class locally, it uses that URL to do an HTTP Get to retrieve the class file.</p><p><strong>Complete client code-</strong></p><pre>import java.rmi.*;<br> public class MyRemoteClient {<br>     public static void main (String[] args) {<br>     new MyRemoteClient().go();<br>  }</pre><pre>  public void go() {<br>      try {<br>           MyRemote service = (MyRemote)       Naming.lookup(“rmi://127.0.0.1/Remote Hello”);<br>           String s = service.sayHello();<br>           System.out.println(s);<br>          } catch(Exception ex) {<br>              ex.printStackTrace();<br>          }  <br>  } <br>}</pre><h4>Servlets</h4><p>Java Servlets are programs that are run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server. Using servlets we can collect input from users through web page forms, present records forms a database or another source, and create dynamic web pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*ofCtG7LMyNW3ztCj9KXe-w.png" /><figcaption>Servlets Architecture</figcaption></figure><p>When executing the servlets it involves six basic steps. <br><strong>1.</strong> The clients send the request to the webserver.<br><strong>2. </strong>The web server receives the request.<br><strong>3. </strong>The web server passes the request to the corresponding servlet.<br><strong>4.</strong> The servlet processes the request and generates the response in the form of output.<br><strong>5.</strong> The servlet sends the response back to the webserver.<br><strong>6.</strong> The web server sends the response back to the client and the client browser displays it on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*HUpch99L7T6hEnEXYIXxsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*RTQpT_4kKfMNBqkwyNW0GA.png" /></figure><p><strong>Code example-</strong></p><pre>import java.io.*;<br>import javax.servlet.*;<br>import javax.servlet.http.*;</pre><pre>public class MyServletA extends HttpServlet {</pre><pre>public void doGet(HttpServletRequest request, HttpServletResponse response)<br>            throws ServletException, IOException {</pre><pre>response.setContentType(“text / html<br>        ”);<br> PrintWriter out = response.getWriter();<br>        String message = “If you<br>        ’re reading this<br>        , it worked<br>        !”;<br> out.println(“&lt;HTML &gt; &lt;BODY&gt;<br>        ”);<br>out.println(“&lt;H1 &gt;” + message + “&lt;/H1 &gt;<br>        ”);<br>out.println(“&lt;/BODY &gt; &lt; / HTML &gt;<br>        ”); <br>out.close();<br>    }<br>}</pre><p>HTML page</p><pre>&lt;HTML&gt;<br>  &lt;BODY&gt;<br>    &lt;a href=”servlets/MyServletA”&gt;This is an amazing servlet.&lt;/a&gt;<br>  &lt;/BODY&gt;<br>&lt;/HTML&gt;</pre><h3>References</h3><p>[1]Sierra, Kathy, and Bert Bates. “Head First Java™ Second Edition.” (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54531d18e47c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java (Chapter 17) Release Your Code]]></title>
            <link>https://medium.com/@kalpa752mohotti/head-first-java-chapter-17-release-your-code-7b794dee60c6?source=rss-4c466850c72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b794dee60c6</guid>
            <category><![CDATA[jar]]></category>
            <category><![CDATA[java-package]]></category>
            <category><![CDATA[chapter-17]]></category>
            <category><![CDATA[release-your-code]]></category>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Kalpa Sandaruwan]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 17:18:40 GMT</pubDate>
            <atom:updated>2022-07-18T17:18:40.866Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, Today I am going to explain the important points of Head First Java chapter 17. I am mainly focusing on package, jars and deployment.</p><h4>Deploying your application</h4><p>After our development process, how can we deliver our end product to the end user? In this chapter, we’ll look at local deployments, including Executable Jars and the part-local/part-remote technology called Java Web Start. We have three development options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*kIGal9kigke5hvvSHrrCag.png" /></figure><p><strong>Local-</strong><br>The entire application runs on the end-user’s computer, as a stand-alone, probably GUI, program, deployed as an executable JAR.</p><p><strong>Combination of local and remote-</strong><br>This type of application are distributed with a client portion running on the user’s local system, connected to a server where other parts of<br>the application is running.</p><p><strong>Remote-</strong><br>This type of application is run on the server. e entire Java application runs on a server system, with the client accessing the system through some non-Java means, probably a web browser.</p><h4>Separate source code and class files</h4><p>I will explain it using a little example. When we create a project directory, inside that directory we create another two directories called classes and source. I tried to save my source code inside the source directory. As a next step, I compiled that project. after that, we can see (.class files) class files are created inside the classes directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*kPq59_kCOjVCB5Fz-wjj-Q.png" /></figure><h4>What is JAR ?</h4><p>A JAR is a package file format. It is typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file to distribute application software or libraries on the Java platform. In other words, the JAR file contains a compressed version of .class files, audio files, image files, or directories.</p><h4>How to make an executable JAR?</h4><ol><li><strong>Make sure all of your class files are in the classes directory.</strong></li></ol><p><strong>2. Create a manifest.txt file that states which class has the main() method.</strong><br> Make a text file named manifest.txt that has one line:</p><pre> Main-Class: MyApp</pre><p>Press the return key after typing the MainClass line, or your manifest may not work correctly. Put the manifest file into the “classes” directory.</p><p><strong>3. Run the jar tool to create a JAR file that contains everything in the classes directory, plus the manifest.</strong></p><h4>Running (executing) the JAR</h4><p>JVM is capable of loading a class from a JAR, calling the main method of the class. In fact, the entire application can stay in the JAR. Once the ball is rolling (i.e., the main() method starts running), the JVM doesn’t care where your classes come from, as long as it can find them. And one of the places the JVM looks is within any JAR files in the classpath. If it can see a JAR, the JVM will look in that JAR when it needs to find and load a class.<br>When we use the operating system we can just only double click the JAR file and launch the program.</p><h4>Java Packages</h4><p>These packages are used to group related classes. We use packages for the main two reasons. we use packages to avoid name conflicts and write better maintainable code. <br>Packages are divided into two categories:</p><p><strong>Built-in Packages (packages from the Java API).<br>User-defined Packages (create your own packages).</strong></p><h4>How to make executable JAR with packages.</h4><p>When we create classes in the packages, the package directory structure must be inside the JAR. You can’t just pop your classes in the JAR the way we did pre-packages. And you must be sure that you don’t include any other directories above your package.</p><p><strong>Making an executable JAR</strong><br>There are three steps.<br>1. Make sure all of your class files are within the correct package structure, under the classes directory.<br>2. Create a manifest.txt file that states which class has the main() method, and be sure to use the fully-qualified class name.<br>3. Run the jar tool to create a JAR file that contains the package directories plus the manifest.</p><h4>Java Web Start</h4><p>How does it work?<br>1. The client clicks on a Web page link to your JWS application (a .jnlp file).<br>2. The Web server (HTTP) gets the request and sends back a .jnlp file (this is NOT the JAR).<br>3. Java Web Start (a small ‘helper app’ on the client) is started up by the browser. The JWS helper app reads the .jnlp file, and asks the server for the MyApp.jar file.<br>4. The Web server ‘serves’ up the requested .jar file.<br>5. Java Web Start gets the JAR and starts the application by calling the specified main( ) method.</p><h4>Steps for making and deploying a Java Web Start app.</h4><p>1. Make an executable JAR for your application.<br>2. Write a .jnlp file.<br>3. Place your JAR and .jnlp files on your Web server.<br>4. Add a new mime type to your Web server.</p><pre>application/x-java-jnlp-file</pre><p>5. Create a Web page with a link to your .jnlp file.</p><pre>&lt;HTML&gt;<br>   &lt;BODY&gt; <br>       &lt;a href=”MyApp2.jnlp”&gt;Launch My Application&lt;/a&gt; <br>   &lt;/BODY&gt;<br>&lt;/HTML&gt;</pre><h4>Important points in the chapter</h4><p>Java Web Start technology lets you deploy a stand-alone client application from the Web.</p><p>Java Web Start includes a ‘helper app’ that must be installed on the client (along with Java).</p><p>A Java Web Start (JWS) app has two pieces: an executable JAR and a .jnlp file. A .jnlp file is a simple XML document that describes your JWS application. It includes tags for specifying the name and location of the JAR, and the name of the class with the main() method.</p><p>When a browser gets a .jnlp file from the server (because the user clicked on a link to the .jnlp file), the browser starts up the JWS helper app.</p><p>The JWS helper app reads the .jnlp file and requests the executable JAR from the Web server.</p><p>When the JWS gets the JAR, it invokes the main() method (specified in the .jnlp file).</p><h3>References</h3><p>[1]Sierra, Kathy, and Bert Bates. “Head First Java™ Second Edition.” (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b794dee60c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java (Chapter 16) Data structures]]></title>
            <link>https://medium.com/@kalpa752mohotti/head-first-java-chapter-16-data-structures-a2a7b64ebb66?source=rss-4c466850c72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2a7b64ebb66</guid>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[collection-interface]]></category>
            <category><![CDATA[collections-framework]]></category>
            <category><![CDATA[chapter-16]]></category>
            <dc:creator><![CDATA[Kalpa Sandaruwan]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 17:16:46 GMT</pubDate>
            <atom:updated>2022-07-18T17:16:46.867Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, Today I am going to explain the important points of Head First Java chapter 16. I am mainly focusing on collections and generics.</p><p>As Java Software engineers we need to know what is collection framework, what is data structures, and what is generics. A collection framework is a framework it offers an architecture for holding and managing a collection of items. All data operations, including searching, sorting, insertion, modification, and deletion, may be carried out via Java Collections.<br>Most of the time we use ArrayList for our jobs. but ArrayList is not the only collection. There are many collection classes included.</p><p><strong>TreeSet</strong><br>Keeps the elements sorted and prevents duplicates. <br><strong>HashMap</strong><br>Lets you store and access elements as name/value pairs.<br><strong>LinkedList</strong><br>Makes it easy to create structures like stacks or queues.<br><strong>HashSet</strong><br>Prevents duplicates in the collection, and given an element, can <br>find that element in the collection quickly.<br><strong>LinkedHashMap</strong><br>Like a regular HashMap, except it can remember the order in <br>which elements (name/value pairs) were inserted, or it can be <br>configured to remember the order in which elements were last <br>accessed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*wUi35QYyrKrEggsRcljN3w.png" /><figcaption>Java Collection Framework Architecture</figcaption></figure><h4>Collections.sort()</h4><p>This method represents in java.utill.Collections class. This method is used to sort the elements present in the specified list of Collections in ascending order. As an example, I create an ArrayList and sort it using collections.sort().</p><pre>import java.util.*;<br>  <br>public class Collectionsorting<br>{<br>    public static void main(String[] args)<br>    {<br>      <br>        ArrayList&lt;String&gt; al = new ArrayList&lt;String&gt;();<br>        al.add(&quot;Geeks For Geeks&quot;);<br>        al.add(&quot;Friends&quot;);<br>        al.add(&quot;Dear&quot;);<br>        al.add(&quot;Is&quot;);<br>        al.add(&quot;Superb&quot;);<br>  <br>       <br>        Collections.sort(al);<br>  <br>       <br>        System.out.println(&quot;List after the use of&quot; +<br>                           &quot; Collection.sort() :\n&quot; + al);<br>    }<br>}</pre><p>Output-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*hiHamV6iZrMQBYN-fG31dw.png" /></figure><h4>Generics</h4><p>It means more type safety. The main responsible of generic is it lets us write type-safe collections. In other words, code that makes the compiler stop you from putting a Dog into a list of Ducks. <br>Let’s see what happens when we create Array List without generics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*02KfOXdKE3h0-sUy1Rq3hg.png" /></figure><p>Let’s see what happens when we create Array List with generics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*_cFuokmIj-eA--EHGrZpMw.png" /></figure><p>When we learn generics, there are really only three that matter to most programmers:<br><strong>Creating instances of generified classes (like ArrayList)</strong><br>When you make an ArrayList, you have to tell it the type of objects you’ll allow in the list</p><pre>new ArrayList&lt;Song&gt;()</pre><p><strong>Declaring and assigning variables of generic types</strong></p><pre>List&lt;Song&gt; songList =new ArrayList&lt;Song&gt;();</pre><p><strong>Declaring (and invoking) methods that take generic types.</strong></p><pre>void foo(List&lt;Song&gt; list)<br>x.foo(songList)</pre><h4>Generic Classes</h4><p>A generic class means that the class declaration includes a type parameter. There are two key areas to look at in a generified class are:<br>1) The class declaration.<br>2) The method declarations that let you add elements.</p><h4>Generic Methods</h4><p>A generic method means that the method declaration uses a type parameter in its signature. You can use type parameters in a method in several different ways:<br><strong>Using a type parameter defined in the class declaration.<br>Using a type parameter that was NOT defined in the class declaration.</strong></p><h4>We need a Set instead of a List.</h4><p>In collection API we know there are three interfaces. LIst, Set, and Map are interfaces. <br><strong>List-</strong><br>when sequence matters. The Collections that know about index position. Here duplicate values are ok.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*BLs_7e0LgDcwHzZyb9KpxQ.png" /></figure><p><strong>Set-</strong><br>when uniqueness matters, Collections that do not allow duplicates. You can never have more than one element referencing the same object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*XbQC6HUz-HCTJHAhPvVbTQ.png" /></figure><p><strong>Map-</strong><br>when finding something by key matters, This uses key, and value pairs. Here duplicate values are ok but we can not add duplicate keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*NBcRF-GOeKNR-otoxGdUEw.png" /></figure><h4>Collection API</h4><p>The map interface doesn’t actually extend the collection interface. But map is still part of the collections framework. Maps are still collections, even though they don’t include java.util.Collection in their inheritance tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*ahtnBPWd7yTTqaH-T7Mz0g.png" /></figure><h4>Wildcards to the rescue</h4><p>It looks unusual, As the following example, but there is a way to create a method argument that can accept an ArrayList of any Animal subtype.</p><pre>public void takeAnimals(ArrayList&lt;? extends Animal&gt; animals) {<br>        for (Animal a : animals) {<br>            a.eat();<br>        }<br>    }</pre><h3>References</h3><p>[1]Sierra, Kathy, and Bert Bates. “Head First Java™ Second Edition.” (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2a7b64ebb66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java (Chapter 15) Make a Connection]]></title>
            <link>https://medium.com/@kalpa752mohotti/head-first-java-chapter-15-make-a-connection-4b0d7ad349ef?source=rss-4c466850c72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b0d7ad349ef</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[chapter-15]]></category>
            <category><![CDATA[sockets]]></category>
            <category><![CDATA[thread-scheduling]]></category>
            <dc:creator><![CDATA[Kalpa Sandaruwan]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 14:34:47 GMT</pubDate>
            <atom:updated>2022-07-18T14:34:47.044Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, Today I am going to explain the important points of Head First Java chapter 15. I am mainly focusing on networking and threads.</p><p>If we need to make a connection between two machines, we need to use a Socket connection.</p><p>The three things we have to learn to get the client working are :<br>1) How to establish the initial connection between the client and server<br>2) How to send messages to the server<br>3) How to receive messages from the server</p><p>To make a socket connection we need to know two things about the server. There are who it is and which port number it is used. In other words, IP address and TCP port number.</p><pre>Socket chatSocket = new Socket(“196.164.1.103”, 5000);</pre><p>Look at the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*IYOervju2MRZe4--ovP7QQ.png" /></figure><p>Without any port number, the server can’t find which application a client wanted to connect to. Because each application might have its own unique protocol.</p><h4>How to read data from the socket.</h4><p>To communicate between Socket connections, we use streams. We can read data using BuffereredReader. Let’s see how we can do it.</p><p>Make a Socket connection to the server</p><pre>Socket chatSocket = new Socket(“127.0.0.1”, 5000);</pre><p>Make an InputStreamReader chained to the Socket’s low-level (connection) input stream.</p><pre>InputStreamReader stream = new InputStreamReader(chatSocket.getInputStream());</pre><p>Make a BufferedReader and read</p><pre>BufferedReader reader = new BufferedReader(stream); <br>String message = reader.readLine();</pre><p>The following diagram represents how it happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*HjwPJrbc4tt1JdSG_BIQiQ.png" /></figure><h4>How to write data to the socket.</h4><p>We can use printWriter to write data for sockets. Let’s see how we can do it.</p><p>Make a Socket connection to the server</p><pre>Socket chatSocket = new Socket(“127.0.0.1”, 5000);</pre><p>Make a PrintWriter chained to the Socket’s low-level (connection) output stream.</p><pre>PrintWriter writer = new PrintWriter(chatSocket.getOutputStream());</pre><p>Write (print) something</p><pre>writer.println(“message to send”); <br>writer.print(“another message”);</pre><p>The following diagram represents how it happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*PrJzremTRm5xAchNoi8gmw.png" /></figure><h4>Multithreading in Java</h4><p>It is a process of executing multiple threads simultaneously. When we use this multithreading it uses a shared memory area. <br><strong>Advantages-<br></strong>It doesn’t block the user because threads are independent and you can perform multiple operations at the same time.<br>We can perform many operations together, so it saves time.<br>Threads are independent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*Y4wl5k8TVpt9-R6iuMM_6w.png" /></figure><p><strong>How to make a Thread</strong><br>We can do it using two methods. There are implementing” the Runnable Interface or by extending the Thread class. These are the only two ways through which we can create a thread.</p><p><strong>Extend Thread Class</strong></p><pre>class Multi extends Thread {</pre><pre>public void run() {<br>        System.out.println(&quot;thread is running...&quot;);<br>    }</pre><pre>public static void main(String args[]) {<br>        Multi t1 = new Multi();<br>        t1.start();<br>}}</pre><p><strong>Implement Runnable Interface</strong></p><pre>class Multi3 implements Runnable {</pre><pre>public void run() {<br>        System.out.println(&quot;thread is running...&quot;);<br>    }</pre><pre>public static void main(String args[]) {<br>        Multi3 m1 = new Multi3();<br>        Thread t1 = new Thread(m1);   // Using the constructor Thread(Runnable r)  <br>        t1.start();<br>    }<br>}</pre><h4>The Thread Scheduler</h4><p>Thread scheduler taka all the decisions. Thread scheduler taka decisions about who moves from runnable to running, and about when a thread leaves the running state. We can’t control the thread scheduler because there are no methods to call. The main important point is there are no guarantees about scheduling. We can identify two types of thread scheduling. <br>1. Preemptive scheduling<br>It means the thread scheduler gives higher priority to the threads to first run.</p><p>2. Time slicing<br>The thread scheduler gives a particular time period and decided which task should be run next.</p><h4>Use sleep Method</h4><p>By using this sleep() method we can stop a currently running thread. Let’s see the example code.</p><pre>try {  <br>     Thread.sleep(2000);<br>  } catch(InterruptedException ex) {  <br>     ex.printStackTrace();  <br>}</pre><p><strong>Example Code-</strong></p><pre>public class RunThreads implements Runnable {</pre><pre>public static void main(String[] args) {<br>        RunThreads runner = new RunThreads();<br>        Thread alpha = new Thread(runner);<br>        Thread beta = new Thread(runner);<br>        alpha.setName(&quot;Alpha Thread&quot;);<br>        beta.setName(&quot;Beta Thread&quot;);<br>        alpha.start();<br>        beta.start();<br>    }</pre><pre>public void run() {<br>        for (int i = 0; i &lt; 25; i++) {<br>            String threadName = Thread.currentThread().getName();<br>            System.out.println(threadName + &quot;is running&quot;);<br>        }<br>    }<br>}</pre><p><strong>Output-</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*sevWqF-UNKB7T_qhJMe8iQ.png" /></figure><h4>Important points in the chapter</h4><ul><li>Client and server applications communicate over a Socket connection.</li><li>A Socket represents a connection between two applications which may (or may not) be running on two different physical machines.</li><li>A client must know the IP address (or domain name) and TCP port number of the server application.</li><li>A TCP port is a 16-bit unsigned number assigned to a specific server application. TCP port numbers allow different clients to connect to the same machine but communicate with different applications running on that machine.</li><li>The port numbers from 0 through 1023 are reserved for ‘well-known services’ including HTTP, FTP, SMTP, etc.</li><li>A client connects to a server by making a Server socket Socket s = new Socket(“127.0.0.1”, 4200);</li><li>Once connected, a client can get input and output streams from the socket. These are low-level ‘connection’ streams. sock.getInputStream(); sock.getOutputStream();</li><li>To launch a new thread, you need a Runnable to pass to the Thread’s constructor.</li><li>A thread is in the NEW state when you have instantiated a Thread object but have not yet called start().</li><li>When you start a thread (by calling the Thread object’s start() method), a new stack is created, with the Runnable run() method on the bottom of the stack. The thread is now in the RUNNABLE state, waiting to be chosen to run.</li><li>A thread is said to be RUNNING when the JVM’s thread scheduler has selected it to be the currently running thread. On a single-processor machine, there can be only one currently-running thread.</li><li>Sometimes a thread can be moved from the RUNNING state to a BLOCKED (temporarily non-runnable) state. A thread might be blocked because it’s waiting for data from a stream, or because it has gone to sleep, or because it is waiting for an object’s lock.</li><li>Thread scheduling is not guaranteed to work in any particular way, so you cannot be certain that threads will take turns nicely. You can help influence turn-taking by putting your threads to sleep periodically.</li><li>The static Thread.sleep() method forces a thread to leave the running state for at least the duration passed to the sleep method. Thread.sleep(200) puts a thread to sleep for 200 milliseconds.</li><li>The sleep() method throws a checked exception (InterruptedException), so all calls to sleep() must be wrapped in a try/catch, or declared.</li></ul><h3>References</h3><p>[1]Sierra, Kathy, and Bert Bates. “Head First Java™ Second Edition.” (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b0d7ad349ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java (Chapter 14) Saving Objects]]></title>
            <link>https://medium.com/@kalpa752mohotti/head-first-java-chapter-14-saving-objects-7e3a5c983bdc?source=rss-4c466850c72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e3a5c983bdc</guid>
            <category><![CDATA[saving-objects]]></category>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[deserialization]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[chapter-14]]></category>
            <dc:creator><![CDATA[Kalpa Sandaruwan]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 08:12:37 GMT</pubDate>
            <atom:updated>2022-07-18T08:12:37.072Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, Today I am going to explain the important points of Head First Java chapter 14. I am mainly focusing on serialization and file I/O.</p><p>Think if you want to save your java program state. We can choose how to save it but it will probably depend on how you plan to use the saved state.<br>If our data will be used by only the Java program that generated it,</p><p><strong>1. We can use serialization.</strong><br>It means writing a file that holds flattened objects. Then have your program read the serialized objects from the file and inflate them <br>back into living, breathing, heap-inhabiting objects.<br>If our data will be used by other programs<br><strong>2. We can write a plain text file</strong><br>Write a file, with delimiters that other programs can parse. For example, a tab-delimited file that a spreadsheet or database application can use.</p><h4><strong>Java Serialization</strong></h4><p>Serialization in Java is a mechanism for writing an object’s state into a byte-stream. It is most commonly found in Hibernate, RMI, JPA, EJB, and JMS technologies. Following are the steps for serialization.</p><p>Make a FileOutputStream</p><pre>FileOutputStream fileStream = new FileOutputStream(“MyGame.ser”);</pre><p>Make an ObjectOutputStream</p><pre>ObjectOutputStream os = new ObjectOutputStream(fileStream);</pre><p>Write the object</p><pre>os.writeObject(characterOne); <br>os.writeObject(characterTwo); <br>os.writeObject(characterThree);</pre><p>Close the ObjectOutputStream</p><pre>os.close();</pre><p>Java I/O API has connection streams. These connection streams represent connections to destinations and sources such as files or network sockets, and chain streams that work only if chained to other streams. The following image represents how it happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*35CqP6hz_c9TBTfZILOQYg.png" /></figure><p><strong>How to create a class to be serializable?</strong></p><p>We can implement a Serializable interface. This interface doesn’t have any methods to implement. Its sole purpose is to announce that the class implementing it is, well, serializable. In other words, objects of that type are saveable through the serialization mechanism.</p><pre>import java.io.*;</pre><pre>public class Box implements Serializable {</pre><pre>private int width;<br>    private int height;</pre><pre>public void setWidth(int w) {<br>        width = w;<br>    }</pre><pre>public void setHeight(int h) {<br>        height = h;<br>    }</pre><pre>public static void main(String[] args) {<br>        Box myBox = new Box();<br>        myBox.setWidth(50);<br>        myBox.setHeight(20);<br>        try {<br>            FileOutputStream fs = new FileOutputStream(&quot;foo.ser&quot;);<br>            ObjectOutputStream os = new ObjectOutputStream(fs);<br>            os.writeObject(myBox);<br>            os.close();<br>        } catch (Exception ex) {<br>            ex.printStackTrace();<br>        }<br>    }<br>}</pre><p><strong>Deserialization: restoring an object</strong></p><p>Deserialization is the reverse operation of serialization in which a byte stream is converted into an object. Because the serialization and deserialization processes are platform-independent, you can serialize an object on one platform and deserialize it on another. Following are the steps for deserialization.</p><p>Make a FileInputStream</p><pre>FileInputStream fileStream = new FileInputStream(“MyGame.ser”);</pre><p>Make an ObjectInputStream</p><pre>ObjectInputStream os = new ObjectInputStream(fileStream);</pre><p>read the objects</p><pre>Object one = os.readObject(); <br>Object two = os.readObject(); <br>Object three = os.readObject();</pre><p>Cast the objects</p><pre>GameCharacter elf = (GameCharacter) one; <br>GameCharacter troll = (GameCharacter) two; <br>GameCharacter magician = (GameCharacter) three;</pre><p>Close the ObjectInputStream</p><pre>os.close();</pre><p>deserialized, the JVM attempts to bring the object back to life by making a new object on the heap that has the same state the serialized object had at the time it was serialized. The following image represents it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*ldg-ry6pUqn1MiG8LPt7Dg.png" /></figure><h4>Write String to a Text File</h4><p>Serialization is the best way to save and restore data between running a Java program. But sometimes we need to save data to a plain old text file. The following code example will let you know how to do that.</p><pre>import java.io.*;</pre><pre>class WriteAFile {</pre><pre>public static void main(String[] args) {<br>        try {<br>            FileWriter writer = new FileWriter(&quot;foo.txt&quot;);<br>            writer.write(&quot;Hello Kalpa Sandaruwan&quot;);<br>            writer.close();<br>        } catch (IOException ex) {<br>            ex.printStackTrace();<br>        }<br>    }<br>}</pre><p>This is we created file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*QOuX0f5bCU-fSPDj1D_4fQ.png" /></figure><h4>The java.io.File class</h4><p>The java.io.File class represents a file on disk, but doesn’t actually represent the contents of the file. A File object represents the name and path of a file or directory on disk, for example:<br><strong>/Users/Kathy/Data/GameFile.txt</strong><br>But it does NOT represent, or give you access to, the data in the file.</p><p>We can do the following things using File Object</p><p>Make a File object representing an existing fil</p><pre>File f = new File(“MyCode.txt”);</pre><p>Make a new directory</p><pre>File dir = new File(“Chapter7”);  <br>dir.mkdir();</pre><p>List the contents of a directory</p><pre>if (dir.isDirectory()) {<br> String[] dirContents = dir.list();<br> for (int i = 0; i &lt; dirContents.length; i++) {<br> System.out.println(dirContents[i]);<br> }<br>}</pre><p>Get the absolute path of a file or directory</p><pre>System.out.println(dir.getAbsolutePath());</pre><p>Delete a file or directory (returns true if successful)</p><pre>boolean isDeleted = f.delete();</pre><p><strong>Reading from Text File</strong></p><p>We can use a File object to represent a file. We can use the Filereader object to read a file but we can do it more efficient way using BufferReader.</p><pre>import java.io.*;</pre><pre>class ReadAFile {</pre><pre>public static void main(String[] args) {<br>        try {<br>            File myFile = new File(&quot;foo.txt&quot;);<br>            FileReader fileReader = new FileReader(myFile);<br>            BufferedReader reader = new BufferedReader(fileReader);<br>            String line = null;<br>            while ((line = reader.readLine()) != null) {<br>                System.out.println(line);<br>            }<br>            reader.close();<br>        } catch (Exception ex) {<br>            ex.printStackTrace();<br>        }<br>    }<br>}</pre><p>Output-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*pOP2xRSD8cXu8fXN7Nobxg.png" /></figure><h4><strong>Important points in the chapter</strong></h4><p>You can save an object’s state by serializing the object.</p><p>To serialize an object, you need an ObjectOutputStream (from the java.io package)</p><p>Streams are either connection streams or chain streams</p><p>Connection streams can represent a connection to a source or destination, typically a file, network socket connection, or the console.</p><p>Chain streams cannot connect to a source or destination and must be chained to a connection (or other) stream.</p><p>To serialize an object to a file, make a FileOuputStream and chain it into an ObjectOutputStream.</p><p>To serialize an object, call writeObject(theObject) on the ObjectOutputStream. You do not need to call methods on the FileOutputStream.</p><p>To be serialized, an object must implement the Serializable interface. If a superclass of the class implements Serializable, the subclass will automatically be serializable even if it does not specifically declare implements Serializable.</p><h4>References</h4><p>[1]Sierra, Kathy, and Bert Bates. “Head First Java™ Second Edition.” (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e3a5c983bdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java (Chapter 13) A Very Graphic Story]]></title>
            <link>https://medium.com/@kalpa752mohotti/head-first-java-chapter-13-a-very-graphic-story-b437010a3d9f?source=rss-4c466850c72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b437010a3d9f</guid>
            <category><![CDATA[jframe]]></category>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[very-graphic-story]]></category>
            <category><![CDATA[gui]]></category>
            <category><![CDATA[chapter-13]]></category>
            <dc:creator><![CDATA[Kalpa Sandaruwan]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 08:09:56 GMT</pubDate>
            <atom:updated>2022-07-18T08:09:56.609Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, Today I am going to explain the important points of Head First Java chapter 13. I am mainly focusing on swing components.</p><p>The component is the same name as the widget. These components can use with our GUI. For example Text fields, buttons, scrollable lists, radio buttons, etc. In a swing virtually all components are capable of holding other components. In a previous article, we learn how to create a Jframe. And here I will explain how to work with panels, layouts, and swing components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*4SFAFXOKQS9sSuoKVDKheA.png" /></figure><h4>Layout Manager</h4><p>A layout manager is a java object. It associates with the particular components, almost always a background component. A layout manager is responsible for the size and placement of components. The layout manager has several flavors. If we create a background component that background component has its own layout manager.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*Zfk-dQIzXgyV6glZzw38pg.png" /></figure><p>We can identify three main layout managers.</p><p><strong>Border Layout</strong></p><p>This border layout manager divides background components into five regions. That regions are east, west, north, south, and center. We can add only one component to each region. Components laid out by this manager usually don’t get to have their preferred size. It is the default layout manager for a frame.</p><p>Sample Code-</p><pre>class A {</pre><pre>public static void main(String[] args) {<br>        A gui = new A();<br>        gui.go();</pre><pre>}</pre><pre>public void go() {<br>        JFrame frame = new JFrame();</pre><pre>JButton east = new JButton(&quot;East&quot;);<br>        JButton west = new JButton(&quot;West&quot;);<br>        JButton north = new JButton(&quot;North&quot;);<br>        JButton south = new JButton(&quot;South&quot;);<br>        JButton center = new JButton(&quot;Center&quot;);</pre><pre>frame.getContentPane().add(BorderLayout.EAST, east);<br>        frame.getContentPane().add(BorderLayout.WEST, west);<br>        frame.getContentPane().add(BorderLayout.NORTH, north);<br>        frame.getContentPane().add(BorderLayout.SOUTH, south);<br>        frame.getContentPane().add(BorderLayout.CENTER, center);<br>        frame.setSize(300, 300);<br>        frame.setVisible(true);<br>    }</pre><pre>}</pre><p>Output-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*tNjPRRr-yPWO1LqqhCigVg.png" /></figure><p><strong>Flow Layout</strong></p><p>FlowLayout manager works like a word processor. So when a component won’t fit horizontally, it drops to the next “line” in the layout. FlowLayout is the default layout manager for a panel.</p><p>Sample Code-</p><pre>class A {</pre><pre>public static void main(String[] args) {<br>        A gui = new A();<br>        gui.go();</pre><pre>}</pre><pre>public void go() {</pre><pre>JFrame frame = new JFrame();<br>        JPanel panel = new JPanel();<br>        panel.setBackground(Color.darkGray);<br>        JButton button = new JButton(&quot;Show me&quot;);<br>        panel.add(button);<br>        frame.getContentPane().add(BorderLayout.EAST, panel);<br>        frame.setSize(400, 400);<br>        frame.setVisible(true);</pre><pre>}</pre><pre>}</pre><p>Output-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*LPToFZbjb_NrAKWVvSYMvQ.png" /></figure><p><strong>Box Layout</strong></p><p>It works like a Flowlayout, but each component gets to have its own size, and the components are placed in the order in which they’re added. The box Layout manager can stack the components vertically or horizontally.</p><p>Sample Code-</p><pre>class A {</pre><pre>public static void main(String[] args) {<br>        A gui = new A();<br>        gui.go();</pre><pre>}</pre><pre>public void go() {<br>        JFrame frame = new JFrame();<br>        JPanel panel = new JPanel();<br>        panel.setBackground(Color.darkGray);<br>        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));</pre><pre>JButton button = new JButton(&quot;Show me&quot;);<br>        JButton buttonTwo = new JButton(&quot;Button 02&quot;);<br>        panel.add(button);<br>        panel.add(buttonTwo);<br>        frame.getContentPane().add(BorderLayout.EAST, panel);<br>        frame.setSize(400, 400);<br>        frame.setVisible(true);<br>    }</pre><pre>}</pre><p>Output-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*Jlez-xt-WImDyI196VftQQ.png" /></figure><h4>Swing Components-</h4><p><strong>JTextField-</strong></p><p>Constructors</p><pre>JTextField field = new JTextField(20);<br>JTextField field = new JTextField(“Your name”);</pre><p><strong>How to use it</strong></p><p>Get text out of it</p><pre>System.out.println(field.getText());</pre><p>Put text in it</p><pre>field.setText(“whatever”); <br>field.setText(““);</pre><p>Get an ActionEvent when the user presses return or enter</p><pre> field.addActionListener(myActionListener);</pre><p>Put the cursor back in the field</p><pre>field.requestFocus();</pre><p><strong>JTextArea</strong></p><p>Constructor</p><pre>JTextArea text = new JTextArea(10,20);</pre><p><strong>How to use it</strong></p><p>Make it have a vertical scrollbar only</p><pre>JScrollPane scroller = new JScrollPane(text); text.setLineWrap(true);</pre><p>Replace the text that’s in it</p><pre>text.setText(“Not all who are lost are wandering”);</pre><p>Append to the text that’s in it</p><pre>text.append(“button clicked”);</pre><p>Put the cursor back in the field</p><pre>text.requestFocus();</pre><p><strong>JCheckBox</strong></p><p>Constructor</p><pre>JCheckBox check = new JCheckBox(“Goes to 11”);</pre><p><strong>How to use it</strong></p><p>Listen for an item event (when it’s selected or deselected)</p><pre> check.addItemListener(this);</pre><p>Handle the event (and find out whether or not it’s selected)</p><pre>public void itemStateChanged(ItemEvent ev) { <br>String onOrOff = “off”; <br>if (check.isSelected()) onOrOff = “on”; <br>System.out.println(“Check box is “ + onOrOff); <br>}</pre><p><strong>JList</strong></p><p>Constructor</p><pre>String [] listEntries = {“alpha”, “beta”, “gamma”, “delta”,  “epsilon”, “zeta”, “eta”, “theta “}; <br>JList list = new JList(listEntries);</pre><p><strong>How to use it</strong></p><p>Make it have a vertical scrollbar</p><pre>JScrollPane scroller = new JScrollPane(list); scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); panel.add(scroller);</pre><p>Set the number of lines to show before scrolling</p><pre>list.setVisibleRowCount(4);</pre><p>Register for list selection events</p><pre>list.addListSelectionListener(this);</pre><h4>Important Points in the chapter.</h4><p>Layout managers control the size and location of components nested within other components.</p><p>When you add a component to another component (sometimes referred to as a background component, but that’s not a technical distinction), the added component is controlled by the layout manager of the background component.</p><p>A layout manager asks components for their preferred size, before making a decision about the layout. Depending on the layout manager’s policies, it might respect all, some, or none of the component’s wishes.</p><p>The BorderLayout manager lets you add a component to one of five regions. You must specify the region when you add the component, using the following syntax: add(BorderLayout.EAST, panel);</p><p>With BorderLayout, components in the north and south get their preferred height, but not width. Components in the east and west get their preferred width, but not height. The component in the center gets whatever is left over (unless you use pack()).</p><p>The pack() method is like shrink-wrap for the components; it uses the full preferred size of the center component, then determines the size of the frame using the center as a starting point, building the rest based on what’s in the other regions.</p><p>FlowLayout places components left to right, top to bottom, in the order they were added, wrapping to a new line of components only when the components won’t fit horizontally.</p><p>FlowLayout gives components their preferred size in both dimensions.</p><h4>References</h4><p>[1]Sierra, Kathy, and Bert Bates. “Head First Java™ Second Edition.” (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b437010a3d9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java (Chapter 12) A Very Graphic Story]]></title>
            <link>https://medium.com/@kalpa752mohotti/head-first-java-chapter-12-a-very-graphic-story-4cd87ed812ac?source=rss-4c466850c72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cd87ed812ac</guid>
            <category><![CDATA[jframe]]></category>
            <category><![CDATA[chapter12]]></category>
            <category><![CDATA[very-graphic-story]]></category>
            <category><![CDATA[gui]]></category>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Kalpa Sandaruwan]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 06:45:48 GMT</pubDate>
            <atom:updated>2022-07-18T06:45:48.431Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, Today I am going to explain the important points of Head First Java chapter 12. I am mainly focusing on getting gui.</p><h4>It all starts with window</h4><p>JFrame is an object. It represents a window on the screen. We can put it to all interface things. For example buttons, checkboxes, text fields, and so on.</p><h4>How to make a GUI</h4><p>Make a frame (a JFrame).</p><pre>JFrame frame = new JFrame();</pre><p>Make a widget (button, text field, etc.)</p><pre>JButton button = new JButton(“click me”);</pre><p>Add the widget to the frame</p><pre>frame.getContentPane().add(button);</pre><p>Display it (give it a size and make it visible).</p><pre>frame.setSize(300,300); <br>frame.setVisible(true);</pre><p><strong>Full Code</strong></p><pre>public static void main(String[] args) {<br>        JFrame frame=new JFrame();<br>        JButton button = new JButton(&quot;click me&quot;);<br>        frame.getContentPane().add(button);<br>        frame.setSize(300,300);<br>        frame.setVisible(true);<br>        <br>    }</pre><p>If we run the above code we can see the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*s00-cDh-nfC_5Le2KLxNUQ.png" /></figure><p>but when we click the button nothing happened. If we need to do something when we click the button we need two things.</p><ol><li>A method to be called when the user clicks (the thing you want to happen as a result of the button click).</li><li>A way to know when to trigger that method. In other words, a way to know when the user clicks the button.</li></ol><p>we can give events to the button to know when the user clicks it. this is called event handling. To listen for an event, you must register your interest with an event source. An event source is a thing that ‘fires’ and events based on user interaction. The listener interface gives the event source a way to call you back because the interface defines the method the event source will call when an event happens.</p><ol><li>we can get ActionEvents to the buttons by using the following points.</li></ol><p>2. Implement the ActionListener interface. <br> Register with the button (tell it you want to listen for events).</p><p>3. Define the event-handling method (implement the actionPerformed() method from the ActionListener interface).</p><pre>class A implements ActionListener{</pre><pre>public static void main(String[] args) {<br>        JFrame frame=new JFrame();<br>        JButton button = new JButton(&quot;click me&quot;);<br>        button.addActionListener(this);<br>        frame.getContentPane().add(button);<br>        frame.setSize(300,300);<br>        frame.setVisible(true);<br>       <br>        <br>    }</pre><pre><a href="http://twitter.com/Override">@Override</a><br>    public void actionPerformed(ActionEvent e) {<br>      <br>    }</pre><h4>Graphics</h4><p>There are three ways to put things into GUI. the following image represents how graphics work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*L-XxkRdAWi1_WNUZEx9Ydw.png" /></figure><h4>Inner Class</h4><p>By using this mechanism we can have one class nested inside another. It’s easy. Just make sure that the definition for the inner class is inside the curly braces of the outer class.<br><strong>main points-</strong><br>An inner class can use all the methods and variables of the outer class and if outer class private ones.</p><p>Example-</p><pre>class MyOuterClass { <br>   class MyInnerClass { <br>     void go() { <br>     }  <br>   }<br> }</pre><p>Inner class using an outer class variable.</p><pre>class MyOuterClass {</pre><pre>private int x;</pre><pre>class MyInnerClass {</pre><pre>void go() {<br>                x = 42;<br>            }<br>        } // close inner class<br>    } // close outer class</pre><p>How to make an instance of an inner class within the outer class.</p><pre>class MyOuter {</pre><pre>private int x;<br>        MyInner inner = new MyInner();</pre><pre>public void doStuff() {<br>            inner.go();<br>        }</pre><pre>class MyInner {</pre><pre>void go() {<br>                x = 42;<br>            }<br>        } // close inner class<br>    } // close outer class</pre><h4>Main points in the chapter</h4><p><strong>Event-</strong></p><p>To make a GUI, start with a window, usually a JFrame JFrame frame = new JFrame();</p><p>You can add widgets (buttons, text fields, etc.) to the JFrame using: frame.getContentPane().add(button);</p><p>Unlike most other components, the JFrame doesn’t let you add to it directly, so you must add to the JFrame’s content pane.</p><p>To make the window (JFrame) display, you must give it a size and tell it be visible: frame.setSize(300,300); frame.setVisible(true);</p><p>To know when the user clicks a button (or takes some other action on the user interface) you need to listen for a GUI event.</p><p><strong>Graphics-</strong></p><p>You can draw 2D graphics directly on to a widget.</p><p>You can draw a .gif or .jpeg directly on to a widget.</p><p>To draw your own graphics (including a .gif or .jpeg), make a subclass of JPanel and override the paintComponent() method.</p><p>The paintComponent() method is called by the GUI system. YOU NEVER CALL IT YOURSELF. The argument to paintComponent() is a Graphics object that gives you a surface to draw on, which will end up on the screen. You cannot construct that object yourself.</p><h4>References</h4><p>[1]Sierra, Kathy, and Bert Bates. “Head First Java™ Second Edition.” (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cd87ed812ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java (Chapter 11) Risky Behavior]]></title>
            <link>https://medium.com/@kalpa752mohotti/head-first-java-chapter-11-risky-behavior-426c29e13066?source=rss-4c466850c72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/426c29e13066</guid>
            <category><![CDATA[risky-behavior]]></category>
            <category><![CDATA[chapter-11]]></category>
            <category><![CDATA[exception]]></category>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[exception-handling]]></category>
            <dc:creator><![CDATA[Kalpa Sandaruwan]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 06:43:45 GMT</pubDate>
            <atom:updated>2022-07-18T06:43:45.398Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, Today I am going to explain the important points of Head First Java chapter 11. I am mainly focusing on exception handling.</p><h4>Exception Handling</h4><p>Java’s exception-handling mechanism is a clean, well-lighted way to handle “exceptional situations” that pop up at runtime. An exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.<br>Following the exception hierarchy will give you the main idea about the exceptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*s2560S1lFVDs_6-4K_1HjA.png" /></figure><p>There are main two types in exception. <br>Checked Exception<br>This type of exception occurs at the compile time. We can call this exception compile-time exceptions. These exceptions cannot simply be ignored at the time of compilation, the programmer should take care of (handle) these exceptions.</p><p>Unchecked Exception <br>This type of exception occurs at the time of execution. We can call it as Runtime Exception. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.</p><p><strong>How to handle an Exception</strong><br>If you are going to call risky methods, we can use try/catch block, throw, and throws. <br><strong>try/ catch</strong></p><pre>try {<br>  // do risky thing <br>} catch(Exception ex) <br>{  // try to recover <br>}</pre><p>In the above example, if the try is successful, the catch block does not execute. catch block runs when this code only runs if an Exception is thrown. For example, if a server is down you might use the catch block to try another server.</p><p><strong>finally</strong><br>A finally block is where you put code that must run regardless of an exception.</p><pre>try {<br>  turnOvenOn();<br>  x.bake();<br> } catch (BakingException ex) { <br>    ex.printStackTrace();<br> } finally { <br>    turnOvenOff();<br> }</pre><p>If the try or catch block has a return statement, finally will still run.</p><p><strong>Multiple Exception</strong><br>If we need to throw more than one exceptions in a method, we can do it with one try block and multiple catch blocks. <br>You can DECLARE exceptions using a supertype of the exceptions you throw.<br>You can CATCH exceptions using a supertype of the exception thrown.</p><pre>try {<br>  x.doRisky();<br>} catch(AlphaEx a) { <br> // recovery from AlphaEx <br>} catch(BetaEx b) {<br>  // recovery from BetaEx <br>} catch(GammaEx c) { <br> // recovery from GammaEx <br>} catch(DeltaEx d) {<br>  // recovery from DeltaEx <br>}</pre><p><strong>Throws</strong><br>This keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exceptions.</p><pre>public void m() throws BadException{<br>    // code<br>}</pre><p><strong>Exception Rules</strong><br>You cannot have a catch or finally without a try.</p><pre>void go() {<br>  Foo f = new Foo();<br>  f.foof();<br>  catch(FooException ex) {<br> }  <br>}</pre><p>You cannot put code between the try and the catch.</p><pre>try {<br>  x.doStuff();<br> } <br>int y = 43;<br> } catch(Exception ex) {<br> }</pre><p>A try MUST be followed by either a catch or a finally.</p><pre>try { <br> x.doStuff();<br> } finally {<br>  // cleanup <br>}</pre><p>A try with only a finally (no catch) must still declare the exception.</p><pre>void go() throws FooException {<br>  try {<br>  x.doStuff();<br>  } <br>finally {<br> } <br>}</pre><h4>Main points in the chapter</h4><p>A method can throw an exception when something fails at runtime.</p><p>An exception is always an object of type Exception. (Which, as you remember from the polymorphism chapters means the object is from a class that has Exception somewhere up its inheritance tree.)</p><p>The compiler does NOT pay attention to exceptions that are of type RuntimeException. A RuntimeException does not have to be declared or wrapped in a try/catch (although you’re free to do either or both of those things)</p><p>All Exceptions the compiler cares about are called ‘checked exceptions’ which really means compiler-checked exceptions. Only RuntimeExceptions are excluded from compiler checking. All other exceptions must be acknowledged in your code, according to the rules.</p><p>A method throws an exception with the keyword throw, followed by a new exception object: throw new NoCaffeineException();</p><p>Methods that might throw a checked exception must announce it with a throws Exception declaration.</p><p>If your code calls a checked-exception-throwing method, it must reassure the compiler that precautions have been taken.</p><p>If you’re prepared to handle the exception, wrap the call in a try/catch, and put your exception handling/recovery code in the catch block.</p><p>If you’re not prepared to handle the exception, you can still make the compiler happy by officially ‘ducking’ the exception. We’ll talk about ducking a little later in this chapter</p><h4>References</h4><p>[1]Sierra, Kathy, and Bert Bates. “Head First Java™ Second Edition.” (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=426c29e13066" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java (Chapter 10) Numbers Matter]]></title>
            <link>https://medium.com/@kalpa752mohotti/head-first-java-chapter-10-numbers-matter-b2448bc6d494?source=rss-4c466850c72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2448bc6d494</guid>
            <category><![CDATA[static]]></category>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[static-methods-java]]></category>
            <category><![CDATA[chapter-10]]></category>
            <category><![CDATA[numbers-matter]]></category>
            <dc:creator><![CDATA[Kalpa Sandaruwan]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 06:42:19 GMT</pubDate>
            <atom:updated>2022-07-18T06:42:19.369Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, Today I am going to explain the important points of Head First Java chapter 10. I am mainly focusing on numbers and statics.</p><h4><strong>Static methods</strong></h4><p>A static method means “behavior not dependent on an instance variable, so no instance/object is required. Just the class.” We can create a static method using static keywords. <br><strong>Let’s create a static method.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*C9ABCT4yY0YxkuMKnVgcSA.png" /></figure><pre>class Math{<br>public static int min(int a, int b){  <br>//returns the lesser of a and b <br>}}<br></pre><p>We can call this static method using a class name.</p><pre>Math.min(88,86);</pre><p>If we try to use an instance variable from inside a static method the compiler thinks, “I don’t know which object’s instance variable you’re talking about!”. because non-static methods are linked to instance variables, a static method cannot communicate with a non-static method. The static method cannot be associated with the non-static method if the non-static method is not associated with the instance variable. If we run the following code example it will get an error.</p><pre>public class Duck {  <br> private int size;<br>public static void main (String[] args) { <br> System.out.println(“Size of duck is “ + size);<br> }  <br>public void setSize(int s) {<br>  size = s;  <br> }  <br>public int getSize() {<br>  return size;  <br> } <br>}</pre><h4>Static variables</h4><p>static variables allow values shared by all instances of a class. We can create a static variable using a static keyword. There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants. Static variables are created when the program starts and destroyed when the program stops.</p><p><strong>Initializing a static variable</strong><br>When the class is loaded, static variables are initialized. There are two guarantees about static variables.<br><strong>1.</strong> Static variables in a class are initialized before any object of that class can be created.<br><strong>2.</strong> Static variables in a class are initialized before any static method of the class runs.</p><h4>Final Keyword</h4><p>If we mark a variable as final we can not change that variable again. that variable became a constant. We can not reassign any value to these variables. If we want we can create methods as a final but we can not override those methods.</p><pre>public static final int FOO_X = 25;</pre><h4>Math Methods</h4><p>These are static methods in class Math. <br><strong>Math.random()</strong><br>Returns a double between 0.0 through (but not including) 1.0.<br><strong>Math.abs()</strong><br>Returns a double that is the absolute value of the argument. The method is overloaded, so if you pass it an int it returns an int. Pass it a <br>double it returns a double.<br><strong>Math.round()</strong><br>Returns an int or a long (depending on whether the argument is a float or a double) rounded to the nearest integer value. <br><strong>Math.min()</strong><br>Returns a value that is the minimum of the two arguments. The method is overloaded to take ints, longs, floats, or doubles.<br><strong>Math.max()</strong><br>Returns a value that is the maximum of the two arguments. The method is overloaded to take ints, longs, floats, or doubles.</p><h4>Wrapping a primitive</h4><p>When you need to treat a primitive like an object, we can use wrapping classes. Before java version 5.0 we have to store primitive values inside the collection like ArrayList or HashMap. But now we don’t want to do this. We can use the wrapper class. The wrappers have a <br>bunch of really useful static methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*EVRMZb9c97hl0FFHIWGBMw.jpeg" /></figure><pre>String s = “2”; <br>int x = Integer.parseInt(s); <br>double d = Double.parseDouble(“420.24”);</pre><h4>Number formatting</h4><p>The method takes two arguments. The first argument describes the pattern of how many decimals places we want to see, and the second argument is the given value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*BK9za6_oAMcyS5SggGBq2A.png" /></figure><p><strong>The only required specifier is for TYPE</strong><br>You must include a type in your format instructions, and if you specify things besides type, the type must always come last.</p><p><strong>%d decimal</strong></p><pre>format(“%d”, 42);</pre><p>The argument must be compatible with an int, so that means <br>only byte, short, int, and char (or their wrapper types)</p><p><strong>%f floating point</strong></p><pre>format(“%.3f”, 42.000000);</pre><p>The argument must be of a floating point type.</p><p><strong>%x hexadecimal</strong></p><pre>format(“%x”, 42);</pre><p>The argument must be a byte, short, int, long (including <br>both primitive and wrapper types), and BigInteger.</p><p><strong>%c character</strong></p><pre>format(“%c”, 42);</pre><p>The argument must be a byte, short, char, or int (including <br>both primitive and wrapper types).</p><h4>Formatting Date</h4><p>The main difference between number and date formatting is that date formats use a two-character type that starts with “t” The examples below should give you a good idea of how it works:</p><p><strong>The complete date and time %tc</strong></p><pre>String.format(“%tc”, new Date());<br>Output - Sun Nov 28 14:52:41 MST 2004</pre><p><strong>Just the time %tr</strong></p><pre>String.format(“%tr”, new Date());<br>Output - 03:01:47 PM</pre><p><strong>Day of the week, month and day %tA %tB %td</strong></p><pre>Date today = new Date();<br>String.format(“%tA, %tB %td”,today,today,today)<br>Output - Sunday, November 28</pre><h4>Importance points in the chapter</h4><ul><li>A static method should be called using the class name rather than an object reference variable: Math.random() vs. myFoo.go()</li><li>A static method can be invoked without any instances of the method’s class on the heap.</li><li>A static method is good for a utility method that does not (and will never) depend on a particular instance variable value.</li><li>A static method is not associated with a particular instance — only the class — so it cannot access any instance variable values of its class. It wouldn’t know which instance’s values to use.</li><li>A static method cannot access a non-static method, since non-static methods are usually associated with instance variable state.</li><li>If you have a class with only static methods, and you do not want the class to be instantiated, you can mark the constructor private.</li><li>A static variable is a variable shared by all members of a given class. There is only one copy of a static variable in a class, rather than one copy per each individual instance for instance variables.</li><li>A static method can access a static variable.</li><li>To make a constant in Java, mark a variable as both static and final.</li><li>A final static variable must be assigned a value either at the time it is declared, or in a static initializer. static { DOG_CODE = 420; }</li><li>The naming convention for constants (final static variables) is to make the name all uppercase.</li><li>A final variable value cannot be changed once it has been assigned.</li><li>Assigning a value to a final instance variable must be either at the time it is declared, or in the constructor.</li><li>A final method cannot be overridden.</li><li>A final class cannot be extended (subclassed).</li></ul><h4>References</h4><p>[1]Sierra, Kathy, and Bert Bates. “Head First Java™ Second Edition.” (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2448bc6d494" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java (Chapter 09) Life and Death of an Object]]></title>
            <link>https://medium.com/@kalpa752mohotti/head-first-java-chapter-09-life-and-death-of-an-object-6c1fd4e4cd4d?source=rss-4c466850c72a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c1fd4e4cd4d</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[construtor]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Kalpa Sandaruwan]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 06:47:24 GMT</pubDate>
            <atom:updated>2022-07-17T06:47:24.329Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone, Today I am going to explain the important points of Head First Java chapter 09. I am mainly focusing constructors and garbage collection.</p><p>We know objects are born and objects die. As a programmer, we decide when and how to construct it. we decide when to destroy it. but actually, we can’t destroy the objects ourself. s Garbage Collector (gc) can vaporize it, reclaiming the memory that the object was using.</p><p>In Java, we care about two areas of memory the one where objects live (the heap), and the one where method invocations and local variables live (the stack).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*WlFDQF4QkRMp4a26M-Kemw.png" /></figure><h4>Difference between Stack and Heap</h4><p>Stack stores very short-time items such as methods, variables, and reference variables. <br>Heap stores objects and Java Runtime Environment classes. <br>Stack has faster access, allocation, and deallocation, and heap have slower access, allocation, and deallocation.<br>Stack follows LIFO order and Heap does not follow any order.</p><p>If local variable is a reference to an object, only the variable goes on the stack while object goes in the heap.Instance variable lives in heap inside the object they belong.</p><h4>Constructor</h4><p>The constructor looks like a method but it is not a method. It runs when we initiate an object. The only way to invoke a constructor is with the keyword new followed by the class name. Every class we create has a constructor. , even if we don’t write it ourselves.</p><pre>public class Duck {<br> public Duck() {<br> System.out.println(“Quack”);<br> }<br>}</pre><p>We can create a constructor with parameters. <br>We can create a constructor with multiple parameters. <br>If you have more than one constructor in a class, the constructors MUST have different argument lists. we can call it overloaded constructors.</p><pre>public class Duck {<br> public Duck() {<br> System.out.println(“Quack”);<br> }</pre><pre>public Duck(String a) {<br> System.out.println(“Quack”);<br> }</pre><pre>public Duck(String a, String b) {<br> System.out.println(“Quack”);<br> }<br>}</pre><p><strong>Importent points of construtor.</strong></p><p>A constructor is the code that runs when somebody says new on a class type.</p><p>A constructor must have the same name as the class, and no return type.</p><p>If you don’t put a constructor in your class, the compiler puts in a default constructor. The default constructor is always a no-arg constructor.</p><p>You can have more than one constructor in your class, as long as the argument lists are different. Having more than one constructor in a class means you have overloaded constructors.</p><p><strong>How do we invoke a superclass constructor?</strong><br>A call to super() in your constructor puts the superclass constructor on the top of the Stack. And what do you think that superclass constructor does? Calls its superclass constructor. And so it goes until the Object constructor is on the top of the Stack. Once Object() finishes, it’s popped off the Stack and the next thing down the Stack (the subclass constructor that called Object()) is now on top.That constructor finishes and so it goes until the original constructor is on the top of the Stack. We can call this as a constructor chain.</p><p>Now we learn how an object is born but how long does an object live?<br>The object’s life depends on the life of the reference referring to it. If the reference is considered “alive”, the object is still alive on the Heap. If the reference dies (and we’ll look at what that means in just a moment), the object will die.</p><p>An object becomes eligible for GC when its last live reference disappears. There are three main ways.<br>1. Make reference to that object that goes out of the scope.</p><p>2. Assign a reference to another object</p><p>3. Set a reference to null.</p><h4>References</h4><p>[1]Sierra, Kathy, and Bert Bates. “Head First Java™ Second Edition.” (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c1fd4e4cd4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>