<?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 Gihan Wijesinghe on Medium]]></title>
        <description><![CDATA[Stories by Gihan Wijesinghe on Medium]]></description>
        <link>https://medium.com/@gihantharaka76?source=rss-78ad2dabcbcd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sYsNn2bpkYQvUPVue_JtTQ.gif</url>
            <title>Stories by Gihan Wijesinghe on Medium</title>
            <link>https://medium.com/@gihantharaka76?source=rss-78ad2dabcbcd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:57:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gihantharaka76/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/@gihantharaka76/head-first-java-chapter-18-distributed-computing-6a415f0f06a3?source=rss-78ad2dabcbcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a415f0f06a3</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Gihan Wijesinghe]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 03:21:47 GMT</pubDate>
            <atom:updated>2022-07-19T03:21:47.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*1oSW-WZDwOXvuTjmO31FVQ.png" /></figure><p>Method calls are always in between two objects on the same heap.</p><pre>class Foo{</pre><pre>void go(){</pre><pre>Bar b = new Bar();</pre><pre>b.doStuff();</pre><pre>}</pre><pre>public static void main(String[] args){</pre><pre>Foo f = new Foo();</pre><pre>f.go();<br>}</pre><pre>}</pre><p>In above code block, Foo instance referenced by f and the Bar object referenced by b are both on the same heap-same JVM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*3Bzvg_8oYRWQ5Rq_QvPYPQ.png" /></figure><h4>Design for Remote Method Calls</h4><p>Create 4 things,</p><ol><li>Server</li><li>Client</li><li>Server helper</li><li>Client helper</li></ol><p><strong>Steps</strong></p><ol><li>Create client and server app.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbBxXFM3vBqotmq2mPjROw.png" /></figure><p>2. Create client and server ‘helpers’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Or8T2y6OPPYFYeoaJzLWJw.png" /></figure><h4>How method call happens</h4><ul><li>Client object calls doBigThing() on the client helper object</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zt49VhXQDYg-hcFKaszaPw.png" /></figure><ul><li>Client helper packages up information about the call and ships it over the network to the service helper.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpYPpsGz5D0dMttqQbQfsQ.png" /></figure><ul><li>Service helper unpacks the information from the client helper, finds out which method to call and invokes the real method on the real service object.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8d0uOlMTYWn7kgP-Taf2Uw.png" /></figure><h4>Making the Remote Service</h4><ol><li>Make a <strong>Remote Interface</strong></li></ol><pre>import java.rmi.*;</pre><pre>public interface MyRemote <strong>extends Remote</strong>{</pre><pre>public <strong>String</strong> sayHello() throws <strong>RemoteException</strong>;<br>}</pre><p>2. Make a Remote Implementation</p><pre>public class MyRemoteImpl <strong>extends UnicastRemoteObject</strong> <strong>implements MyRemote</strong>{</pre><pre>public MyRemoteImpl <strong>throws RemoteException</strong>(){<br>}</pre><pre>public String sayHello(){</pre><pre>return &quot;Server says,&#39;Hey&#39;&quot;;<br>}</pre><pre>public static void main(String[] args){</pre><pre>try{</pre><pre>MyRemote service = new MyRemoteImpl();</pre><pre>Naming.rebind(&quot;Remote Hello&quot;, service);<br>}catch(Exception e){</pre><pre>e.printStackTrace();<br>}<br>}<br>}</pre><p>3. Generate Stubs and Skeletons using rmic</p><p>4. Start the RMI registry(rmiregistry)</p><p>5. Start the remote service</p><h4>Servlets</h4><p>Servlets are Java programs that run on HTTP web server. When a client uses a web browser to interact with a web page, a request is sent back to the web server. If the request needs the help of a Java servlet, the web server runs the servlet code.</p><h4>Steps for making and running a servlet</h4><ol><li>Find out where your servlets need to be placed.</li><li>Get the servlets.jar and add it to your classpath.</li><li>Write a servlet class by extending HttpServlet.</li><li>Write an HTML page that invokes your servlet.</li><li>Make your servlet and HTML page available to your server.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a415f0f06a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java - Chapter 17 Release Your Code]]></title>
            <link>https://medium.com/@gihantharaka76/head-first-java-chapter-17-release-your-code-c3ad86653096?source=rss-78ad2dabcbcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3ad86653096</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Gihan Wijesinghe]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 02:11:06 GMT</pubDate>
            <atom:updated>2022-07-19T02:11:06.777Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deploying your application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*d-YseHqDhzJ6rSC63Al2lA.png" /></figure><ol><li><strong>Local</strong> - Entire application runs on the end-user’s computer.</li><li><strong>Combination of local and remote</strong> - Application is distributed with a client portion running on the user’s local system.</li><li><strong>Remote</strong> - Entire java application runs on a server system, with the client accessing the system through non-Java(Web browser).</li></ol><h4>Put your Java in a JAR</h4><p>A JAR file is Java Archive. its based on the pkzip file format, and it lets you bundle all your classes so that instead of presenting your client with 28 class files, you hand over just a single JAR file.</p><p>Making an executable JAR,</p><ol><li>Make sure all of your class files are in the classes directory.</li><li>Create a manifest.txt file that states which class has the main() method.</li></ol><pre>Main-Class: MyApp // don&#39;t put the .class at the end only class name</pre><p>3. Run the jar tool to create a JAR file that containes everything in the classes directory, plus the manifest.</p><h4>Packages</h4><p>Packages prevent class name conflicts, but only if you choose a package name that’s guaranteed to you unique. Best way to do that is to preface your packages with your reverse domain name. You might write a class named Customer and a class named Account and a class named ShoppingCart. And what do you know, half of all developers working in enterprise e-commerce have probably written classes with those names. In an Object oriented world, that’s just dangerous. If part of the point of Object oriented is to write reusable components, developers need to be able to piece together components from a variety of sources, and build something new out of them. Your components have to be able to ‘play well with others’, including those you didn’t write or even know about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGBi0vDRldb8-NFBUGjsRA.png" /></figure><h4>Put classes in a package</h4><ol><li>Choose a package name</li><li>Put a package statement in your class</li></ol><pre><strong>package com.headfirstjava;</strong></pre><pre>import javax.swing.*;</pre><pre>public class PackageExercise{</pre><pre>}</pre><p>3. Set up a matching directory structure.</p><h4>Making an executable JAR with packages</h4><ol><li>Make sure all of your class files are withing the correct package structure, under the classes directory.</li><li>Create a manifest.txt file that states which class has the main() method, and be sure to use the fully-qualified class name.</li><li>Run the jar tool to create a JAR file that contains the package directories plus the manifest.</li></ol><h4>Java Web Start</h4><p>Java Web Start(JWS) is you launch your application with a web browser. End-users launch this by clicking on a link in a web page. But once the app downloads, it runs outside the browser, just like any other stand-alone java application. JWS is just an executable JAR that’s distributed over the web.</p><p>How JWS works,</p><ol><li>Client clicks on Web page link to your JWS application(a .jnlp file)</li></ol><pre>&lt;a <strong>href=&quot;MyApp.jnlp&quot;</strong>&gt;Click&lt;/a&gt;</pre><p>2. Web server(http) gets the request and sent back a .jnlp file (not the JAR)</p><p>3. JWS is started up by the browser. JWS helper app reads the .jnlp file and asks the server for the MyApp.jar file.</p><p>4. Web server ‘serves’ up the requested .jar file.</p><p>5. JWS gets the JAR and starts the application by calling the specified main() method.</p><h4>The .jnlp file</h4><p>To make a JWS, you need .jnlp file which is <strong>Java Network Launch Protocol</strong> which describes your application. It is a simple XML document. JWS use this file to find the applications JAR file.</p><h4>Steps to make and deploy a JWS app</h4><ol><li>Make an executable JAR for your application.</li><li>Write a .jnlp file</li><li>Place your JAR and .jnlp files on your server.</li><li>Add a new mime type to your web server.</li><li>Create a web page with a link to your .jnlp file.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3ad86653096" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java - Chapter 16 Data Structures]]></title>
            <link>https://medium.com/@gihantharaka76/head-first-java-chapter-16-data-structures-65a4e4a6ad6?source=rss-78ad2dabcbcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/65a4e4a6ad6</guid>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Gihan Wijesinghe]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 00:45:43 GMT</pubDate>
            <atom:updated>2022-07-19T00:45:43.489Z</atom:updated>
            <content:encoded><![CDATA[<h4>Collections</h4><ul><li><strong>TreeSet </strong>- keeps the element sorted and prevent duplicates</li><li><strong>HashMap </strong>- let you store and accewss elements as name/value pairs.</li><li><strong>LinkedList </strong>- designed to give better performance when you insert or delete elements from the middle of the collection.</li><li><strong>HashSet </strong>- prevents duplicates in the collection, and given an element, can find that element in the collection quickly.</li><li><strong>LinkedHashMap </strong>- it can remember the order in which elements were inserted.</li></ul><h4>Sort() method</h4><p>There is a sort() method in the Collection class. It takes a List, and since ArrayList implements the List interface, ArrayList IS-A List.</p><pre>Collections.sort()</pre><h4>Generics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*IzfvR9S5BalTMCQXy6npNg.png" /></figure><p>With generics you can create type-safe collections where more problems are caught at compile-time instead of runtime.</p><p>Without generics the compiler would happily let you put a Fish into an ArrayList that supposed to hold only Car objects.</p><ol><li>Creating instances of generified classes</li></ol><pre>new ArrayList&lt;Car&gt;()</pre><p>2. Declaring and assigning variables of generic type</p><pre>List&lt;Car&gt; carList =  new ArrayList&lt;Car&gt;()</pre><p>3. Declaring methods that take generic types</p><pre>void foo(List&lt;Car&gt; list) <br>x.foo(carList)</pre><h4>Using generic classes</h4><p>Generic class means that the class declaration includes a type parameter. Two key areas to look at in generified class,</p><ol><li>The class declaration</li><li>The method declarations that let you add elements</li></ol><h4>Using generic methods</h4><p>Generic method means that the method declaration uses a type parameter in its signature.</p><ul><li>Using a type parameter defined in the class declaration.</li></ul><pre>public class ArrayList<strong>&lt;E&gt;</strong> extends AbstractList<strong>&lt;E&gt;</strong> ... {<br>     public boolean add(<strong>E</strong> o)</pre><ul><li>Using a type parameter that was NOT defined in the class declaration.</li></ul><pre>public <strong>&lt;T extends Animal&gt;</strong> void takeThing(ArrayList<strong>&lt;T&gt;</strong> list)</pre><h4>Set instead of a List</h4><p>In Collection API, we find three main interfaces. List, Set, and Map. ArrayList is a List, but it looks like Set is exactly what we need.</p><ul><li><strong>LIST </strong>- when sequence matters. Collection that know about index position.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*DrPIkiWKxse2tNWZZ02YTw.png" /></figure><ul><li><strong>SET </strong>- when uniqueness matters. Collections that do not allow duplicates.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*75lhXvL8NOlvKyk7s0t9wQ.png" /></figure><ul><li><strong>MAP</strong> - when finding something by key matters. Collections that use key-value pairs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*gjz65Nps-JhGQ7W96RAzjA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65a4e4a6ad6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java - Chapter 15 Make a Connection]]></title>
            <link>https://medium.com/@gihantharaka76/head-first-java-chapter-15-make-a-connection-173b958d1fd0?source=rss-78ad2dabcbcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/173b958d1fd0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Gihan Wijesinghe]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 00:13:49 GMT</pubDate>
            <atom:updated>2022-07-19T00:13:49.310Z</atom:updated>
            <content:encoded><![CDATA[<h4>Connection, Sending and Receiving</h4><p>The three things we have to lean to get the client working are,</p><ol><li>How to establish the initial <strong>connection </strong>between the client and server</li><li>How to <strong>send </strong>messages to the server</li><li>How to <strong>receive </strong>messages from the server</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*1F_EVK28OtWGLSaGH_bt5g.png" /></figure><h4>Make a network Socket connection</h4><p>To make a socket connection we need to know two things,</p><ul><li>About the server</li><li>Which port it is running on</li></ul><p>Simply, <strong>IP address</strong> and <strong>TCP port number</strong>.</p><pre>Socket chatSocket = new Socket(“196.164.1.103”, 5000);<br>                     // Socket(IP Address, TCP port number)</pre><ul><li>TCP port numbers from <strong>0</strong> to <strong>1023</strong> are reserved for well known services. Don’t use them to server programs</li><li>For the server we can pick a number between <strong>1024</strong> to <strong>65535</strong>.</li></ul><h4>Reading data from a Socket</h4><p>To communicate over a Socket connection, you use streams. In java most of you Input Output won’t care what you high-level chain stream is actually connected to. You can use <strong>BufferedReader </strong>that makes difference because your connection stream is connected to a Socket rather than a File.</p><ol><li>Make a Socket connection to the server</li></ol><pre>Socket chatSocket = new Socket(“127.0.0.1”, 5000);</pre><p>2. Make an InputStreamReader chained to the Socket’s low-level input stream.</p><pre>InputStreamReader stream = new InputStreamReader(chatSocket.getInputStream());</pre><p>3. Make a BufferedReader and read</p><pre>BufferedReader reader = new BufferedReader(stream);<br>String message = reader.readLine();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMwNFBru-jg055NXTFR8HQ.png" /></figure><h4>Write data to a Socket</h4><p>When you’re writing one String at a time, PrintWriter is the standard choice. It has two key methods which are print() and println() just like system.out.</p><ol><li>Make a Socket connection to the server</li></ol><pre>Socket chatSocket = new Socket(“127.0.0.1”, 5000);</pre><p>2. Make a PrintWrite chained to the Socket’s low-level output stream</p><pre>PrintWriter writer = new PrintWriter(chatSocket.getOutputStream());</pre><p>3. Write something</p><pre>writer.println(“message to send”); <br>writer.print(“another message”);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJADb88UJiWZE8WdGitu8Q.png" /></figure><h4>Multithreading in Java</h4><p>For maximum CPU efficiency, Java’s multithreading functionality enables the concurrent execution of two or more program components. Each element of such software is referred to as a thread. Threads are hence short processes that are encapsulated within a process.</p><p>A thread is a separate ‘thread of execution’. In other words separate call stack. A <strong>Thread</strong> is a java class that represents a <strong>thread</strong>.</p><h4>What does it mean to have more than one call stack?</h4><ol><li>JVM calls the main() method</li></ol><pre>public static void main(String[] args) {</pre><pre>}</pre><p>2. main() starts a new thread. main thread is temporarily frozen while the new thread starts running.</p><pre>Runnable r = new MyThreadJob();<br>Thread t = new Thread(r); <br>t.start(); <br>Dog d = new Dog();</pre><p>3. JVM switches between the new thread and the original main thread, until both threads complete.</p><h4>How to launch a new thread</h4><ol><li>Make a Runnable object</li></ol><pre>Runnable threadJob = new MyRunnable();</pre><p>2. Make a Thread object and give it a Runnable</p><pre>Thread myThread = new Thread(threadJob);</pre><p>3. Start the Thread</p><pre>myThread.start();</pre><p>To make a job for your thread, implement <strong>Runnable interface</strong>.</p><pre>public class MyRunnable <strong>implements</strong> <strong>Runnable</strong>{</pre><pre>}</pre><h4>The Thread Scheduler</h4><p>Thread scheduler makes all the decisions about who moves from runnable to running. It decides who runs, and for how long, and where the threads go when the scheduler decides to kick them out of the currently-running state.</p><p>Two types of scheduling,</p><ul><li>Time-slicing schedule</li></ul><p>Some time-slices are provided to the threads so that after some time, the running thread has to give up the CPU. Thus, the other waiting threads also get time to run their job.</p><ul><li>Preemptive-Priority Scheduling</li></ul><p>Name of the scheduling algorithm denotes that the algorithm is related to the priority of the threads. Assume there are multiple threads available in the runnable state. The thread scheduler picks that thread that has the highest priority.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=173b958d1fd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java - Chapter 14 Saving Objects]]></title>
            <link>https://medium.com/@gihantharaka76/head-first-java-chapter-14-saving-objects-77f9c3276b60?source=rss-78ad2dabcbcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/77f9c3276b60</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Gihan Wijesinghe]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 23:04:54 GMT</pubDate>
            <atom:updated>2022-07-18T23:04:54.737Z</atom:updated>
            <content:encoded><![CDATA[<h4>Serialization</h4><p>Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object. After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.</p><p>Classes <strong>ObjectInputStream</strong> and <strong>ObjectOutputStream</strong> are high-level streams that contain the methods for serializing and deserializing an object</p><h4>Writing serialized object to a file</h4><ol><li>Make a <strong>FileOutputStream</strong></li></ol><pre>FileOutputStream fileStream = new FileOutputStream(&quot;MyGame.ser&quot;);</pre><p>2. Make an <strong>ObjectOutputStream</strong></p><pre>ObjectOutputStream os = new ObjectOutputStream(fileStream);</pre><p>3. Write the object</p><pre>os.writeObject(characterOne);</pre><pre>os.writeObject(characterTwo);</pre><pre>os.writeObject(characterThree);</pre><p>4. Close the <strong>ObjectOutputStream</strong></p><pre>os.close();</pre><p>If you want your class to be serializable you have to implement Serializable Interface.</p><pre>public class Box <strong>implements</strong> <strong>Serializable</strong>{</pre><pre>}</pre><h4>Deserialization</h4><p>The whole point of serializing an object is so that you can restore it back to its original state at some later date, in a different ‘run’ of the JVM. Deserialization is a lot like serialization in reverse.</p><ol><li>Make a <strong>FileInputStream</strong></li></ol><pre>FileInputStream fileStream = new FileInputStream(&quot;MyGame.ser&quot;);</pre><p>2. Make an <strong>ObjectInputStream</strong></p><pre>ObjectInputStream os = new ObjectInputStream(fileStream);</pre><p>3. Read the objects</p><pre>Object one = os.readObject(); <br>Object two = os.readObject(); <br>Object three = os.readObject();</pre><p>4. <strong>Cast </strong>the objects</p><pre>GameCharacter elf = (GameCharacter) one;<br>GameCharacter troll = (GameCharacter) two;<br>GameCharacter magician = (GameCharacter) three;</pre><p>5. Close the <strong>ObjectInputStream</strong></p><pre>os.close();</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77f9c3276b60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java - Chapter 13 Work on your swing]]></title>
            <link>https://medium.com/@gihantharaka76/head-first-java-chapter-13-work-on-your-swing-3fb5c961c8ca?source=rss-78ad2dabcbcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fb5c961c8ca</guid>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Gihan Wijesinghe]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 17:10:12 GMT</pubDate>
            <atom:updated>2022-07-18T17:10:12.584Z</atom:updated>
            <content:encoded><![CDATA[<h4>Swing Components</h4><p>A widget is technically a Swing Component. The things you put in a GUI and the things user sees and interacts with,</p><ul><li>Text Fields</li><li>Buttons</li><li>Scrollable lists</li><li>Radio buttons</li></ul><p>Those widgets are extends from javax.swing.JComponent</p><h4>Layout Manager</h4><p>Layout manager is a java object associated with a particular component, almost always a background component. It controls the components contained within the component the layout manager is associated with.</p><p>Types of layout managers,</p><ul><li><strong>BorderLayout </strong>- divides a background conponent into five regions.</li><li><strong>FlowLayout </strong>- acts kind of like a word processor, except with components instead of words.</li><li><strong>BoxLayout </strong>- is like FlowLayout in that each component gets to have its own size.</li></ul><h4>Swing Components</h4><h4>JTextField</h4><pre>JTextField field = new JTextField(20); // 20 columns<br>JTextField field = new JTextField(&quot;phone&quot;);</pre><p>How to use,</p><ol><li>Get text out of it.</li></ol><pre>System.out.println(field.getText());</pre><p>2. Put text in it.</p><pre>field.setText(&quot;whatever&quot;);</pre><p>3. Get an actionEvent when user presses return or enter.</p><pre>field.addActionListener(myActionListener);</pre><p>4. Select/Highlight the text in the field</p><pre>field.selectAll();</pre><p>5. Put the cursor back in the field.</p><pre>field.requestFocus();</pre><h4>JTextArea</h4><pre>JTextArea text = new JTextArea(10,20);</pre><ol><li>Make it have a vertical scrollbar only</li></ol><pre>JScrollPane scroller = new JScrollPane(text); text.setLineWrap(true); scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); <br>panel.add(scroller);</pre><p>2. Replace the text that’s in it.</p><pre>text.setText(“Not all who are lost are wandering”);</pre><p>3. Append to the text that’s in it.</p><pre>text.append(“button clicked”);</pre><p>4. Select/Highlight the text in the field.</p><pre>text.selectAll();</pre><p>5. Put the cursor back in the field.</p><pre>text.requestFocus();</pre><h4>JCheckBox</h4><pre>JCheckBox check = new JCheckBox(&quot;Goes to 11&quot;);</pre><ol><li>Listen for an item event</li></ol><pre>check.addItemListener(this);</pre><p>2. Handle the event</p><pre>public void itemstateChanged(ItemEvent ev){ <br>String onOrOff = &quot;off&quot;; <br>if (check.isSelected()) onOrOff = &quot;on&quot;; <br>System.out.println(&quot;Check box is &quot; + onOrOff);<br>}</pre><p>3. Select or deselect it in code.</p><pre>check.setSelected(true);<br>check.setSelected(false);</pre><h4>JList</h4><pre>String [] listEntries = {“alpha”, “beta”, “gamma”, “delta”,  “epsilon”, “zeta”, “eta”, “theta “};<br>JList list = new JList(listEntries);</pre><ol><li>Make it have a vertical scrollbar</li></ol><pre>JScrollPane scroller = new JScrollPane(list); scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); panel.add(scroller);</pre><p>2. Set the number of lines to show before scrolling</p><pre>list.setVisibleRowCount(4);</pre><p>3. Restrict the user to selecting only ONE thing at a time.</p><pre>list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);</pre><p>4. Register for list selection events.</p><pre>list.addListSelectionListener(this);</pre><p>5. Handle events.</p><pre>public void valueChanged(ListSelectionEvent lse) {<br> if( !lse.getValueIsAdjusting()) {<br>  String selection = (String) list.getSelectedValue();<br>  System.out.println(selection);<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fb5c961c8ca" 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/@gihantharaka76/head-first-java-chapter-12-a-very-graphic-story-7f8a3ec3add7?source=rss-78ad2dabcbcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f8a3ec3add7</guid>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Gihan Wijesinghe]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 16:19:56 GMT</pubDate>
            <atom:updated>2022-07-18T16:19:56.872Z</atom:updated>
            <content:encoded><![CDATA[<h4>JFrame</h4><p>JFrame is the object that represents a window on the screen. It’s where you put all the interface things like buttons, check boxes, text fields etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*7ZDIiWktkADgwMn4upmq3A.png" /></figure><h4>Making a GUI</h4><ol><li>Make a frame(a JFrame)</li></ol><pre>JFrame frame = new JFrame();</pre><p>2. Make a widget(button, text field etc)</p><pre>JButton button = new JButton(&quot;click me&quot;);</pre><p>3. Add the widget to the frame</p><pre>frame.getContentPane().add(button);</pre><p>4. Display it</p><pre>frame.setSize(300,300); // giving a size<br>frame.setVisible(true); // make it visible</pre><h4>Button Click</h4><p>We need two things</p><ol><li>A method to be called when the user clicks the button</li><li>A way to know when to trigger that method. In other words, way to know when user click the button.</li></ol><h4>Getting Button’s Action Event</h4><ol><li>Implement ActionListener Interface.</li></ol><pre><strong>import java.awt.event.*;</strong>  // importing package that have ActionListener and ActionEvent</pre><pre>public class SimpleGUI <strong>implements ActionListener{</strong></pre><pre><br>}</pre><p>2. Register with the button.</p><pre>button.<strong>addActionListener(this);</strong></pre><p>3. Define the event-handling method</p><pre>public void actionPerformed(<strong>ActionEvent event</strong>) {</pre><pre>button.setText(“I’ve been clicked!”);<br>}</pre><h4>Ways to put things on GUI</h4><ol><li>Put widgets on a frame.</li></ol><pre>frame.getcont&amp;ntPane().add(myButton);</pre><p>2. Draw 2D graphics on a widget.</p><pre>graphics.fi110val(70,70,lOO,lOO);</pre><p>3. Put a JPEG on a widget.</p><pre>qraphics.drawImage(myPic,lO,lO,this);</pre><h4>Graphics</h4><ul><li>Can draw 2D graphics directly on to a widget.</li><li>Can draw a .gif or .jpeg directly on to a widget.</li><li>To draw your own graphics (including a .gif or.jpeg), make a subclass of JPanel and override the paint Component() method.</li><li>The paintComponent() method is called bythe 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.</li><li>Typical methods to call on a Graphics object (the paintComponent paramenter) are:</li></ul><pre>graphic5.setColor(Color.blue); <br>g.fillRect(20,SO,lOO,120);</pre><ul><li>To draw a .jpg, construct an Image using:</li></ul><pre>Image image = new ImageIcon(&quot;catzilla.jpg&quot;).getImage();</pre><h4>Inner Classes</h4><p>From using inner classes you can have one class nested inside another.</p><pre>class MyOuterClass {<br>    class MyInnerClass {<br>  void go() {}<br>  }<br> }</pre><ul><li>Inner class can use all the methods and variables of the outer class. (private ones also).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f8a3ec3add7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java - Chapter 11 Risky Behaviour]]></title>
            <link>https://medium.com/@gihantharaka76/head-first-java-chapter-11-risky-behaviour-9aa4fa2ef9f7?source=rss-78ad2dabcbcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa4fa2ef9f7</guid>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Gihan Wijesinghe]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 14:36:53 GMT</pubDate>
            <atom:updated>2022-07-18T14:36:53.700Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exceptions</h4><p>Methods in java use exceptions to tell the calling code, “something bad happened, I failed”. So simply, exception is a problem that arises during the execution of a program.</p><p>If you wrap this risky code in something called a try/catch, the compiler will relax.</p><pre><strong>try{</strong></pre><pre>//do risky thing<br><strong>}catch(exception e){</strong></pre><pre>//try to recover<br><strong>}</strong></pre><p>An exception is an object because of that what you trying to catch is an object. <strong>Catch </strong>argument is declared as type Exception, and the parameter reference variable is <strong>e</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*I7ahTyL6ABtijp-DDaCU5A.png" /></figure><ul><li>Compile does not pay attention to exceptions that are of type <strong>RuntimeException</strong>.</li><li>All exceptions the compiler cares about are called <strong>checked exceptions.</strong></li></ul><h4>Finally block</h4><p>A finally block is where you put code that must run regardless of an exception.</p><pre>try{</pre><pre>turnOvenOn();</pre><pre>x.bake();<br>}catch(BackingException e){</pre><pre>e.printStackTrace();<br>}<strong>finally{</strong></pre><pre><strong>turnOvenOff();<br>}</strong></pre><p>Whether the task is a failure or not Oven should be turned off at the end. Even the try block fails, even the try block succeeds, if the try/catch block has a return statement but the finally will still run.</p><h4>Multiple Exceptions</h4><p>The compiler will make sure that you’re handled all the checked exceptions thrown by the method you’re calling.</p><pre>public class Foo{</pre><pre>public void go(){</pre><pre>Laundry l = new Laundry();</pre><pre>try{</pre><pre>l.doLaundry();<br><strong>}catch(PantsException pex){</strong></pre><pre><strong>//recovery code<br>}catch(LingerieException lex){</strong></pre><pre><strong>//recovery code<br>}</strong><br>}</pre><pre>}</pre><h4>Handle / Declare</h4><ul><li><strong>Handle</strong></li></ul><p>Wrap the risky call in a try/catch</p><pre><strong>try{</strong></pre><pre>l.doLaundry();<br><strong>}catch</strong>(PantsException pex)<strong>{</strong></pre><pre>//recovery code<br><strong>}</strong></pre><ul><li><strong>Declare</strong></li></ul><p>If you don’t want to handle an exception you can duck it by <strong>declaring </strong>it.</p><pre>public void foo() <strong>throws ReallyBadException</strong>{</pre><pre>laundry.doLaundry();<br>}</pre><h4>Exception Rules</h4><ul><li>Cannot have a catch block or finally block without a try block.</li><li>Cannot put code between the try and catch block.</li><li>Try block must be followed by either a catch block or a finally block.</li><li>Try block with only a finally block must declare the exception.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa4fa2ef9f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java - Chapter 10 Numbers Matters]]></title>
            <link>https://medium.com/@gihantharaka76/head-first-java-chapter-10-numbers-matters-1b4d2206141b?source=rss-78ad2dabcbcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b4d2206141b</guid>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Gihan Wijesinghe]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 13:39:43 GMT</pubDate>
            <atom:updated>2022-07-18T13:39:43.488Z</atom:updated>
            <content:encoded><![CDATA[<h4>Static &amp; Non Static Methods</h4><p>Keyword static lets a method run without any instance of the class. Static method means behaviour not dependent on an instance variable, so no instance or object is required.</p><ul><li>Static methods can’t use non-static (instance) variables.</li><li>Static methods can’t use non-static methods.</li></ul><p>Static Method</p><pre>public <strong>static </strong>int min(int a, int b){</pre><pre>}</pre><p>Non- Static method</p><pre>public class Song{</pre><pre><strong>String title;</strong> // instance variable</pre><pre>public void play(){</pre><pre>SoundPlayer sp = new SoundPlayer();</pre><pre>sp.playSound(<strong>title</strong>);<br>}</pre><pre>}</pre><p>Static methods can call using class name. Doesn’t need to instantiate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*YHvC0AeH523T9pGAnJwHuQ.png" /></figure><pre><strong>Math.min</strong>(88,86)</pre><p>But non-static methods have to use reference variables to call.</p><pre>Song <strong>s</strong> = new Song();<br><strong>s.play(); </strong>// assume play() is a non-static method</pre><ul><li>Static variables are shared.</li><li>All instances of the same class share a single copy of the static variables.</li><li>All static variables in a class are initialized before any object of that class can be created.</li></ul><h4>Static Final Variables</h4><p>A variable marked final means that once initialized it can never change. In other words, the value of the static final variable will stay the same as long as the class is loaded.</p><pre>public <strong>static fina</strong>l double PI = 3.141592653589793;</pre><h4>Initializing a final static variable</h4><ul><li>At the time you declare</li></ul><pre>public class Foo{</pre><pre><strong>public static final int FOO_X = 25;</strong><br>}</pre><p>static final variables are constants so the name should be all uppercase with an underscore seperating the words.</p><ul><li>In a static initializer</li></ul><pre>public class Bar{</pre><pre><strong>public static final double BAR_SIGN;</strong></pre><pre><strong>static</strong>{</pre><pre><strong>BAR_SIGN = (double) Math.random();</strong><br>}<br>}</pre><p>Above code runs as soon as the class is loaded.</p><ul><li>Final variable means you can’t change its value.</li></ul><pre>class Foof{</pre><pre>fint int size = 3; // can&#39;t change value<br>}</pre><ul><li>Final method means you can’t override the method.</li></ul><pre>class Poof{</pre><pre>final void calcWhuffle(){</pre><pre>// must never overridden<br>}<br>}</pre><ul><li>Final class means you can’t extend the class. (can’t make subclass).</li></ul><pre>final class Bee{</pre><pre>//cannot be extended<br>}</pre><h4>Math methods</h4><ul><li><strong>Math.random()</strong></li></ul><p>Returns a double between 0.0 through 1.0</p><pre>double r1 = <strong>Math.random();</strong></pre><ul><li><strong>Math.abs()</strong></li></ul><p>Returns a double that is the absolute value of the argument.</p><pre>int x = <strong>Math.abs(-240)</strong> // returns 240</pre><ul><li><strong>Math.round()</strong></li></ul><p>Returns an int or a long rounded to the nearest integer value.</p><pre>int x = <strong>Math.round(-24.8f)</strong> // returns -25</pre><ul><li><strong>Math.min()</strong></li></ul><p>Returns a value that is the minimum of the two arguments.</p><pre>int x = <strong>Math.min(24,240)</strong> // returns 24</pre><ul><li>Math.max()</li></ul><p>Returns a value that is the maximum of the two arguments.</p><pre>int x = <strong>Math.max(24,240)</strong> // returns 240</pre><h4>Wrapping a primitive</h4><p>Sometimes you want to treat a primitive like an object. There’s a wrapper class for every primitive type. You will need this when you want to store a primitive value inside a collection like ArrayList or HashMap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*X1lotvx2rGJGXjRKQtTVwQ.png" /></figure><pre>int i = 288;<br><strong>Integer </strong>integerWrap = new Integer(i);</pre><h4>Unwrapping a value</h4><pre>int unWrap = integerWrap.<strong>intValue();</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b4d2206141b" 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/@gihantharaka76/head-first-java-chapter-09-life-and-death-of-an-object-ac2e3ead09af?source=rss-78ad2dabcbcd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac2e3ead09af</guid>
            <category><![CDATA[head-first-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Gihan Wijesinghe]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 11:28:46 GMT</pubDate>
            <atom:updated>2022-07-18T11:28:46.802Z</atom:updated>
            <content:encoded><![CDATA[<p>As you know, in Java there a two <strong>areas of memory</strong>.</p><ol><li><strong>Heap</strong> - This is the place where all objects live.</li><li><strong>Stack</strong> - This is the place where method invocations and local variables live.</li></ol><p>So the heap is also known as <strong>garbage-collectible heap</strong>. Local variables are also known as <strong>stack variables</strong>.</p><h4>Instance Variables</h4><p>Instance variables are declared inside a class but not inside a method.</p><pre>public class Duck{</pre><pre><strong>int size;</strong><br>}</pre><h4>Local Variables</h4><p>Local variables are declared inside a method, including method parameters.</p><pre>public void foo(<strong>int x</strong>){</pre><pre><strong>int i</strong> = x + 3;</pre><pre><strong>boolean b</strong> = true;<br>}</pre><p>int x, int i and boolean b are local variables in the above code block.</p><h4>Contructor</h4><p>Do you remember the steps of how we create an object?</p><ol><li>declare a reference variable. (<strong>Duck myDuck</strong>)</li><li>creating the object. (<strong>new Duck();</strong>)</li><li>assign the object to the reference. (<strong>=</strong>)</li></ol><pre>Duck myDuck = new Duck();</pre><p>As you can see in the above second step, it seems like we are calling a method names Duck() because of the parentheses. <strong>NO! </strong>we are calling the Duck contructor.</p><p>So, constructor is the code that runs when you instantiate an object. Every class you create has a constructor even if you don’t write it on your code. If you don’t write a constructor, the compiler writes one for you.</p><pre>public class Duck{</pre><pre><strong>public Duck(){</strong></pre><pre><strong>}</strong></pre><pre>}</pre><p>constructors has the same name as the class name and it does not have a return type.</p><p>If you have more than one constructor in a class it is called <strong>overloaded constructors</strong>.</p><pre>public class Duck{</pre><pre><strong>public Duck(){}</strong></pre><pre><strong>public Duck(int size){}</strong></pre><pre><strong>public Duck(String name){}</strong></pre><pre><strong>public Duck(String name, int size){}</strong><br>}</pre><h4>How do you invoke a superclass constructor?</h4><p>The only way to call a super constructor is by calling super(). Assume you have Duck class which has superclass of Animal. Before you calling the constructor of subclass you have to call its superclass constructor first. super() is always a no argument call and super() must be the first statement of each constructor as well.</p><pre>public class Duck <strong>extends</strong> Animal{<br>int size;</pre><pre><strong>public Duck(int newSize){</strong></pre><pre><strong>super();</strong></pre><pre>size = newSize;<br><strong>}</strong></pre><pre>}</pre><h4>Three ways to get rid of an object’s reference</h4><ul><li>Reference goes out of scope, permanently. Reference dies at the end of the method.</li></ul><pre><strong>void go(){</strong></pre><pre>Life z = new Life();<br><strong>}</strong></pre><ul><li>Reference is assigned to another object. First object is abandoned when ‘z’ is programmed to a new object.</li></ul><pre>Life z = new Life();<br><strong>z = new Life();</strong></pre><ul><li>Reference is explicitly set to null. First object is abandoned when ‘z’ is assigned to null.</li></ul><pre>Life z = new Life();<br><strong>z = null;</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac2e3ead09af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>