<?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 Bhagya Devduni on Medium]]></title>
        <description><![CDATA[Stories by Bhagya Devduni on Medium]]></description>
        <link>https://medium.com/@bhagya.devduni98?source=rss-d3c81c4b57c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4tUm3SsvcTDoZiYuU_nyVA.png</url>
            <title>Stories by Bhagya Devduni on Medium</title>
            <link>https://medium.com/@bhagya.devduni98?source=rss-d3c81c4b57c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:34:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhagya.devduni98/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 Summary -Distributed Computing]]></title>
            <link>https://medium.com/@bhagya.devduni98/head-first-java-chapter-18-summary-distributed-computing-8aaf0ae1513?source=rss-d3c81c4b57c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aaf0ae1513</guid>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Bhagya Devduni]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 18:57:01 GMT</pubDate>
            <atom:updated>2022-07-18T18:57:01.771Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is to highlight the main points include in the chapter18.</p><p><strong>Java Remote Method Invocation(RMI)</strong></p><p>Create client and server applications and the server application is the remote service that has an object with the method that the client wants to invoke. ‘Helpers’ handle all the low level networking and I/O details. So the client and server can pretend like they’re in the same heap.</p><p>The ‘helpers’ are the objects that actually do the communicating. They make it possible for the client to act as though it’s calling a method on a local object. In fact, it is. The client calls a method on the client helper, as <em>if the client helper were the actual service. The client helper is a proxy for the Real Thing.</em></p><p><strong>How the method call happens</strong>,</p><ol><li>Client object calls doBigThing() on the client helper object</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/0*eCnkfql5WkXjSprd.png" /></figure><p>2.Client helper packages up information about the call (arguments, method name, etc.) and ships it over the network to the service helper</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*UU6Dv8U-Eq6_DQl3.png" /></figure><p>3. 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/700/0*P54SEpONYtrq0l9R.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aaf0ae1513" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Zones(Day light saving , local Date Time , SQL Date Time ,Time API)]]></title>
            <link>https://medium.com/@bhagya.devduni98/time-zones-day-light-saving-local-date-time-sql-date-time-time-api-cef5d6f014d7?source=rss-d3c81c4b57c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cef5d6f014d7</guid>
            <category><![CDATA[timezone]]></category>
            <dc:creator><![CDATA[Bhagya Devduni]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 18:09:44 GMT</pubDate>
            <atom:updated>2022-07-18T18:50:04.502Z</atom:updated>
            <content:encoded><![CDATA[<h3>Time Zones(Day light saving , local Date Time , SQL Date Time ,Time API)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*khJaxIdw5DNZ9KRQ.jpeg" /></figure><h3>Time zone</h3><p>A time zone is an area that observes a uniform standard time for legal, commercial and social purposes. Time zones tend to follow the boundaries between countries and their subdivisions instead of strictly following longitude, because it is convenient for areas in frequent communication to keep the same time.</p><p>The universal time standard (UTC) is used all over the world.<br>The world’s timing centers have decided to keep their time scales closely synchronized — or coordinated, as the names indicate. Greenwich Mean Time (GMT) is often interchanged or confused with Coordinated Universal Time (UTC). But GMT is a time zone and UTC is a time standard.</p><p>The UTC offset is the difference in hours and minutes from Coordinated Universal Time(UTC) for a particular place and date.</p><p>When we talking about this topic there some other aspects to consider.</p><ol><li>Daylight saving</li><li>Local Date Time</li><li>SQL date time</li><li>Time API</li></ol><h3>Day Light Saving Time (DST)</h3><p>DST, also known as daylight savings time or daylight time in the United States and Canada, and summer time in the United Kingdom, European Union, and other countries, is the tradition of advancing clocks (typically by one hour) during warmer months such that night occurs at a later clock time. The typical implementation of DST is to set clocks forward by one hour in the spring (“spring forward”) and set clocks back by one hour in autumn (“fall back”) to return to standard time. As a result, there is one 23-hour day in late winter or early spring and one 25-hour day in the autumn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bLf1UozZQZ_NJKS4.jpg" /></figure><h3>Local Date Time</h3><p>LocalDateTime is an immutable date-time object that represents a date, which is frequently expressed in the format year-month-day-hour-minute-second. Day-of-year, day-of-week, and week-of-year are among the other date and time parameters that may be retrieved. Nanosecond precision is used to express time. A LocalDateTime can be used to hold the value “11th June 2022 at 15:25.20.123456789.” A time zone is not stored or represented in this class. Instead, it’s a combination of the date (as seen on a wall clock) and the local time (as shown on a calendar). Without additional information such as an offset or time-zone, it cannot represent a point in time on the timeline.</p><h3>SQL date time</h3><p>Most of database support three forms of datetime fields which are DATE, TIME and TIMESTAMP. Each of these have a corresponding class in JDBC and each of them extend <a href="https://www.dariawan.com/tutorials/java/java-date-examples/"><strong>java.util.Date</strong></a>. These three are:</p><ul><li><a href="https://www.dariawan.com/tutorials/java/java-sql-date-examples/"><strong>java.sql.Date</strong></a></li></ul><p><strong>A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value</strong>. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. To conform with the definition of SQL DATE , the millisecond values wrapped by a java.</p><ul><li><a href="https://www.dariawan.com/tutorials/java/java-sql-time-examples/"><strong>java.sql.Time</strong></a></li></ul><p>This class is <strong>a thin wrapper around java.</strong> <strong>util.</strong> <strong>Date that allows JDBC to identify this as a SQL TIME value</strong>. It adds formatting and parsing operations to support the JDBC escape syntax for time values. Time(int, int, int) Construct a Time Object Time(long) Construct a Time using a milliseconds time value.</p><ul><li><a href="https://www.dariawan.com/tutorials/java/java-sql-timestamp-examples/"><strong>java.sql.Timestamp</strong></a></li></ul><p>The <strong>getTime()</strong> function is a part of Timestamp class of Java SQL.The function is used to get the time of the Timestamp object. The function returns time in milliseconds which represents the time in milliseconds after 1st January 1970.</p><p><strong>Function Signature:</strong></p><pre>public long getTime()</pre><p><strong>Syntax:</strong></p><pre>ts1.getTime();</pre><h3>Time API</h3><p>The Date-Time APIs, introduced in JDK 8, are a set of packages that model the most important aspects of date and time. The core classes in the java.time package use the calendar system defined in ISO-8601 (based on the Gregorian calendar system) as the default calendar. Other non-ISO calendar systems can be represented using the java.time.chrono package and several predefined chronologies, such as Hijrah and Thai Buddhist are provided.</p><p><strong>Classical Date Time API Classes</strong></p><p>The primary classes before Java 8 release were:</p><p><strong>Java.lang.System:</strong> The class provides the currentTimeMillis() method that returns the current time in milliseconds. It shows the current date and time in milliseconds from January 1st 1970.</p><p><strong>java.util.Date:</strong> It is used to show specific instant of time, with unit of millisecond.</p><p><strong>java.util.Calendar:</strong> It is an abstract class that provides methods for converting between instances and manipulating the calendar fields in different ways.</p><p><strong>java.text.SimpleDateFormat:</strong> It is a class that is used to format and parse the dates in a predefined manner or user defined pattern.</p><p><strong>java.util.TimeZone:</strong> It represents a time zone offset, and also figures out daylight savings.</p><h3>Drawbacks of existing Date/Time API’s</h3><ol><li><strong>Thread safety:</strong> The existing classes such as Date and Calendar does not provide thread safety. Hence it leads to hard-to-debug concurrency issues that are needed to be taken care by developers. The new Date and Time APIs of Java 8 provide thread safety and are immutable, hence avoiding the concurrency issue from developers.</li><li><strong>Bad API designing:</strong> The classic Date and Calendar APIs does not provide methods to perform basic day-to-day functionalities. The Date and Time classes introduced in Java 8 are ISO-centric and provides number of different methods for performing operations regarding date, time, duration and periods.</li><li><strong>Difficult time zone handling:</strong> To handle the time-zone using classic Date and Calendar classes is difficult because the developers were supposed to write the logic for it. With the new APIs, the time-zone handling can be easily done with Local and ZonedDate/Time APIs.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cef5d6f014d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java Chapter 17 Summary -package, jars and deployment]]></title>
            <link>https://medium.com/@bhagya.devduni98/head-first-java-chapter-17-summary-package-jars-and-deployment-2ec2b0fca52f?source=rss-d3c81c4b57c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ec2b0fca52f</guid>
            <dc:creator><![CDATA[Bhagya Devduni]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 15:00:56 GMT</pubDate>
            <atom:updated>2022-07-18T15:00:56.645Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Deploying your application</strong></p><p>A Java program is a bunch of classes. That’s the output of your development. The real question is what to do with those classes when you’re done.</p><p>Once you’re done with development, what is it that you deliver? Chances are, your end-users don’t have a system identical to yours. More importantly, they don’t have your application. So now it’s time to get your program in shape for deployment into The Outside World. In this chapter, we’ll look at local deployments, including Executable Jars and the part-local/part-remote technology called Java Web Start. In the next chapter, we’ll look at the more remote deployment options, including RMI and Servlets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/0*-Tlp6nJrQNtnz-gO.jpeg" /></figure><ol><li><strong>Local : </strong>The entire application runs on the end-user’s computer, as a stand-alone, probably GUI, program, deployed as an executable JAR.</li><li><strong>Combination of local and remote : </strong>The application is distributed with a client portion running on the user’s local system, connected to a server where other parts of the application are running.</li><li><strong>Remote: </strong>The entire Java application runs on a server system, with the client accessing the system through some non-Java means, probably a web browser.</li></ol><p><strong>Separate source code and class files</strong></p><p>create a project directory, and inside that you create a directory called source and a directory called classes. You start by saving your source code (.java files) into the source directory. Then the trick is to compile your code in such a way that the output (the .class files) ends up in the classes directory. And there’s a nice compiler flag, -d, that lets you do that</p><p><strong>Compiling with the -d (directory) flag</strong></p><pre>%cd MyProject/source <br>%javac -d ../classes MyApp.java</pre><ul><li>- d →tells the compiler to put the compiled code into classes directory</li><li>MyApp.java → the last thing is still the name of the java file to compile</li></ul><p>*To compile all the <strong>.java</strong> files in the source directory, use:</p><pre>%javac -d ../classes *.java// *.java compiles ALL  source files in the  current directory</pre><p><strong>Put your Java in a JAR</strong></p><p>A JAR file is a Java ARchive. It’s 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. If you’re familiar with the tar command on UNIX, you’ll recognize the jar tool commands. (Note: when we say JAR in all caps, we’re referring to the archive file. When we use lowercase, we’re referring to the jar tool you use to create JAR files.)</p><p>An executable JAR means the end-user doesn’t have to pull the class files out before running the program. The user can run the app while the class files are still in the JAR. The trick is to create a manifest file, that goes in the JAR and holds information about the files in the JAR. To make a JAR executable, the manifest must tell the JVM which class has the main() method!</p><p>Making an executable JAR,</p><ol><li>Make sure all of your class files are in the <strong>classes</strong> directory</li><li>Create a manifest.txt file that states which class has the main() method</li><li>Run the jar tool to create a JAR file that contains everything in the classes directory, plus the manifest.</li></ol><pre>%cd MyProject/classes <br>%jar -cvmf manifest.txt app1.jar *.class <br>OR <br>%jar -cvmf manifest.txt app1.jar MyApp.class</pre><p><strong>Running (executing) the JAR</strong></p><p>Java (the JVM) is capable of loading a class from a JAR, and calling the main() method of that 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.</p><p><strong>Put your classes in packages</strong></p><p>When organize classes into packages but prevents naming collisions with other classes. To put a class into a package need to put the package statement at the first line of the source code file. Do not use import or class declaration before the package statement.</p><p>Class must be in a directory structure which should exactly match the package when to be in a package. eg: if the class name is MyApplication that class should be in the directory of exampleApplication which is in the directory named com. We can use the -d compiler flag to make compiled class located in the correct package directory structure.</p><p><strong>Packages prevent class name conflicts</strong></p><p>When organize classes into packages but prevents naming collisions with other classes. To put a class into a package need to put the package statement at the first line of the source code file. Do not use import or class declaration before the package statement.</p><p>Class must be in a directory structure which should exactly match the package when to be in a package. eg: if the class name is MyApplication that class should be in the directory of exampleApplication which is in the directory named com. We can use the -d compiler flag to make compiled class located in the correct package directory structure.</p><p><strong>Preventing package name conflicts</strong></p><p>Putting your class in a package reduces the chances of naming conflicts with other classes, but what’s to stop two programmers from coming up with identical package names? In other words, what’s to stop two programmers, each with a class named Account, from putting the class in a package named shopping. Customers? Both classes, in that case, would still have the same name: shopping.customers. Account Sun strongly suggests a package naming convention that greatly reduces that risk — prepend every class with your reverse domain name. Remember, domain names are guaranteed to be unique. Two different guys can be named Bartholomew Simpson, but two different domains cannot be named doh.com.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*J93lhl9PIQK2cAuw0G4uIg.png" /></figure><p>To put your class in a package,</p><ol><li>Choose a package name</li><li>Put a package statement in your class</li><li>Set up a matching directory structure</li></ol><p>We must put a class into a directory structure that matches the package hierarchy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/0*Jgvv6jlw0815k2kD.jpeg" /></figure><p><strong>Compiling and running with packages</strong></p><p>When a class is in a package, it’s a little trickier to compile and run. The main problem is that both the compiler and JVM have to be capable of finding the class and all of the other classes it uses. For the classes in the core API, that’s never a problem. Java always knows where its own stuff is. But for our classes, the solution of compiling from the same directory where the source files are simply won’t work .</p><p><strong>Compiling with the -d (directory) flag</strong></p><pre><strong>%cd MyProject/source</strong></pre><p>Stay in the source directory. Do NOT cd down into the directory where the .java file is.</p><pre>%javac -d ../classes com/headfirstjava/PackageExercise.java</pre><ul><li>-d →tells the compiler to put the compiled code (class files) into the classes directory, within the right package structure</li><li>com/headfirstjava → specify the PATH to get to the actual source file</li></ul><p>To compile all the .java files in the com.headfirstjava package, use:</p><pre>%javac -d ../classes com/headfirstjava/*.java</pre><ul><li>.java → compiles every source (.java) file in this directory</li></ul><p><strong>Making an executable JAR with package</strong></p><p>When your class is in a package, 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. The first directory of your package (usually com) must be the first directory within the JAR! If you were to accidentally include the directory above the package (e.g. the “classes” directory), the JAR wouldn’t work correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*Zj0w5BklY00AZy-wLZBBpw.png" /></figure><p><strong>Jar commands for listing and extracting</strong></p><ol><li>List the contents of a JAR</li></ol><pre>% jar -tf packEx.jar</pre><ul><li>-tf stands for ‘Table File’</li></ul><p>2.Extract the contents of a JAR (i.e. unjar)</p><pre>% cd Skyler <br>% jar -xf packEx.jar</pre><ul><li>-xf stands for ‘Extract File’ and it works like unzipping or untiring. Ifwe extract the packEx.jar, we can see the META-INF directory and the com directory in the current directory.</li></ul><h3>Java Web Starts</h3><p>Using JWS we can launch our application from a web browser. But it runs as a stand-alone application without the constraints of the browser. JWS includes a helper app so it must be installed on the client. And JWS app has two parts, one piece is an executable JAR and the other one is a .jnlp file.</p><p>End-users launch a Java Web Start app by clicking on a link in a Web page. But once the app downloads, it runs outside the browser, like any other stand-alone Java application. In fact, a Java Web Start app is just an executable JAR that’s distributed over the Web.</p><p>How Java Web Start works,</p><ol><li>The client clicks on a Web page link to your JWS application (a .jnlp file).</li></ol><pre>&lt;a href=&quot;MyApp.jnlp&quot;&gt;Click&lt;/a&gt;</pre><p>2.The Web server (HTTP) gets the request and sends back a .jnlp file (this is NOT the JAR) :</p><ul><li>The .jnlp file is an XML document that states the name of the application’s executable JAR file.</li></ul><p>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.</p><p>4.The Web server ‘serves’ up the requested .jar file</p><p>5.Java Web Start gets the JAR and starts the application by calling the specified main( ) method (just like an executable JAR)</p><p><strong>The .jnlp file</strong></p><p>To make a Java Web Start app, we need to create a .jnlp (Java Network Launch Protocol) file that describes the application. This is the file the JWS app reads and uses to find your JAR and launch the app (by calling the JAR’s main() method).A.jnlp file is a simple XML document that can contain a variety of things, but at the very least.</p><h3>Bullet Points</h3><ul><li>A standard organization structure is to create a project directory, and then put a source directory and a classes directory inside the project directory.</li><li>Organizing your classes into packages prevents naming collisions with other classes, if you prepend your reverse domain name on to the front of a class name.</li><li>To put a class in a package, put a package statement at the top of the source code file, before any import statements: package com.wickedlysmart;</li><li>To be in a package, a class must be in a directory structure that exactly matches the package structure. For a class, com.wickedlysmart.Foo, the Foo class must be in a directory named wickedlysmart, which is in a directory named com.</li><li>To make your compiled class land in the correct package directory structure under the classes directory, use the -d compiler flag: % cd source % javac -d ../classes com/wickedlysmart/Foo.java</li><li>To run your code, cd to the classes directory, and give the fully-qualified name of your class: % cd classes % java com.wickedlysmart.Foo</li><li>You can bundle your classes into JAR (Java ARchive) files. JAR is based on the pkzip format.</li><li>You can make an executable JAR file by putting a manifest into the JAR that states which class has the main() method. To create a manifest file, make a text file with an entry like the following (for example): Main-Class: com.wickedlysmart.Foo</li><li>Be sure you hit the return key after typing the Main-Class line, or your manifest file may not work.</li><li>To create a JAR file, type: jar -cvfm manifest.txt MyJar.jar com</li><li>The entire package directory structure (and only the directories matching the package) must be immediately inside the JAR file.</li><li>To run an executable JAR file, type: java -jar MyJar.jar</li><li>Java Web Start technology lets you deploy a stand-alone client application from the Web.</li><li>Java Web Start includes a ‘helper app’ that must be installed on the client (along with Java).</li><li>A Java Web Start (JWS) app has two pieces: an executable JAR and a .jnlp file.</li><li>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.</li><li>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.</li><li>The JWS helper app reads the .jnlp file and requests the executable JAR from the Web server.</li><li>When the JWS gets the JAR, it invokes the main() method (specified in the .jnlp file).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ec2b0fca52f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java Chapter 16 Summary -Data Structures]]></title>
            <link>https://medium.com/@bhagya.devduni98/head-first-java-chapter-16-summary-data-structures-270392472b13?source=rss-d3c81c4b57c------2</link>
            <guid isPermaLink="false">https://medium.com/p/270392472b13</guid>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Bhagya Devduni]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 14:46:11 GMT</pubDate>
            <atom:updated>2022-07-18T14:46:11.729Z</atom:updated>
            <content:encoded><![CDATA[<p>ArrayList is not the only collection</p><p>Although ArrayList is the one you’ll use most often, there are others for special occasions. Some of the key collection classes include:</p><ul><li><em>TreeSet</em> : Keeps the elements sorted and avoid duplicates.</li><li><em>HashMap :</em> Allows you to store and access elements as name/value pairs.</li><li><em>LinkedList </em>: Makes it easy to create structures like stacks or queues.</li><li><em>HashSet</em> :Avoid duplicates in the collection, and given an element, can find that element in the collection quickly.</li><li><em>LinkedHashMap</em> : Like a regular HashMap, except it can remember the order in which elements (name/value pairs) were inserted, or it can be configured to remember the order in which elements were last accessed.</li></ul><p><strong>Collection.sort() Method</strong></p><p>The Java.util.Collections class includes a method called Collections.sort().It is used to sort the elements present in the specified list of Collection in ascending order. The Collections.sort() method sorts a list of Strings alphabetically.</p><p><strong>Sorting Objects</strong></p><p>Let’s assume we want actual class instances in the list, not just Strings, so that each instance can have more data.</p><p><strong>The sort() method declaration</strong></p><p>From the API docs (looking up the java.util.Collections class, and scrolling to the sort() method), it looks like the sort() method is declared… strangely. Or at least different from anything we’ve seen so far. That’s because the sort() method (along with other things in the whole collection framework in Java) makes heavy use of generics. Anytime you see something with angle brackets in Java source code or documentation, it means generics — a feature added to Java 5.0. So it looks like we’ll have to learn how to interpret the documentation before we can figure out why we were able to sort String objects in an ArrayList, but not an ArrayList of Song objects</p><h3>Generics</h3><p>The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code by finding the bugs during compilation .. Before generics, we can store any type of objects in the collection and With generics, you can create type-safe collections where more problems are caught at compile-time instead of runtime.</p><ul><li>Generics means more type-safety.</li><li>With generics, we can create type-safe collections where more problems are caught at compile-time instead of runtime.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/0*7BSeHVOw3vO6ZJLt.png" /></figure><ul><li>And also, without generics, the compiler would let us put into an ArrayList that was supposed to hold only the objects.</li><li>Now with generics, we can put only Fish objects in the ArrayList, so the objects come out as Fish references. we don’t need to worry about someone sticking a Volkswagen in there, or that what we get out won’t really be cast-able to a Fish reference.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/0*hP9UQOMHYJL_Hr00.jpeg" /></figure><p><strong>Learning generics</strong></p><p>Of the dozens of things you could learn about generics, there are really only three that matter to most programmers.</p><p>1.Creating instances of generified <strong>classes</strong> (like ArrayList)</p><pre>new ArrayList&lt;Song&gt; ()</pre><ul><li>When creating an ArrayList, need to tell it the type of objects that allow in the list, like we do with plain old arrays.</li></ul><p>2.Declaring and assigning <strong>variables</strong> of generic types</p><pre>List&lt;Song&gt; songList = <strong>new</strong> ArrayList&lt;Song&gt;();</pre><p>3.Declaring (and invoking) <strong>methods</strong> that take generic types.</p><pre><strong>void</strong> foo(List&lt;Song&gt; list);<br>x.foo(songList);</pre><p>If you have a method that takes as a parameter, say, an ArrayList of Animal objects, what does that really mean? Can you also pass it an ArrayList of Dog objects? We’ll look at some subtle and tricky polymorphism issues that are very different from the way you write methods that take plain old arrays.</p><p><strong>But don’t I also need to learn how to create my OWN generic classes? What if I want to make a class type that lets people instantiating the class decide the type of things that class will use?</strong></p><p>You probably won’t do much of that. Think about it — the API designers made an entire library of collections classes covering most of the data structures you’d need, and virtually the only type of classes that really need to be generic are collection classes. In other words, classes designed to hold other elements, and you want programmers using it to specify what type those elements are when they declare and instantiate the collection class. Yes, it is possible that you might want to create generic classes, but that’s the exception.</p><p><strong>Using generic CLASSES</strong></p><p>Since ArrayList is our most-used generified type, we’ll start by looking at its documentation. The two key areas to look at in a generified class are:</p><ol><li>The class declaration</li><li>The method declarations that let you add elements.</li></ol><p>Think of “E” as a stand-in for “the type of element you want this collection to hold and return.” (E is for Element.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*Jtt1t9kCzY9tA2b970fYOA.png" /></figure><p><strong>Generic Methods</strong></p><p>We can develop a generic method that will accept any type of arguments, just like the generic class. A generic class is one that has a type parameter in the class definition. A generic method is one that includes a type parameter in its signature in the method declaration.</p><p>we can use type parameters in a method in different ways,</p><ol><li>Using a type parameter defined in the class declaration</li></ol><pre>public class ArrayList&lt;<strong>E</strong>&gt; extends AbstractList&lt;E&gt; ... {<br>       public boolean add(<strong><em>E</em></strong> o)  // we can use the “<strong><em>E</em></strong>” here ONLY because it’s already defined as part of the class</pre><ul><li>When declare a type parameter for the class, can simply use that type any place that we ’d use a real class or interface type. The type declared in the method argument is essentially replaced with the type we use when we instantiate the class</li></ul><p>2.Using a type parameter that was NOT defined in the class declaration</p><pre>public &lt;T extends Animals&gt; void takeThink(ArrayList&lt;<strong><em>T</em></strong>&gt; list)<br>//can use “<strong><em>T</em></strong>” because we declared  “<strong><em>T</em></strong>” earlier in the method declaration</pre><ul><li>When the class itself doesn’t use a type parameter, can still specify one for a method, by declaring it in a really unusual ) space before the return type.</li></ul><p>but here where it gets weired,</p><pre>public &lt;T extends Animals&gt; void takeThink(ArrayList&lt;<strong><em>T</em></strong>&gt; list)</pre><p>and</p><pre>public void takeThing(ArrayList list)</pre><p>is not same. Both are legal, but they’re different.</p><ul><li><strong>&lt;T extends Animal&gt;</strong> is part of the method declaration, which means,any ArrayList declared of a type that is Animal, or one of Animal’s sub type is legal.</li><li><strong>public</strong> <strong>void</strong> takeThing(ArrayList&lt;Animal&gt; list);This method argument only an <strong>ArrayList&lt;Animal&gt;</strong> is legal and not sub type.</li><li>When you declare a method to take ArrayList&lt;Animal&gt; it can only take an ArrayList&lt;Animal&gt;, not ArrayList&lt;Dog&gt;.</li></ul><p><strong>*Generic Extends or Implements</strong></p><p>In generics, keyword “extends” means “extends or implements”. The keyword “extends” really means “is-a”, and works for BOTH classes and interfaces.</p><p><strong>We need a Set instead of a List</strong></p><p>From the Collection API, we find three main interfaces, <strong>List, Set,</strong> and <strong>Map</strong>. ArrayList is a List, but it looks like Set is exactly what we need.</p><ol><li><strong>LIST:</strong> <strong>when sequence matters</strong></li></ol><p>Collections knowledgeable about the <strong>index position</strong>. Lists are aware of where each item is located. More than one element may refer to the same thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/0*xAp-zmc_ovS6vQKt.jpeg" /></figure><p>2.<strong>SET — when uniqueness matters</strong></p><p>collections that <strong>prohibit duplication. </strong>Sets know whether something is already in the collection. You can never have more than one element referencing the same object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/0*FG8c2bzoKoLW10gO.jpeg" /></figure><p><strong>3.MAP — when finding something by key matters</strong></p><p>Collections that use <strong>key-value pairs. </strong>Maps know the value associated with a given key. Cannot have duplicate keys but can have two keys that reference the same value,. Although keys are typically String names a key can be any object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*u6R0l_hB9azExGsb.jpeg" /></figure><p><strong>The Collection API</strong></p><p>Notice that the Map interface doesn’t actually extend the Collection interface, but Map is still considered part of the “Collection Framework” (also known as the “Collection API”). So 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/700/0*M1L-Q4uyStUjHyQL.jpeg" /></figure><p><strong><em>Map Interface</em></strong></p><ul><li>Maps don’t extend from java.util.Collection, but they’re still considered to be part of the “collections framework” in Java. So a Map is still referred to as a collection.</li></ul><p><strong><em>HashSet</em></strong></p><ul><li>Set Interface is implemented by HashSet class. it represents the collection that uses a hash table for storage. The elements of the HashSet are stored using hashing and it contains unique items. And also A HashSet checks the hasCodes, if the hashcodes are different the HashSet assumes there’s no way the objects can be equal.</li></ul><pre>HashSet songSet = new HashSet();  <br>songSet.addAll(songList);  <br>System.out.println(songSet);</pre><p>Here we create a new HashSet parameterized to hold Songs. And HashSet has a simple addAll() method that can take another collection and use it to populate the HashSet. It’s the same as if we added each song one at a time.</p><p><strong><em>TreeSet</em></strong></p><ul><li>Java TreeSet class implements the Set interface that uses a tree for storage. A TreeSet is similar to HashSet in that it prevents duplicates, and it also keeps the list sorted. To use a TreeSet, one of these things must be true,</li></ul><ol><li>The elements in the list must be of a type that implements <strong>Comparable</strong></li></ol><p>OR</p><p>2.Use the TreeSet’s overloaded constructor that takes a <strong>Comparator</strong></p><pre>TreeSet songSet = new TreeSet(); <br>songSet.addAll(songList);</pre><p>Instantiate a TreeSet instead of HashSet. Calling the no-arg TreeSet constructor means the set will use the Song object’s compareTo() method for the sort also can add ll the songs from the HashSet using addAll()</p><p><strong><em>Map</em></strong></p><ul><li>Each element in a Map is actually TWO objects — a key and a value. You can have duplicate values, but NOT duplicate keys.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/0*Z_mhoeqyYQSpTzcp.jpeg" /></figure><h3>Generic Wildcards</h3><p>The<strong> </strong>question mark <strong>(?)</strong> is known as the<strong> wildcard</strong> in generic programming. It represents an unknown type. The wildcard can be used in a number of contexts, including to specify the type of a parameter, field, or local variable, as well as occasionally as a return type.There is a way a method argument that can accept an ArrayList of any Animal sub type.</p><pre><strong>public</strong> <strong>void</strong> takeAnimal(ArrayList &lt;? <strong>extends</strong> Animal&gt; animals){<br>   <strong>for</strong> (Animal animal : animals) {<br>     animal.eat();<br>    }<br>}</pre><p>OR</p><pre><strong>public</strong> &lt;T <strong>extends</strong> Animal&gt;<strong>void</strong> takeAnimal(ArrayList &lt;T&gt; animals){<br>    <strong>for</strong> (Animal animal : animals) {<br>        animal.eat();<br>    }<br> }</pre><p>When we use a wild card in a method argument, the compiler will STOP from doing anything that could hurt the list referenced by the method parameters. Still invoke methods on the elements in the list, but we cannot add elements to the list.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=270392472b13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java Chapter 15 Summary -Make a Connection]]></title>
            <link>https://medium.com/@bhagya.devduni98/head-first-java-chapter-15-summary-make-a-connection-37d717bb4a02?source=rss-d3c81c4b57c------2</link>
            <guid isPermaLink="false">https://medium.com/p/37d717bb4a02</guid>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Bhagya Devduni]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 14:32:19 GMT</pubDate>
            <atom:updated>2022-07-18T14:32:19.782Z</atom:updated>
            <content:encoded><![CDATA[<p>The purpose of this article is to highlight the key ideas covered in chapter 15.</p><p><strong>Chat Program Overview</strong></p><p>The Client has to know about the Server.</p><p>The Server has to know about ALL the Clients.</p><p><strong>How it Works:</strong></p><ol><li>The client connects to the server</li><li>The server makes a connection and adds the client to the list of participants</li><li>Connects another client</li><li>Client A sends a message to the chat service</li><li>The server distributes the message to ALL participants.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*cgKL9Zeo_VXN52yg.jpeg" /></figure><p><strong>Connecting, Sending, and Receiving</strong></p><p>The three things we have to learn to get the client working are : 1) How to establish the initial connection between the client and server 2) How to send messages to the server 3) How to receive messages from the server There’s a lot of low-level stuff that has to happen for these things to work. But we’re lucky, because the Java API networking package (java.net) makes it a piece of cake for programmers. You’ll see a lot more GUI code than networking and I/O code. And that’s not all. Lurking within the simple chat client is a problem we haven’t faced so far in this book: doing two things at the same time. Establishing a connection is a one-time operation (that either works or fails). But after that, a chat participant wants to send outgoing messages and simultaneously receive incoming messages from the other participants (via the server).</p><p>The three things involved to client working are:</p><p>1. <em>Connection:</em> Client connects to the server by establishing a <strong>Socket</strong> connection.</p><p>2. <em>Send:</em><strong> </strong>The client <strong>sends</strong> a message to the server.</p><p>3. <em>Receive</em><strong>: </strong>The client <strong>gets</strong> a message from the server.</p><p><strong>Make a network Socket connection</strong></p><p>We require a Socket connection in order to connect to another machine. A Socket is an object that represents a network connection between two machines. To make a Socket connection, we need to know two things about the server. They are IP address and the TCP port number. In other words, a Socket connection means the two machines have information about each other, including network location (IP address) and TCP port.</p><pre>Socket socket = new Socket (“196.164.1.103”, 5000);</pre><p>196.164.1.103 → IP address for the server</p><p>5000 → TCP port number</p><p>A TCP port is just a number and 16-bit number that identifies a specific program on the server.</p><p>The TCP port numbers from 0 to 1023 are reserved for well-known services. don’t use them for own server programs.</p><p>As mentioned before we are writing uses port 5000,because picked a number between 1024 and 65535.</p><p>We know that the internet web (HTTP) server runs on port 80. That is a standard. Telnet server running on port 23, FTP running on port 20 ,POP3 mail server running on port 110 are some well-known TCP port numbers for common server applications. Port numbers can be considered as unique identifiers. They represent a logical connection to a certain piece of<br>software running on the server. The server wouldn’t be able to identify which application a client wants to connect to without port numbers.</p><p>We require a Socket connection in order to connect to another machine. A Socket is an object that represents a network connection between two machines. To make a Socket connection, we need to know two things about the server. They are IP address and the TCP port number. In other words, a Socket connection means the two machines have information about each other, including network location (IP address) and TCP port.</p><pre>Socket socket = new Socket (“196.164.1.103”, 5000);</pre><p>*196.164.1.103 → IP address for the server</p><p>*5000 → TCP port number</p><p>*A TCP port is just a number and 16-bit number that identifies a specific program on the server.</p><p>*The TCP port numbers from 0 to 1023 are reserved for well-known services. don’t use them for own server programs.</p><p>*As mentioned before we are writing uses port 5000,because picked a number between 1024 and 65535.</p><p>We know that the internet web (HTTP) server runs on port 80. That is a standard. Telnet server running on port 23, FTP running on port 20 ,POP3 mail server running on port 110 are some well-known TCP port numbers for common server applications. Port numbers can be considered as unique identifiers. They represent a logical connection to a certain piece of<br>software running on the server. The server wouldn’t be able to identify which application a client wants to connect to without port numbers.</p><p><strong>Read Data From a Socket</strong></p><p>We can use BufferReader to read data from a socket.</p><ol><li>Make a Socket connection to the server</li></ol><pre>Socket chatSocket = new Socket(“127.0.0.1”, 5000);</pre><ul><li>127.0.0.1 is the IP address for “localhost”. We can use this when we’re testing the client and server on a single, stand-alone machine. 5000 is the port number of our chat server.</li></ul><p>2. Make an InputStreamReader chained to the Socket’s low-level (connection) input stream.</p><pre>InputStreamReader stream = new <br>                 InputStreamReader(chatSocket.getInputStream());</pre><ul><li>InputStreamReader is a ‘bridge’ between a lowlevel byte stream and a high-level character stream.</li></ul><p>3.Make a BufferedReader and read</p><pre>BufferedReader reader = new BufferedReader(stream);<br>String message = reader.readLine();</pre><ul><li>Chain the BufferedReader to the InputStreamReader(which was chained to the lowlevel connection stream we got from the Socket.)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/0*9NG4s-HgNIZiGxHB.jpeg" /></figure><p><strong>To write data to a Socket, use a PrintWriter</strong></p><p>We didn’t use PrintWriter in the last chapter, we used BufferedWriter. We have a choice here, but when you’re writing one String at a time, PrintWriter is the standard choice. And you’ll recognize the two key methods in PrintWriter, print() and println()! Just like good ol’ 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 PrintWriter chained to the Socket’s low-level (connection) output stream</p><pre>PrintWriter writer = new <br>                      PrintWriter(chatSocket.getOutputStream());</pre><ul><li>PrintWriter acts as its own bridge between character data and the bytes it gets from the Socket’s low-level output stream.</li></ul><p>3. Write (print) something</p><pre>writer.println(“message to send”);<br>writer.print(“another message”);</pre><ul><li>println() adds a new line at the end of what it sends &amp; print() doesn’t add the new line.</li></ul><p><strong>Writing a simple server</strong></p><p>So what’s it take to write a server application? Just a couple of Sockets. Yes, a couple as in two. A ServerSocket, which waits for client requests (when a client makes a new Socket()) and a plain old Socket socket to use for communication with the client.</p><p>How it Works:</p><ol><li>Server application makes a ServerSocket, on a specific port</li></ol><pre>ServerSocket serverSock = new ServerSocket(4242);</pre><ul><li>This starts the server application listening for client requests coming in for port 4242.</li></ul><p>2. Client makes a Socket connection to the server application</p><pre>Socket sock = new Socket(“190.165.1.103”, 4242)</pre><ul><li>Client knows the IP address and port number (published or given to him by whomever configures the server app to be on that port)</li></ul><p>3. Server makes a new Socket to communicate with this client</p><pre>Socket sock = serverSock.accept();</pre><p>The accept() method blocks while it’s waiting for a client Socket connection. When a client tries to connect, the method returns a plain old Socket (on a different port) that knows how to communicate with the client.</p><p><strong>Java has multiple threads but only one Thread class</strong></p><p>A thread is a separate ‘thread of execution’. In other words, a separate call stack. A Thread is a Java class that represents a thread. To make a thread, make a Thread.</p><p>A <strong>thread</strong> is a separate thread of execution. That means a separate call stack. Every Java program starts up a main thread. The thread that puts the main() method on the bottom of the stack. The JVM is responsible for starting the main <strong>thread.</strong></p><p>*A <strong><em>thread</em> </strong>is a separate ‘thread of execution’. In other words, a separate call stack. A <strong><em>Thread</em></strong> is a Java class that represents a <strong><em>thread</em></strong>. To make a <strong><em>thread</em></strong>, make a <strong><em>Thread</em></strong>.</p><ol><li>JVM calls the main() method.</li></ol><pre>public static void main(String[] args) { }</pre><p>2. main( ) starts a new thread. While the new thread is executing, the main thread is temporarily frozen.</p><pre>Runnable r = new MyThreadJob();<br>Thread t = new Thread(r);<br>t.start(); Dog d = new Dog();</pre><p>3.The JVM switches between the new thread (user thread A) and the original main thread, until both threads complete.</p><h3>*How to launch a New Thread</h3><ol><li>Make a Runnable object (the thread’s job)</li></ol><pre>Runnable threadJob = new MyRunnable();</pre><ul><li>Runnable is an interface. A class that implements the Runnable interface, and that class is where you’ll define the work that a thread will perform</li></ul><p>2.Make a Thread object (the worker) and give it a Runnable (the job)</p><pre>Thread myThread = new Thread(threadJob);</pre><ul><li>Pass the new Runnable object to the Thread constructor</li></ul><p>3.Start the Thread</p><pre>myThread.start();</pre><p>Before you call the start() method of the Thread, nothing will happens.</p><h3>*Runnable</h3><p>Java runnable is an interface used to execute code on a concurrent thread. It implemented by any class when we want the instances of that class should be executed by a thread. Runnable is to a Thread what a job is to a worker. A Runnable is the job a thread is supposed to run. A Runnable holds the method that goes on the bottom of the new thread’s stack: run().The Runnable interface defines only one method, public void run().</p><p><strong>The Three States Of a New Thread</strong></p><ol><li><em>New:</em> A Thread instance created but not started yet. In other words, there is a Thread object, but no thread of execution.</li><li><em>Runnable</em>: The thread is ready to run when calling start() method.</li><li><em>Running</em>: When a thread is started.</li></ol><p>*Once the thread becomes runnable, it can move back and forth between runnable, running, and an additional state: temporarily not runnable.</p><p>*A thread can be made temporarily not runnable.</p><h3>* The Thread Scheduler</h3><p>The thread scheduler makes all the decisions about who runs and who doesn’t. He usually makes the threads take turns, nicely. We can’t control the scheduler and also there is no API for calling methods on the scheduler. Most important point is, there are no guarantees about scheduling. He might let one thread run to its heart’s content while the other threads ‘starve’.</p><p><strong>*Sleep() Method</strong></p><p>One of the best ways to help the threads take turns is to put them to sleep periodically. All you need to do is call the static sleep() method, passing it the sleep duration, in milliseconds. Put The thread to sleep if want to be sure that other threads get a chance to run. When the thread wakes up, it always goes back to the runnable state and waits for the thread scheduler to choose it to run again.</p><p>A <strong>thread</strong> is a separate thread of execution. That means a separate call stack. Every Java program starts up a main thread. The thread that puts the main() method on the bottom of the stack. The JVM is responsible for starting the main <strong>thread.</strong></p><p>*A <strong><em>thread</em> </strong>is a separate ‘thread of execution’. In other words, a separate call stack. A <strong><em>Thread</em></strong> is a Java class that represents a <strong><em>thread</em></strong>. To make a <strong><em>thread</em></strong>, make a <strong><em>Thread</em></strong>.</p><ol><li>JVM calls the main() method.</li></ol><pre>public static void main(String[] args) { }</pre><p>2. main( ) starts a new thread. While the new thread is executing, the main thread is temporarily frozen.</p><pre>Runnable r = new MyThreadJob();<br>Thread t = new Thread(r);<br>t.start(); Dog d = new Dog();</pre><p>3.The JVM switches between the new thread (user thread A) and the original main thread, until both threads complete.</p><h3>*How to launch a New Thread</h3><ol><li>Make a Runnable object (the thread’s job)</li></ol><pre>Runnable threadJob = new MyRunnable();</pre><ul><li>Runnable is an interface. A class that implements the Runnable interface, and that class is where you’ll define the work that a thread will perform</li></ul><p>2.Make a Thread object (the worker) and give it a Runnable (the job)</p><pre>Thread myThread = new Thread(threadJob);</pre><ul><li>Pass the new Runnable object to the Thread constructor</li></ul><p>3.Start the Thread</p><pre>myThread.start();</pre><p>Before you call the start() method of the Thread, nothing will happens.</p><h3>*Runnable</h3><p>Java runnable is an interface used to execute code on a concurrent thread. It implemented by any class when we want the instances of that class should be executed by a thread. Runnable is to a Thread what a job is to a worker. A Runnable is the job a thread is supposed to run. A Runnable holds the method that goes on the bottom of the new thread’s stack: run().The Runnable interface defines only one method, public void run().</p><p><strong>The Three States Of a New Thread</strong></p><ol><li><em>New:</em> A Thread instance created but not started yet. In other words, there is a Thread object, but no thread of execution.</li><li><em>Runnable</em>: The thread is ready to run when calling start() method.</li><li><em>Running</em>: When a thread is started.</li></ol><p>*Once the thread becomes runnable, it can move back and forth between runnable, running, and an additional state: temporarily not runnable.</p><p>*A thread can be made temporarily not runnable.</p><h3>The Thread Scheduler</h3><p>The thread scheduler makes all the decisions about who runs and who doesn’t. He usually makes the threads take turns, nicely. We can’t control the scheduler and also there is no API for calling methods on the scheduler. Most important point is, there are no guarantees about scheduling. He might let one thread run to its heart’s content while the other threads ‘starve’.</p><p><strong>*Sleep() Method</strong></p><p>One of the best ways to help the threads take turns is to put them to sleep periodically. All you need to do is call the static sleep() method, passing it the sleep duration, in milliseconds. Put The thread to sleep if want to be sure that other threads get a chance to run. When the thread wakes up, it always goes back to the runnable state and waits for the thread scheduler to choose it to run again.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37d717bb4a02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java Chapter 14 Summary -Saving Objects]]></title>
            <link>https://medium.com/@bhagya.devduni98/head-first-java-chapter-14-summary-saving-objects-614a46b83fb8?source=rss-d3c81c4b57c------2</link>
            <guid isPermaLink="false">https://medium.com/p/614a46b83fb8</guid>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Bhagya Devduni]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 13:22:04 GMT</pubDate>
            <atom:updated>2022-07-18T13:22:04.054Z</atom:updated>
            <content:encoded><![CDATA[<p>The purpose of this article is to highlight the key ideas covered in chapter 14.</p><h3>Serialization</h3><p>The serialized file is much harder for humans to read, but it’s much easier (and safer) for your program to restore the three objects from serialization than from reading in the object’s variable values that were saved to a text file. For example, imagine all the ways in which you could accidentally read back the values in the wrong order.! The type might become “dust” instead of “Elf”, while the Elf becomes a weapon</p><p><strong>Writing a serialized object to a file</strong></p><ol><li>Make a FileOutputStream</li></ol><pre>FileOutputStream fileStream = new FileOutputStream(“MyGame.ser”);</pre><pre>//If the file “MyGame.ser” doesn’t  exist, it will be created automatically.</pre><pre>//Make a FileOutputStream object. FileOutputStream  knows how to connect to (and create) a file</pre><p>2. Make an ObjectOutputStream</p><pre>ObjectOutputStream os = new ObjectOutputStream(fileStream);</pre><pre>//ObjectOutputStream lets you write objects,  but it can’t directly connect to a file. It  needs to be fed a ‘helper’. This is actually  called ‘chaining’ one stream to another.</pre><p>3. Write the object</p><pre>os.writeObject(characterOne); <br>os.writeObject(characterTwo);<br> os.writeObject(characterThree);</pre><pre>//serializes the objects referenced by characterOne, characterTwo, and characterThree, and  writes them to the file “MyGame.ser”.</pre><p>4. Close the ObjectOutputStream</p><pre>os.close();</pre><pre>//Closing the stream at the top closes the ones  underneath, so the FileOutputStream (and the  file) will close automatically.</pre><p><strong>Data moves in streams from one place to another</strong></p><p>Connection streams represent a connection to a source or destination (file, socket, etc.) while chain streams can’t connect on their own and must be chained to a connection stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*yLnc1F7PzoyD0iZHw8emCA.png" /></figure><p>The Java I/O API has connection streams, that represent connections to destinations and sources such as files or network sockets, and chain streams that work only if chained to other streams. Often, it takes at least two streams hooked together to do something useful — one to represent the connection and another to call methods on. Why two? Because connection streams are usually too low-level. FileOutputStream (a connection stream), for example, has methods for writing bytes. But we don’t want to write bytes! We want to write objects, so we need a higher-level chain stream.</p><p>OK, then why not have just a single stream that does exactly what you want? One that lets you write objects but underneath converts them to bytes? Think good OO. Each class does one thing well. FileOutputStreams write bytes to a file. ObjectOutputStreams turn objects into data that can be written to a stream. So we make a FileOutputStream that lets us write to a file, and we hook an ObjectOutputStream (a chain stream) on the end of it. When we call writeObject() on the ObjectOutputStream, the object gets pumped into the stream and then moves to the FileOutputStream where it ultimately gets written as bytes to a file. The ability to mix and match different combinations of connection and chain streams gives you tremendous flexibility! If you were forced to use only a single stream class, you’d be at the mercy of the API designers, hoping they’d thought of everything you might ever want to do. But with chaining, you can patch together your own custom chains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*sIHDrzhDj-pu9-xE-qY35Q.png" /></figure><p><strong>What really happens to an object when it’s serialized?</strong></p><ol><li>Object on the heap</li></ol><p>Objects on the heap have state — the value of the object’s instance variables. These values make one instance of a class different from another instance of the same class</p><p>2. Object serialized</p><p>Serialized objects save the values of the instance variables, so that an identical instance (object) can be brought back to life on the heap.</p><p>When an object is serialized, all the objects it refers to from instance variables are also serialized. And all the objects those objects refer to are serialized. And all the objects those objects refer to are serialized… and the best part is, it happens automatically</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*p-IRaTryFb04aMNv.jpeg" /></figure><p>Here we can see the Kennel object has a reference to a Dog [] array object and the Dog [] holds references to two Dog objects. Each Dog object holds a String and a Collar object. The collar objects have an int and the String objects have a collection of characters . When we save the Kennel, all of this is saved.</p><p>Serialization saves the entire object graph. All objects referenced by instance variables, starting with the object being serialized.</p><p><strong>If you want your class to be serializable, implement Serializable</strong></p><p>The Serializable interface is known as a marker or tag interface, because the 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. If any superclass of a class is serializable, the subclass is automatically serializable even if the subclass doesn’t explicitly declare implements Serializable. (This is how interfaces always work. If your superclass “IS-A” Serializable, you are too).</p><pre>objectOutputStream.writeObject(myBox);</pre><pre>// Whatever goes here MUST implement  Serializable or it will fail at runtime</pre><p>Whatever goes here MUST implement Serializable or it will fail at runtime.</p><p>Let’s look at an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26b19ceaaac39644e989980bcfbbe95a/href">https://medium.com/media/26b19ceaaac39644e989980bcfbbe95a/href</a></iframe><p><strong>Mark an instance variable as transient if it can’t (or shouldn’t) be saved.</strong></p><p>If you want an instance variable to be skipped by the serialization process, mark the variable with the transient keyword.</p><pre>import java.net.*; <br>class Chat implements Serializable {  <br>   transient String currentID;    <br>String userName;  </pre><pre>// more code <br>}<br>//transient says, “don’t  save this variable during  serialization, just skip it</pre><pre>//userName variable  will be saved as part  of the object’s state  during serialization.</pre><p>If you have an instance variable that can’t be saved because it isn’t serializable, you can mark that variable with the transient keyword and the serialization process will skip over it.</p><p>So why would a variable not be serializable? It could be that the class designer simply forgot to make the class implement Serializable. Or it might be because the object relies on runtime-specific information that simply can’t be saved. Although most things in the Java class libraries are serializable, you can’t save things like network connections, threads, or file objects. They’re all dependent on (and specific to) a particular runtime ‘experience’. In other words, they’re instantiated in a way that’s unique to a particular run of your program, on a particular platform, in a particular JVM. Once the program shuts down, there’s no way to bring those things back to life in any meaningful way; they have to be created from scratch each time</p><p><strong>Deserialization: restoring an object</strong></p><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 (which might not even be the same JVM that was running at the time the object was serialized). Deserialization is a lot like serialization in reverse.</p><ol><li>Make a FileInputStream</li></ol><pre>FileInputStream fileStream = new FileInputStream(“MyGame.ser”);</pre><p>The FileInputStream know to connect an existing file. When the file “MyGame.ser” doesn’t exist, then will get an exception.</p><p>2. Make an ObjectInputStream</p><pre>ObjectInputStream os = new ObjectInputStream(fileStream);</pre><p>ObjectInputStream allow to read objects, but it cannot connect to a file directly. It needs to be chained to a connection stream (FileInputStream)</p><p>3.Read the objects</p><pre>Object one = os.readObject(); <br>Object two = os.readObject();<br>Object three = os.readObject();</pre><p>Each time we call readObject(), the we get the next object in the stream. So we will read them back in the same order in which they were written. When we try to read more objects than we wrote, then we get a exception.</p><p>4. Cast the objects</p><pre>GameCharacter elf = (GameCharacter) one;<br>GameCharacter troll = (GameCharacter) two;<br>GameCharacter magician = (GameCharacter) three;</pre><p>Type Object is the return value of readObject(). We have to cast it back to the type.</p><p>5. Close the ObjectInputStream</p><pre>os.close();</pre><p>Closing the stream at the top closes the ones underneath, then automatically close the FileInputStream.</p><p><strong>What Happens During Deserialization</strong></p><p>When an object is deserialized, the JVM bring the object back to life by creating a new object on the heap. So that object has the same state the serialized object had at the time it was serialized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*hl5EN_L71Q47RdJX.jpeg" /></figure><ol><li>The object is read from the stream</li><li>The JVM determines the object’s class type.</li><li>The JVM attempts to find and load the object’s class. When the JVM can’t find and/or load the class, then the JVM throws an exception and fail the deserialization.</li><li>A new object is given space on the heap, but the serialized object’s constructor does NOT run.</li><li>If the object has a non-serializable class in the inheritance tree, the constructor for that non-serializable class will run along with any constructors above that. we can’t stop it, once the constructor chaining begins. which means all super classes, beginning with the first non-serializable one, will reinitialize their state.</li><li>The object’s instance variables are given the values from the serialized state. Transient variables are given a value of null for object references and defaults (0, false, etc.) for primitives.</li></ol><p><strong>*Writing a String to a Text File</strong></p><p>Writing text data (a String) is similar to writing an object, except write a String instead of an object, and use a FileWriter instead of a FileOutputStream .</p><p>To write a serialized object:</p><pre>objectOutputStream.writeObject(someObject);</pre><p>To write a String:</p><pre>fileWriter.write(“My first String to save”);</pre><ol><li>The object is read from the stream</li><li>The JVM determines the object’s class type.</li><li>The JVM attempts to find and load the object’s class. When the JVM can’t find and/or load the class, then the JVM throws an exception and fail the deserialization.</li><li>A new object is given space on the heap, but the serialized object’s constructor does NOT run.</li><li>If the object has a non-serializable class in the inheritance tree, the constructor for that non-serializable class will run along with any constructors above that. we can’t stop it, once the constructor chaining begins. which means all super classes, beginning with the first non-serializable one, will reinitialize their state.</li><li>The object’s instance variables are given the values from the serialized state. Transient variables are given a value of null for object references and defaults (0, false, etc.) for primitives.</li></ol><p><strong>*Writing a String to a Text File</strong></p><p>Writing text data (a String) is similar to writing an object, except write a String instead of an object, and use a FileWriter instead of a FileOutputStream .</p><p>To write a serialized object:</p><pre>objectOutputStream.writeObject(someObject);</pre><p>To write a String:</p><pre>fileWriter.write(“My first String to save”);</pre><p><strong>The java.io.File Class</strong></p><p>The java.io.File class represents a file on disk, but doesn’t represent the contents of the file. A File object represents the name and path of a file or directory on disk. But it does NOT represent, or give you access to, the data in the file.</p><p><strong>Some things can do with a File object:</strong></p><ol><li>Make a File object representing an existing file</li></ol><pre>File f = new File(“MyCode.txt”);</pre><p>2.Make a new directory</p><pre>File dir = new File(“Chapter7”);  dir.mkdir();</pre><p>3.List the contents of a directory</p><pre>if (dir.isDirectory()) {  <br>         String[] dirContents = dir.list(); <br>         for (int i = 0; i &lt; dirontents.length; i++) {<br>            System.out.println(dirContents[i]);<br>         }<br>  }</pre><p>4.Get the absolute path of a file or directory</p><pre>System.out.println(dir.getAbsolutePath());</pre><p>5. Delete a file or directory</p><pre>boolean isDeleted = f.delete();</pre><h3>Buffers</h3><p>Buffers give a temporary holding place to group things until the holder is full.</p><pre>BufferedWriter writer = new BufferedWriter(new FileWriter(aFile));</pre><p>we don’t need to keep a reference to the FileWriter object. . The only thing we care about is the BufferedWriter, because that’s the object we’ll call methods on, and when close the BufferedWriter, it will take care of the rest of the chain</p><h3>*Bullet Points</h3><ul><li>You can save an object’s state by serializing the object.</li><li>To serialize an object, you need an ObjectOutputStream (from the java.io package)</li><li>Streams are either connection streams or chain streams</li><li>Connection streams can represent a connection to a source or destination, typically a file, network socket connection, or the console.</li><li>Chain streams cannot connect to a source or destination and must be chained to a connection (or other) stream.</li><li>To serialize an object to a file, make a FileOuputStream and chain it into an ObjectOutputStream.</li><li>To serialize an object, call writeObject(theObject) on the ObjectOutputStream. You do not need to call methods on the FileOutputStream.</li><li>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.</li><li>When an object is serialized, its entire object graph is serialized. That means any objects referenced by the serialized object’s instance variables are serialized, and any objects referenced by those objects…and so on.</li><li>If any object in the graph is not serializable, an exception will be thrown at runtime, unless the instance variable referring to the object is skipped.</li><li>Mark an instance variable with the transient keyword if you want serialization to skip that variable. The variable will be restored as null (for object references) or default values (for primitives).</li><li>During deserialization, the class of all objects in the graph must be available to the JVM.</li><li>You read objects in (using readObject()) in the order in which they were originally written.</li><li>The return type of readObject() is type Object, so deserialized objects must be cast to their real type.</li><li>Static variables are not serialized! It doesn’t make sense to save a static variable value as part of a specific object’s state, since all objects of that type share only a single value — the one in the class.</li><li>To write a text file, start with a FileWriter connection stream.</li><li>Chain the FileWriter to a BufferedWriter for efficiency.</li><li>A File object represents a file at a particular path, but does not represent the actual contents of the file.</li><li>With a File object you can create, traverse, and delete directories.</li><li>Most streams that can use a String filename can use a File object as well, and a File object can be safer to use.</li><li>To read a text file, start with a FileReader connection stream.</li><li>Chain the FileReader to a BufferedReader for efficiency.</li><li>To parse a text file, you need to be sure the file is written with some way to recognize the different elements. A common approach is to use some kind of character to separate the individual pieces.</li><li>Use the String split() method to split a String up into individual tokens. A String with one separator will have two tokens, one on each side of the separator. The separator doesn’t count as a token.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=614a46b83fb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Head First Java Chapter 13 Summary -Work on Your Swing]]></title>
            <link>https://medium.com/@bhagya.devduni98/head-first-java-chapter-13-summary-work-on-your-swing-e40c81410060?source=rss-d3c81c4b57c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e40c81410060</guid>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Bhagya Devduni]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 12:13:01 GMT</pubDate>
            <atom:updated>2022-07-18T12:13:01.591Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Swing components</strong></p><p>Component is the more correct term for what we’ve been calling a widget. The things you put in a GUI. The things a user sees and interacts with. Text fields, buttons, scrollable lists, radio buttons, etc. are all components. In fact, they all extend javax.swing.JComponent.</p><p>A widget is technically a Swing Component. Almost every thing you can stick in a GUI extends from javax. swing.JComponent.</p><p><strong>Components can be nested</strong></p><p>In Swing, virtually all components are capable of holding other components. In other words, you can stick just about anything into anything else. But most of the time, you’ll add user interactive components such as buttons and lists into background components such as frames and panels. Although it’s possible to put, say, a panel inside a button, that’s pretty weird, and won’t win you any usability awards. With the exception of JFrame, though, the distinction between interactive components and background components is artificial. A JPanel, for example, is usually used as a background for grouping other components, but even a JPanel can be interactive. Just as with other components, you can register for the JPanel’s events including mouse clicks and keystrokes.</p><p><strong>Four steps to making a GUI (review)</strong></p><ol><li>Make a window (a JFrame)</li></ol><pre>JFrame frame = new JFrame();</pre><p>2. Make a component (button, text field, etc.)</p><pre>JButton button = new JButton(“click me”);</pre><p>3. Add the component to the frame</p><pre>frame.getContentPane().add(BorderLayout.EAST, button);</pre><p>4. Display it (give it a size and make it visible)</p><pre>frame.setSize(300,300); <br>frame.setVisible(true);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*cttJ6r3IRH8svx2IhlY8gg.png" /></figure><h3>Layout Managers</h3><ul><li>A layout manager is a Java object associated with a specific component, almost always a background component.</li><li>The Layout Manager controls the locations as well as the size of the component associated with inside other components.</li><li>The layout manager is in charge of the size and placement of the components. In the GUI, layout manager is the one who decided how big these buttons should be, and where they are relative to each other and the frame.</li><li>We can add a component to another component and the layout manager is controlled the added component.</li><li>When building a layout, layout managers have their own policies to follow. So, they first get the preferred sizes from the components and then make decisions about layout. layout managers will make decisions according to their policies and also different layout managers have different policies.</li></ul><h3>A Layout Scenario</h3><ol><li>Make a panel and add three buttons to it.</li><li>The panel’s layout manager asks each button how big</li><li>that button prefers to be.</li><li>Add the panel to a frame.</li><li>The panel’s layout manager uses its layout policies to decide whether it should respect all, part, or none of the buttons’ preferences.</li><li>The frame’s layout manager asks the panel how big the panel prefers to be. The frame’s layout manager uses its layout policies to decide whether it should respect all, part, or none of the panel’s preferences.</li></ol><h3>The Big Three Layout Managers</h3><ol><li><strong>BorderLayout</strong></li></ol><p>A BorderLayout manager divides a background component into five regions. They are East, West, North, South, and Center. We can add only one component per region to a background controlled by a BorderLayout manager. The default layout manager for a <strong>frame</strong> is BorderLayout.</p><p>Let’s add a button to the <strong>East region.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ab5fdafdec99f22fca077b7e8c9562c/href">https://medium.com/media/1ab5fdafdec99f22fca077b7e8c9562c/href</a></iframe><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*xYazDtfUJNhleLEa.jpeg" /></figure><p>Let’s add a button to the <strong>North Region</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/571b9b1f9fcdb084be695a4e50505095/href">https://medium.com/media/571b9b1f9fcdb084be695a4e50505095/href</a></iframe><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/0*mTmb3g_GmQ4mL7zS.jpeg" /></figure><p>Now lets add buttons for <strong>All Regions</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/914e8212f6c9fd0be2a84a045fcadb85/href">https://medium.com/media/914e8212f6c9fd0be2a84a045fcadb85/href</a></iframe><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/0*LN4mSgAm8AV7pg3h.jpeg" /></figure><p><strong>FlowLayout</strong></p><p>A FlowLayout manager acts like a word processor, except with components instead of words. FlowLayout cares about the flow of the components: left to right, top to bottom, in the order they were added. Each component is the size it wants to be and components added left to right, wrapping to a new line when needed. A component moves to the next “line” in the layout when it can fit horizontally. FlowLayout is the default layout manager for a <strong>panel.</strong></p><p><strong>BoxLayout</strong></p><p>A BoxLayout manager is like FlowLayout in that each component gets to have its own size, and the components are placed in the order in which they’re added. But, unlike FlowLayout, a BoxLayout manager can stack the components vertically (or horizontally, but usually we’re just concerned with vertically). It’s like a FlowLayout but instead of having automatic ‘component wrapping’, you can insert a sort of ‘component return key’ and force the components to start a new line.</p><h3>Playing with Swing Components</h3><p>Few of the most common components are text field, scrolling text area, checkbox, and list.</p><h3>JTextField</h3><p>Constructors</p><pre>JTextField field = new JTextField(30); <br>JTextField field = new JTextField(“Your name”); //30 means 30 columns, not 20 pixels.</pre><p><strong>How to use it</strong></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(“whatever”); <br>field.setText(““);   // This clears the field</pre><p>3. Get an ActionEvent when the 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 ( the user can start typing)</p><pre>field.requestFocus();</pre><h3>JTextArea</h3><p>JTextArea allow to have more than one line of text. It takes a little configuration to make one, because it doesn’t come out of the box with scroll bars or line wrapping.</p><p>Constructor</p><pre>JTextArea text = new JTextArea(20,30); <br>// 20 means 20 lines &amp; 30 means 30 columns</pre><p><strong>How to use it</strong></p><ol><li>Make it have a vertical scrollbar only</li></ol><pre>JScrollPane scroller = new JScrollPane(text); //Make a JScrollPane <br>text.setLineWrap(true);  // Turn on line wrappingscroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); panel.add(scroller);</pre><p>2. Replace the text</p><pre>text.setText(“here is the new text”);</pre><p>3. Append to the text that is 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><h3>JCheckBox</h3><p><strong>Constructor</strong></p><pre>JCheckBox check = new JCheckBox(“Goes to 11”);</pre><p><strong>How to use it</strong></p><ol><li>Listen for an item event (when it’s selected or deselected)</li></ol><pre>check.addItemListener(this);</pre><p>2.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>     intln(“Check box is “ + onOrOff);  <br> }</pre><p>3. Select or deselect it in code</p><pre>check.setSelected(true); <br>check.setSelected(false);</pre><h3>JList</h3><p><strong>Constructor</strong></p><p>JList constructor takes an array of any object type. They don’t have to be Strings, but a String representation will appear in the list.</p><pre>String [] listEntries = {“alpha”, “beta”, “gamma”, “delta”,  “epsilon”,  <br>                                    “zeta”, “eta”, “theta “};JList list = new JList(listEntries);</pre><p><strong>How to use it</strong></p><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 (find out which thing in the list was selected)</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><h3>Bullet Points</h3><ul><li>Layout managers control the size and location of components nested within other components.</li><li>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.</li><li>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.</li><li>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);</li><li>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()).</li><li>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.</li><li>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.</li><li>FlowLayout gives components their preferred size in both dimensions.</li><li>BoxLayout lets you align components stacked vertically, even if they could fit side-by-side. Like FlowLayout, BoxLayout uses the preferred size of the component in both dimensions.</li><li>BorderLayout is the default layout manager for a frame; FlowLayout is the default for a panel.</li><li>If you want a panel to use something other than flow, you have to call setLayout() on the panel.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e40c81410060" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting GUI — Head First Java 12]]></title>
            <link>https://medium.com/@bhagya.devduni98/getting-gui-head-first-java-12-73d150a2ad5e?source=rss-d3c81c4b57c------2</link>
            <guid isPermaLink="false">https://medium.com/p/73d150a2ad5e</guid>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Bhagya Devduni]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 11:59:12 GMT</pubDate>
            <atom:updated>2022-07-18T11:59:12.972Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting GUI — Head First Java 12</h3><p>The purpose of this article is to highlight the key ideas covered in chapter 12.</p><p>A JFrame is the object that represents a window on the screen. It’s where you put all the interface things like buttons, checkboxes, text fields, and so on. It can have an honest-to-goodness menu bar with menu items. And it has all the little windowing icons for whatever platform you’re on, for minimizing, maximizing, and closing the window. The JFrame looks different depending on the platform you’re on. This is a JFrame on Mac OS X:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*H1_8WYLyMwwjHv23dz1biw.png" /></figure><p><strong>How to Make GUI?</strong></p><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(“click me”);</pre><p>3.Add the widget to the frame</p><pre>frame.getContentPane().add(button);//No need add things to the frame directly.</pre><p>4.Give size and make it visible</p><pre>frame.setSize(300,300); <br>frame.setVisible(true);</pre><h3>First GUI: A button on a frame</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/507c714a86136cfb19840e8f442d6819/href">https://medium.com/media/507c714a86136cfb19840e8f442d6819/href</a></iframe><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/0*t2zmYJ9zQAroiQ33.jpeg" /></figure><p>But when we click me button, nothing happens . Because this is just a design. How do we get the button to do something specific when the user clicks it?</p><p>Need two things:</p><ol><li>A <strong>method </strong>to be called when the user clicks</li><li>A way to <strong>know </strong>when to trigger that method. In other words, a way to know when the user clicks the button.</li></ol><p><strong>Getting a user event</strong></p><p>Imagine you want the text on the button to change from click me to I’ve been clicked when the user presses the button. First we can write a method that changes the text of the button (a quick look through the API will show you the method):</p><pre>public void changeIt() { <br> <br>button.setText(“I’ve been clicked!”); </pre><pre>}</pre><p>But now what? How will we know when this method should run? How will we know when the button is clicked?</p><p>In Java, the process of getting and handling a user event is called event-handling. There are many event types in Java, although most involve GUI user actions. If the user clicks a button, that’s an event. An event that says “The user wants the action of this button to happen.” If it’s a “Slow Tempo” button, the user wants the slow-tempo action to occur. If it’s a Send button on a chat client, the user wants the send-my-message action to happen. So the most straightforward event is when the user clicked the button, indicating they want an action to occur.</p><p>With buttons, you usually don’t care about any intermediate events like button-is-being-pressed and button-is-being-released. What you want to say to the button is, “I don’t care how the user plays with the button, how long they hold the mouse over it, how many times they change their mind and roll off before letting go, etc. Just tell me when the user means business! In other words, don’t call me unless the user clicks in a way that indicates he wants the darn button to do what it says it’ll do!”</p><p><strong>The Event Source</strong></p><p>The Swing GUI elements are event sources. An event source is an object that can convert user actions into events in Java term. In Java, an event is represented as an object. An object of some event class. An event source creates an event object when the user does something that matters . Most of the code we write will receive events rather than create events. In other words, we will spend most of the time as an event listener rather than an event source.</p><p>A button is a source of ActionEvents, so it has to know which objects are interested listeners. The button provides a method called addActionListener() that enables interested objects (listeners) a way to tell the button that they are interested. The button takes the parameter and stores it in a list when addActionListener() executes. When the user clicks the button, the button ‘fires’ the event by calling the actionPerformed() method on each listener in the list.</p><p><strong>The Listener</strong></p><p>We implement the ActionListener interface when the class needs to be aware of a button’s ActionEvents. we register with the button by calling addActionListener(this) and passing an ActionListener reference to it. When we implement a listener interface, the button needs a way to call you back when the event happens, so it calls the method in the listener interface. As an ActionListener, you must implement the interface’s sole method, actionPerformed(). The compiler guarantees it.</p><p><strong>Getting a button’s ActionEvent</strong></p><ol><li>Implement the ActionListener interface</li></ol><p>2. 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><p>Let’s see an example of Button ActionEvent</p><pre>import javax.swing.*;<br>import java.awt.event.*;</pre><pre>public class Test implements ActionListener {   //mplement the interface. This says, “an instance of Test IS-A ActionListener”.<br>    JButton button;<br>     public static void main (String[] args) {<br>        Test test = new Test();<br>        test.go();<br>    }</pre><pre>public void go() {<br>        JFrame frame = new JFrame();<br>        button = new JButton(&quot;Hi, click me&quot;);</pre><pre>button.addActionListener(this);   //register your interest with the button<br>        frame.getContentPane().add(button);<br>        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br>        frame.setSize(300,300);<br>        frame.setVisible(true);<br>    }</pre><pre>public void actionPerformed(ActionEvent event) {  // mplement the ActionListener interface’s actionPerformed() method.. This is the actual event-handling method!</pre><pre>button.setText(&quot;I’ve been clicked! &quot;);</pre><pre>}<br>}</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*D9IIMqQpgrBkvKR2.jpeg" /></figure><p><strong>Listeners, Sources, and Events</strong></p><p><strong>Listeners job is,</strong></p><ol><li><em>Implement</em> the interface</li><li><em>Register</em> with the button,</li><li><em>Provide</em> the event-handling.</li></ol><p><strong>An event source job is,</strong></p><ol><li><em>Accept</em> registrations (from listeners)</li><li><em>Get</em> events from the user</li><li><em>Call</em> the listener’s event-handling method (when the user clicks )</li></ol><p><strong>Event object,</strong></p><ul><li>HOLDS DATA about the event</li><li>It is the <em>argument</em> to the event call-back method (from the interface) and its job is to <em>carry data</em> about the event back to the listener.</li><li><strong>Listener</strong> <em>GETS</em> the event, <strong>Source</strong> <em>SENDS</em> the event, <strong>Event object</strong> <em>HOLDS</em> <em>DATA</em> about the event.</li></ul><p><strong>Getting back to graphics.</strong></p><p>Now that we know a little about how events work (we’ll learn more later), let’s get back to putting stuff on the screen. We’ll spend a few minutes playing with some fun ways to get graphic, before returning to event handling.</p><p>Three ways to put things on your GUI:</p><ol><li><strong>Put widgets on a frame:</strong> Add buttons, menus, radio buttons, etc. The javax.swing package has more than a dozen widget types</li></ol><pre>frame.getContentPane().add(myButton);</pre><p>2. <strong>Draw 2D graphics on a widget :</strong>Use a graphics object to paint shapes. we can paint a lot more than boxes and circles; the Java2D API is full of fun, sophisticated graphics methods.</p><pre>graphics.fillOval(70,70,100,100);</pre><p>3. <strong>Put a JPEG on a widget : C</strong>an put own images on a widget</p><pre>graphics.drawImage(myPic,10,10,this);</pre><p>To draw our own graphic we can extend JPanel class and then override the painComponent() method.paintComponent() method includes all the graphic code inside it. Let’s say if we want to draw a specific shape like Triangle that method has all the code that is needed for drawing.</p><pre>import java.awt.*;<br>import javax.swing.*;</pre><pre>class MyDrawPanel extends JPanel {      //Make a subclass of JPanel, a widget that can add to a frame <br> <br>     public void paintComponent(Graphics g) {   //You will NEVER call this yourself. The system calls it</pre><pre>g.setColor(Color.orange);<br>         g.fillRect(20,50,100,100);<br>    }<br>}</pre><p>we can use below code to<strong> display a JPEG</strong></p><pre>public void paintComponent(Graphics g) {   Image image = new ImageIcon(“catzilla.jpg”).getImage();<br>   g.drawImage(image,3,4,this);  //The x,y coordinates for where the picture’s top  left corner should go.<br> <br>}</pre><p><strong>Behind every good Graphics reference is a Graphics2D object.</strong></p><p>The argument to paintComponent() is declared as type Graphics (java.awt.Graphics).</p><pre>public void paintComponent(<strong>Graphics</strong> g) { }</pre><p>The parameter ‘g’ IS-A Graphics object. Which mean, it could be a subclass of Graphics (because of polymorphism). The object referenced by the ‘g’ parameter is an instance of the Graphics2D class.</p><p>If you need to use a method from the Graphics2D class, you can’t use the the paintComponent parameter (‘g’) straight from the method. But you can cast it with a new Graphics2D variable.</p><p>when we need to use a method from the Graphics2D class, we can’t use the the paintComponent parameter (‘g’) straight from the method. But can cast it with a new Graphics2D variable. (To cast the Graphics2D object to a Graphics2D reference)</p><pre>Graphics2D g2d = (Graphics2D) g;</pre><p>Let’s see an example when whe circle changes color each time you click the button.</p><pre>import javax.swing.*;<br>import java.awt.*;<br>import java.awt.event.*;</pre><pre>public class SimpleGui implements ActionListener {<br>    JFrame frame;<br>    public static void main (String[] args) {<br>        SimpleGui gui = new SimpleGui();<br>        gui.go();<br>    }</pre><pre>public void go() {<br>        frame = new JFrame();<br>        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br> <br>        JButton button =new JButton(&quot;Change Colors&quot;);<br>        button.addActionListener(this);  //Add the listener (this) to the button<br> <br>        MyDrawPanel drawPanel = new MyDrawPanel();<br> <br>         frame.getContentPane().add(BorderLayout.SOUTH, button);    //Add widgets  to the two regions of the frame.<br>         frame.getContentPane().add(BorderLayout.CENTER, drawPanel);  //Add widgets  to the two regions of the frame.<br>         frame.setSize(300,300);<br>         frame.setVisible(true);<br>   }</pre><pre>public void actionPerformed(ActionEvent event) {<br>        frame.repaint();  //When the user clicks, tell the frame to repaint() itself<br>    }<br>}</pre><p><strong>Output :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/0*wdewGJoF4bqqCmtQ.jpeg" /></figure><p><strong>Get Action Events For Two Different Buttons</strong></p><p>How do we get action events for two different buttons, when each button needs to do something different?</p><ol><li><strong>option one : </strong>Implement two actionPerformed() methods</li></ol><pre>class MyGui implements ActionListener { <br>    // lots of code here and then   public void actionPerformed(ActionEvent event) { <br>     frame.repaint(); <br>   }<br>  <br>   public void actionPerformed(ActionEvent event) {  <br>      label.setText(“That hurt!”); <br>   }<br> }</pre><p>In the above code we can there are two same methods. we can’t implement the same method twice in a Java class. It won’t compile. And even if we could, how the event source know which of the two methods to call.</p><p>2.<strong> Option two: </strong>Register the same listener with both buttons.</p><pre>class MyGui implements ActionListener { <br>   // declare a bunch of instance variables here    public void go() {  <br>      // build gui  <br>       colorButton = new JButton(); <br>       labelButton = new JButton();       //Register same Listner with both buttons<br>       colorButton.addActionListener(this);  <br>       labelButton.addActionListener(this); <br>      // more gui code here <br> } <br> <br>    public void actionPerformed(ActionEvent event) { <br>        if (event.getSource() == colorButton) { <br>             frame.repaint(); <br>         } else {  <br>             label.setText(“That hurt!”); <br>          } <br>      }<br> }</pre><p>This does work, but in most cases it’s not very. One event handler doing many different things means, have a single method doing many different things. When we need to change how one source is handled, we have to mess with everybody’s event handler. Sometimes it is a good solution, but usually it hurts maintainability and extensibility.</p><p>3.O<strong>ption three:</strong> Create two separate ActionListener classes</p><pre>class MyGui { <br>   JFrame frame;  <br>   JLabel label;  <br>  <br>    void gui() { <br>   // code to instantiate the two listeners and register one  <br>   // with the color button and the other with the label button <br>  }<br>}class ColorButtonListener implements ActionListener { <br>    public void actionPerformed(ActionEvent event) {     <br>          frame.repaint();  //Won’t work! This class doesn’t have a reference to  the ‘frame’ variable of the MyGui class<br>    }<br> }class LabelButtonListener implements ActionListener { <br>    public void actionPerformed(ActionEvent event) {   <br>          label.setText(“That hurt!”);    // This class has no reference to the variable ‘label<br>    }<br> }</pre><p>These classes won’t have access to the variables they need to act on, ‘frame’ and ‘label’.</p><p>So there has got to be a better way. we can solve this with <strong>Inner class.</strong></p><h3>Inner Class</h3><p>Inner class means one class nested inside another class. An inner class can use all the methods and variables of the outer class, even the private ones. The inner class gets to use those variables and methods just as if the methods and variables were declared within the inner class.</p><p>An inner class gets a special pass to use the outer class’s stuff. Even the private . And the inner class can use those private variables and methods of the outer class as when the variables and members were defined in the inner class.</p><p>Inner class using an outer class variable</p><pre>class MyOuterClass {<br>    private int x;  class MyInnerClass { <br>      void go() { <br>        x = 42;//use ‘x’ as if it were a variable of inner class<br>      }<br>   } // close inner class<br>} // close outer clas</pre><p><strong>Make an Instance of an inner class</strong></p><p>When we instantiate an inner class from code within an outer class, the instance of the outer class is the one that the inner object will ‘bond’ with.</p><p>Code in an outer class can instantiate one of its own inner classes, in exactly the same way it instantiates any other class<strong> new MyInner()</strong></p><pre>class MyOuter { <br>   private int x; //outer class has a privateinstance variable ‘x   MyInner inner = new MyInner();//Make an instance of inner class   public void doStuff() { <br>     inner.go(); //call a method on the  inner class<br>  }  class MyInner { <br>     void go() { <br>        x = 42;  <br>     }<br>  } // close inner class <br>} // close outer class</pre><p>Now we can get the two-button code working</p><pre>import javax.swing.*;<br>import java.awt.*;<br>import java.awt.event.*;<br> <br>public class TwoButtons {<br>    JFrame frame;<br>    JLabel label;<br> <br>    public static void main(String[] args)<br>    {<br>        TwoButtons gui = new TwoButtons();<br>        gui.go();<br>    }<br> <br>    public void go()<br>    {<br>        frame = new JFrame();<br>        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br> <br>        JButton labelButton = new JButton(&quot;Change label&quot;);<br>        labelButton.addActionListener(new LabelListener());<br> <br>        JButton colorButton = new JButton(&quot;Change circle&quot;);<br>        labelButton.addActionListener(new ColorListener());<br> <br>        label = new JLabel(&quot;I&#39;m a label&quot;);<br>        MyDrawPanel drawPanel = new MyDrawPanel();<br> <br>        frame.getContentPane().add(BorderLayout.SOUTH, colorButton);<br>        frame.getContentPane().add(BorderLayout.CENTER, drawPanel);<br>        frame.getContentPane().add(BorderLayout.EAST, labelButton);<br>        frame.getContentPane().add(BorderLayout.WEST, label);<br> <br>        frame.setSize(400,300);<br>        frame.setVisible(true);<br>    }<br>     <br>    class LabelListener implements ActionListener<br>    {<br>        public void actionPerformed(ActionEvent event)<br>        {<br>            label.setText(&quot;Ouch!&quot;);<br>        }<br>    }<br> <br>    class ColorListener implements ActionListener<br>    {<br>        public void actionPerformed(ActionEvent event)<br>        {<br>            frame.repaint();<br>        }<br>    }<br> <br>}<br> <br>class MyDrawPanel extends JPanel<br>{<br>    public void paintComponent(Graphics g)<br>    {<br>        Graphics2D g2d = (Graphics2D) g;<br> <br>        g2d.setColor(randomColor());<br>        g2d.fillRect(0,0,this.getWidth(), this.getHeight());<br> <br>        GradientPaint gradient = new GradientPaint(70,70,randomColor(),<br>            150,150,randomColor() );<br>        g2d.setPaint(gradient);<br>        g2d.fillOval(70,70,100,100);<br>    }<br> <br>    public Color randomColor()<br>    {<br>        int red = (int) (Math.random() * 255);<br>        int green = (int) (Math.random() * 255);<br>        int blue = (int) (Math.random() * 255);<br>        Color randomColor = new Color(red, green, blue);<br>        return randomColor;<br>    }<br>}</pre><p><strong>Output :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/0*GNQsDTJkSbSliL_n.jpeg" /></figure><h3>Bullet Points</h3><p><strong><em>Event</em></strong></p><p>· To make a GUI, start with a window, usually a JFrame.</p><p><strong>JFrame frame = new JFrame();</strong></p><p>· You can add widgets (buttons, text fields, etc.) to the JFrame using: <strong>frame.getContentPane().add(button);</strong></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:</p><p><strong>frame.setSize(300,300);</strong></p><p><strong>frame.setVisible(true);</strong></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>· To listen for an event, you must register your interest with an event source. An event source is the thing (button, checkbox, etc.) that ‘fires’ an event based on user interaction</p><p>· The listener interface gives the event source a way to call you back, because the interface defines the method(s) the event source will call when an event happens.</p><p>· To register for events with a source, call the source’s registration method. Registration methods always take the form of: addListener. To register for a button’s ActionEvents, for example, call:</p><p><strong>button.addActionListener(this);</strong></p><p>· Implement the listener interface by implementing all of the interface’s event-handling methods. Put your event[1]handling code in the listener call-back method. For ActionEvents, the method is:</p><p><strong>public void actionPerformed(ActionEvent event) {</strong></p><p><strong>button.setText(“you clicked!”);</strong></p><p><strong>}</strong></p><p>· The event object passed into the event-handler method carries information about the event, including the source of the event.</p><p><strong><em>GRAPHICS</em></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><p>· Typical methods to call on a Graphics object (the paintComponent paramenter) are:</p><p><strong>g.setColor(Color.blue); g.fillRect(20,50,100,120);</strong></p><p>· To draw a .jpg, construct an Image using: Image image = new ImageIcon(“catzilla. jpg”).getImage(); and draw the image using: <strong>g.drawImage(image,3,4,this);</strong></p><p>· The object referenced by the Graphics parameter to paintComponent() is actually an instance of the Graphics2D class. The Graphics 2D class has a variety of methods including: fill3DRect(), draw3DRect(), rotate(), scale(), shear(), transform()</p><p>· To invoke the Graphics2D methods, you must cast the parameter from a Graphics object to a Graphics2D object:</p><p><strong>Graphics2D g2d = (Graphics2D) g;</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73d150a2ad5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exception Handling — Headfirst Java Chapter 11]]></title>
            <link>https://medium.com/@bhagya.devduni98/exception-handling-headfirst-java-chapter-11-1f5664501e2e?source=rss-d3c81c4b57c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f5664501e2e</guid>
            <category><![CDATA[exception-handling]]></category>
            <dc:creator><![CDATA[Bhagya Devduni]]></dc:creator>
            <pubDate>Mon, 18 Jul 2022 11:41:48 GMT</pubDate>
            <atom:updated>2022-07-18T11:41:48.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exception Handling — Headfirst Java Chapter 11</h3><p>The purpose of this article is to highlight the key ideas covered in chapter</p><p><strong>Hierarchy of Java Exception classes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*mogvrUR71FKNSF39.jpeg" /></figure><p>The class at the top of the exception class hierarchy is the Throwable class, which is a direct subclass of the Object class. Exception and Error are two of Throwable’s direct subclasses. The Exception class is used for exception conditions that the application may need to handle and also The Error class is used to indicate a more serious problem in the architecture and should not be handled in the application code. The hierarchy of Java exception classes is shown below.</p><p>Here we can see Exception and Error classes are subclasses of the Throwable class. Throwable is not an interface. and Throwable class extend Object class. Errors are what we cannot handle.</p><p><strong>Types of Java Exceptions</strong></p><p>There are mainly two types of exceptions: Checked exception &amp; Unchecked<strong> </strong>exception <strong>. </strong>An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:</p><ol><li><strong>Checked exception</strong></li></ol><p>The classes that directly inherit the Throwable class except RuntimeException and Error are called as checked exceptions. Checked exceptions are checked at compile-time. IOException, SQLException, are a few examples.</p><p><strong>2. Unchecked exception</strong></p><p>The classes that inherit the RuntimeException are called as unchecked exceptions. Unchecked exceptions are not checked at compile-time, but they are checked at runtime. ArithmeticException &amp; NullPointerException are few examples of unchecked exception.</p><p><strong>3. Errors</strong></p><p>Error is irrecoverable. OutOfMemoryError, AssertionError are some example of errors .</p><p>The exception-handling mechanism in Java is a clean, well-lighted way to handle “exceptional situations” that occur during runtime. It enables us to place all the error-handling code in convenient location (one easy-to-read place).</p><p><strong>Types of Java Exceptions</strong></p><p>There are mainly two types of exceptions: Checked exception &amp; Unchecked<strong> </strong>exception <strong>. </strong>An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely:</p><ol><li><strong>Checked exception</strong></li></ol><p>The classes that directly inherit the Throwable class except RuntimeException and Error are called as checked exceptions. Checked exceptions are checked at compile-time. IOException, SQLException, are a few examples.</p><p><strong>2. Unchecked exception</strong></p><p>The classes that inherit the RuntimeException are called as unchecked exceptions. Unchecked exceptions are not checked at compile-time, but they are checked at runtime. ArithmeticException &amp; NullPointerException are few examples of unchecked exception.</p><p><strong>3. Errors</strong></p><p>Error is irrecoverable. OutOfMemoryError, AssertionError are some example of errors .</p><p>The exception-handling mechanism in Java is a clean, well-lighted way to handle “exceptional situations” that occur during runtime. It enables us to place all the error-handling code in convenient location (one easy-to-read place).</p><p><strong>Flow control in try/catch blocks</strong></p><p>When you call a risky method, one of two things can happen. The risky method either succeeds, and the try block completes, or the risky method throws an exception back to your calling method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*jgCGw3lQSf3asxzt_chNkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*h5e2YrZnGtvJ4GMfyDMOQQ.png" /></figure><p>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>Without finally, you have to put the turnOvenOff() in both the try and the catch because you have to turn off the oven no matter what. A finally block lets you put all your important cleanup code in one place instead of duplicating it like this:</p><pre>try {<br> turnOvenOn();<br> x.bake();<br> turnOvenOff();<br> } catch (BakingException ex) { <br> ex.printStackTrace();<br> turnOvenOff();<br> }</pre><p><strong>If the try block fails (an exception)</strong>, flow control immediately moves to the catch block. When the catch block completes, the finally block runs. When the finally block completes, the rest of the method continues on.</p><p><strong>If the try block succeeds (no exception)</strong>, flow control skips over the catch block and moves to the finally block. When the finally block completes, the rest of the method continues on.</p><p><strong>If the try or catch block has a return statement</strong>, finally will still run! Flow jumps to the finally, then back to the return.</p><p>A method can throw multiple exceptions if it darn well needs to. But a method’s declaration must declare all the checked exceptions it can throw (although if two or more exceptions have a common superclass, the method can declare just the superclass.)</p><p><strong>Catching multiple exceptions</strong></p><p>The compiler will make sure that you’ve handled all the checked exceptions thrown by the method you’re calling. Stack the catch blocks under the try, one after the other.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9df373d1a4f5d9f05580c61137de1f79/href">https://medium.com/media/9df373d1a4f5d9f05580c61137de1f79/href</a></iframe><p><strong>Exceptions are polymorphic</strong></p><p>Exceptions are objects, remember. There’s nothing all that special about one, except that it is a thing that can be thrown. So like all good objects, Exceptions can be referred to polymorphically.</p><p><strong>Throw Block</strong></p><p>When we don’t want to handle an exception, we can duck it by declaring it. When we call a risky method, the compiler needs to acknowledge it. Most of the time, that means wrapping the risky call in a try/ catch. But we have another alternative, duck it and let the method that called you catch the exception. We have to do is declare that we throw the exceptions.</p><pre>public void laundry() throws BadException{<br>   // call risky method without a try/catch<br>   laundry.doLaundry();<br>}</pre><p>Here we don’t REALLY throw it, but since we don’t have a try/catch for the risky method we call, risky method. Because now, whoever calls ,has to deal with the exception.</p><h3>Exception Rules</h3><ol><li>Cannot have a catch or finally without try block.</li></ol><pre>//The below code is not legalvoid go() { <br>    Foo f = new Foo();<br>    f.foof(); <br>    catch(FooException ex) { } <br> }</pre><p>2. Cannot put a code between the try and the catch</p><pre>// Not legal ! can’t put code between the try and  the catchtry { <br>      x.doStuff(); <br>} int y = 43; <br>} catch(Exception ex) { }</pre><p>3. A try MUST be followed by either a catch or a finally</p><pre>// LEGAL because have a finally, even  though there’s no catch.But cannot have a try by itselftry { <br>   x.doStuff();<br>} finally { <br>   // cleanup <br>}</pre><p>4. A try with only a finally (no catch) must still declare the exception</p><pre>//A try without a catch  doesn’t satisfy the  handle or declare lawvoid go() throws FooException { <br>      try { <br>         x.doStuff();  <br>      } finally { }<br> }</pre><h3>Bullet Points</h3><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 Runtime Exception. A Runtime Exception 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 Runtime Exceptions 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><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f5664501e2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Numbers And Statics — Headfirst Java Chapter 10]]></title>
            <link>https://medium.com/@bhagya.devduni98/numbers-and-statics-headfirst-java-chapter-10-c8c31887bf16?source=rss-d3c81c4b57c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c31887bf16</guid>
            <category><![CDATA[head-first-java]]></category>
            <dc:creator><![CDATA[Bhagya Devduni]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 18:39:58 GMT</pubDate>
            <atom:updated>2022-07-18T05:31:30.955Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Numbers And Statics — Headfirst Java Chapter 10</strong></h3><p>The aim of the article is to highlight the key concepts discussed in Chapter 10.</p><p>Methods in the Math class don’t use any instance variable values. And because the methods are ‘static’, you don’t need to have an instance of Math. All you need is the Math class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*Aoumv3Y-AfODRua01o0KKQ.png" /></figure><p>If you try to make an instance of class Math</p><p><strong>Math mathObject = new Math();</strong></p><p>You’ll get this error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*yH_0o_14NyhHbN969HDkVg.png" /></figure><p><strong>The difference between regular (non-static) and static methods.</strong></p><p>Java is object-oriented, but once in a while you have a special case, typically a utility method (like the Math methods), where there is no need to have an instance of the class. The keyword static lets a method run without any instance of the class. A static method means “behavior not dependent on an instance variable, so no instance/object is required. Just the class.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*lHPZi0Y64m5mcE4Uq67iuA.png" /></figure><p><strong>Call a static method using a class name:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*9Xr8_SKRwCnBKmXiuIKrYg.png" /></figure><pre><strong>Math.min(88,86)</strong></pre><p><strong>Call a non-static method using a <em>reference variable </em>name</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/1*AIVkzJr0JgPmEY-uMgmNuQ.png" /></figure><pre><strong>Song t2 = new Song();<br>t2.play();</strong></pre><p><strong>Static Methods Cannot Use Non-Static (Instance) Variables</strong></p><p>Static methods run without knowing about any particular instance of the static method’s class. And as you saw on the previous pages, there might not even be any instances of that class. Since a static method is called using the class (Math. random()) as opposed to an instance reference (t2.play()), a static method can’t refer to any instance variables of the class. The static method doesn’t know which instance’s variable value to use.</p><p>Let’s look at an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f414d388e02a8c696c7648bb268f32f/href">https://medium.com/media/8f414d388e02a8c696c7648bb268f32f/href</a></iframe><p>if we run the Cat.java class we will get the below error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*r5XKRtHjJu1EXplm5Cu4UQ.png" /></figure><p><strong>Static Methods Can’t Use Non-Static Methods, Either</strong></p><p>What non-static methods do is, usually use instance variable states to affect the behaviour of the method. A getName() method returns the value of the name variable. The object used to invoke the getName() method.</p><p>The below program also won’t compile.</p><p><strong>&lt;script src=”https://gist.github.com/BhagyaDevduni/804777216f0aac3c367718d64177fa88.js&quot;&gt;&lt;/script&gt;</strong></p><p><strong>Static Variable</strong></p><p>Static variables are shared. All instances of the same class share a single copy of the static variables.</p><p><strong>Static Variable</strong></p><p>Static variables are shared. All instances of the same class share a single copy of the static variables.</p><p>Initializing a Static Variable</p><p>When the class is loaded, static variables are initialized. If we don’t explicitly initialize a static variable (by assigning it a value at the time we declare it), it gets a default value, Int variables are initialized to zero, which mean we didn’t need to explicitly say “playerCount = 0”. Declaring, but not initializing, a static variable means the static variable will get the default value for that variable type, in exactly the same way that instance variables are given default values when declared.</p><p>There are two guarantees about static variables.</p><p>1. Static variables in a class are initialized before any object of that class can be created</p><p>2. Static variables in a class are initialized before any static method of the class runs.</p><p><strong>Final Keyword</strong></p><p><strong>Static Final Variables</strong></p><p>When a variable is declared as final, it cannot be changed after initialization. As long as the class is loaded, the static final variable’s value won’t change.</p><p>public static final double PI = 3.141592653589793;</p><p>The variable is marked as public so that any code can access it. The variable is marked static so that don’t need an instance of class Math. The variable is marked final because PI doesn’t change.</p><p>There is a naming convention that makes it easier for you to identify a constant, but there is no other way to mark a variable as a constant. <em>Constant variable names should be in all caps.</em></p><p>A static initializer is a block of code that runs when a class is loaded, before any other code can use the class, so it’s a great place to initialize a static final variable.</p><p>We can use the keyword<em> final</em> to modify non-static variables also, including instance variables, local variables, and method parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/0*Nd_loi6EtC0uHr5t.jpeg" /></figure><h3>Math methods</h3><p>The Java Math class has many methods that allows you to perform mathematical tasks on numbers.</p><ol><li><strong>Math.random()</strong></li></ol><p>Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive)</p><pre>double x1 = Math.random(); <br>int x2    = (int) (Math.random() * 4);</pre><p><strong>2. Math.abs()</strong></p><p>Math.abs() method 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 double it returns a double.</p><pre>int x    = Math.abs(-150);       // returns 150<br>double y = Math.abs(140.45);  // returns 150.45</pre><p><strong>3. Math.round()</strong></p><p>It returns an int or a long (depending on whether the argument is a float or a double) rounded to the nearest integer value.</p><pre>int x = Math.round(-18.9f);     // returns -19<br>int y = Math.round(44.45f);     // returns 44//Floating point literals are assumed  to be doubles unless we add the ‘f&#39;</pre><p><strong>4. Math.min()</strong></p><p>Math.min() method returns a value that is the minimum of the two arguments. The method is overloaded to take ints, longs, floats, or doubles.</p><pre>int x    = Math.min(34,240);            // returns 34<br>double y = Math.min(90876.5, 90876.49); // returns 90876.49</pre><p><strong>5. Math.max()</strong></p><p>Returns a value that is the maximum of the two arguments. The method is overloaded to take ints, longs, floats, or doubles.</p><pre>int x    = Math.max(24,240);            // returns 240 <br>double y = Math.max(90876.5, 90876.49); // returns 90876.5</pre><h3>*Wrapping a Primitive</h3><p>When we want to treat primitives like an object, then we can do it by wrapping them. There’s a wrapper class for every primitive type, and since the wrapper classes are in java.lang package and we don’t need to import them. And also we can identify wrapper classes because, each one is named after the primitive type it wraps, but with the first letter capitalized to follow the class naming convention.</p><h3>Math methods</h3><p>The Java Math class has many methods that allows you to perform mathematical tasks on numbers.</p><ol><li><strong>Math.random()</strong></li></ol><p>Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive)</p><pre>double x1 = Math.random(); <br>int x2    = (int) (Math.random() * 4);</pre><p><strong>2. Math.abs()</strong></p><p>Math.abs() method 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 double it returns a double.</p><pre>int x    = Math.abs(-150);       // returns 150<br>double y = Math.abs(140.45);  // returns 150.45</pre><p><strong>3. Math.round()</strong></p><p>It returns an int or a long (depending on whether the argument is a float or a double) rounded to the nearest integer value.</p><pre>int x = Math.round(-18.9f);     // returns -19<br>int y = Math.round(44.45f);     // returns 44//Floating point literals are assumed  to be doubles unless we add the ‘f&#39;</pre><p><strong>4. Math.min()</strong></p><p>Math.min() method returns a value that is the minimum of the two arguments. The method is overloaded to take ints, longs, floats, or doubles.</p><pre>int x    = Math.min(34,240);            // returns 34<br>double y = Math.min(90876.5, 90876.49); // returns 90876.49</pre><p><strong>5. Math.max()</strong></p><p>Returns a value that is the maximum of the two arguments. The method is overloaded to take ints, longs, floats, or doubles.</p><pre>int x    = Math.max(24,240);            // returns 240 <br>double y = Math.max(90876.5, 90876.49); // returns 90876.5</pre><h3>*Wrapping a Primitive</h3><p>When we want to treat primitives like an object, then we can do it by wrapping them. There’s a wrapper class for every primitive type, and since the wrapper classes are in java.lang package and we don’t need to import them. And also we can identify wrapper classes because, each one is named after the primitive type it wraps, but with the first letter capitalized to follow the class naming convention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*aARXCok4EerJx2oW.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*Jveax7IRJ4ZN93CZ.jpeg" /></figure><p>Formatting consists of two main parts,</p><ol><li><strong>Formatting instructions :</strong> Use special format specifiers that describe how the argument should be formatted</li><li><strong>The argument to be formatted : </strong>The argument type should be that can formatted. if you use double value in the argument there is a compilation error.</li></ol><p>What do these instructions actually say is,<strong> </strong>“Take the second argument to this method, and format it as a decimal integer and insert commas.”</p><p>·format() → method is called the format string.</p><p>·The first argument to a format() method is called the format String, and it can include characters that we want printed as-is, without extra formatting.</p><p>·When we see the percent sign (%) think of it as representing a variable, and the variable is the other argument to the method. The rest of the characters after the percent sign describe the formatting instructions for the argument.</p><p>We can’t put <em>anything</em> after %</p><p>· <strong>%,d</strong> →insert commas and format the number as a decimal integer</p><p>· <strong>%.2f</strong> →format numbers as floating-point with a precision of to decimal places.</p><p>· <strong>%,2f</strong> →insert commas and format numbers as floating-point with a precision of to decimal places.</p><h3>The format specifier</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*ivmeL7WYuePafO34.jpeg" /></figure><p>The <strong>Type</strong> is mandatory everything else is optional.</p><p>· <strong>% d →decimal</strong></p><p>The <strong>Type</strong> is mandatory everything else is optional.</p><p>· <strong>% d →decimal</strong></p><pre>format(“%d”, 42);</pre><p>The argument must be compatible with an int, so that means only byte, short, int, and char (or their wrapper types)</p><p>· <strong>%f →floating-point</strong></p><pre>format(“% .3f” ,42.000000)   →   42.000</pre><p>The argument must be of a floating point type, so that means only a float or double (primitive or wrapper) as well as something called Big Decimal.</p><p>· <strong>%x →hexadecimal</strong></p><pre>format(“%x” ,42)    →   2a</pre><p>The argument must be a byte, short, int, or long. this can be including both primitives and wrapper types and also BigIntegers.</p><p>· <strong>%c →Character</strong></p><pre>format(“%c” ,42)     →    *</pre><p>The number 42 represents the char *. The argument must be a byte, short, int, or char. This can be including both primitives and wrapper types</p><h3>*Formatting Date</h3><p>The main difference between number and date formatting is that date formats use a two-character type that starts with “t”.</p><p>·The complete date and time represents <strong><em>% tc</em></strong></p><pre>String.format(“%tc”, new Date());</pre><p>·Just the time represents <strong><em>%tr</em></strong></p><pre>Just the time %tr</pre><p>·Day of the week, month and day represents <em>%tA %tB %td</em></p><p>There isn’t a single format specifier that will do exactly what we want, so we have to combine three of them for day of the week (%tA), month (%tB), and day of the month (%td).</p><pre>Date today = new Date();<br> String.format(“%tA, %tB %td”,today,today,today);</pre><h3>*Getting An Object That Extends Calendar</h3><p><strong>Calendar cal = new Calendar();</strong> is will not work .</p><p>Instead, use the static “getInstance()” method:</p><pre>Calendar cal = Calendar.getInstance();</pre><h3>*Bullet Points</h3><p>· A static method should be called using the class name rather than an object reference variable: <strong>Math. random() vs. myFoo.go()</strong></p><p>· A static method can be invoked without any instances of the method’s class on the heap.</p><p>· A static method is good for a utility method that does not (and will never) depend on a particular instance variable value.</p><p>· 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.</p><p>· A static method cannot access a non-static method, since non-static methods are usually associated with an instance variable state.</p><p>· 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.</p><p>· A <strong><em>static variable</em></strong> 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 instance for instance variables.</p><p>· A static method can access a static variable.</p><p>· To make a constant in Java, mark a variable as both static and final.</p><p>· A final static variable must be assigned a value either at the time it is declared or in a static initializer.</p><p>static {</p><p>DOG_CODE = 420;</p><p>}</p><p>· The naming convention for constants (final static variables) is to make the name all uppercase.</p><p>· A final variable value cannot be changed once it has been assigned.</p><p>· Assigning a value to a final instance variable must be either at the time it is declared or in the constructor.</p><p>· A final method cannot be overridden.</p><p>· A final class cannot be extended (sub classed).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c31887bf16" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>