Java Nots
Java Nots
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
welcome
First, I want to say thank you for choosing my book, Get Programming with Java!
This version of a Java book is designed to increase your knowledge of programming with
objects. Since Java is considered an object-oriented programming language, it makes sense
that I use that as my tool of choice. It is important to understand that some prior
programming experience is essential to get the most out of this book. It is written with the
premise that you, the reader, have already learned about basic programming constructs, such
as variables, data types, loops and methods. This knowledge can be from programming with
JavaScript, Python, or a similar programming language.
The Java programming language is still considered one of the most popular object-
oriented programming languages available. It was originally developed under Sun
Microsystems, but more recently it was taken over by Oracle.
For this book, you will probably notice right away that I am also a teacher. I approached
this book with the same thought and diligence that I use when preparing to teach Java to
students. Teaching is my lifelong passion, and I think it comes through in this book. I’m
telling you this, so you know this is not strictly a technical book about all things Java, it is a
book that teaches you the important concepts in Java starting with an understanding of object
representation through advance topics such as inheritance, file processing, collections, and a
discussion on design patterns in Java.
After completing this book, you can add Java to the list of tools in your toolbox. In today’s
job landscape, this is a great addition to any resume. Be sure to update your Linkedin profile
with this skill!
I strongly encourage you to post any questions or comments you have about the content
in the book’s forum. This feedback is appreciated so that I can make improvements and
increase your understanding of the material.
Sincerely,
—Peggy Fisher
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
brief contents
UNIT 0: GETTING STARTED WITH JAVA
Lesson 1 Get Started
UNIT 1 CLASSES AND OBJECTS
Lesson 2 Creating classes
Lesson 3 Visibility modifiers
Lesson 4 Adding methods
Lesson 5 Adding loops
Lesson 6 Arrays and ArrayLists
Lesson 7 Capstone 1 (Payroll)
UNIT 2: APPLICATION PROGRAMMING INTERFACE (API)
Lesson 8 Standard Java API
Lesson 9 String and StringBuilder Classes
Lesson 10 Static methods and variables
Lesson 11 Using interfaces
Lesson 12 Capstone 2
UNIT 3: PROGRAMMING WITH OBJECTS
Lesson 13 Overloading Methods
Lesson 14 Overriding Methods
Lesson 15 Polymorphism Explained
Lesson 16 Polymorphism in Action
Lesson 17 Comparing Objects
Lesson 18 Capstone 3
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
UNIT 4: MORE PROGRAMMING WITH OBJECTS
Lesson 19 Pass by Value vs. Pass by Reference
Lesson 20 Garbage Collection
Lesson 21 Java Collections: List
Lesson 22 Java Collections: Set
Lesson 23 Collections: Queues
Lesson 24 Collections: Maps
Lesson 25 Using Generic classes
Lesson 26 Capstone 4
UNIT 5: FILE PROCESSING
Lesson 27 Reading from Files
Lesson 28 Writing to Files
Lesson 29 Using Streams from Java 8
Lesson 30 Data parsing
Lesson 31 File error handling
Lesson 32 Capstone 5
UNIT 6: ADVANCED TOPICS
Lesson 33 Exception Handling
Lesson 34 Lambda Functions
Lesson 35 Coupling/Cohesion
Lesson 36 Design Patterns
Lesson 37 Singletons
Lesson 38 Encapsulation
SPECIAL LESSONS:
How to run Java programs from the terminal
How to use JShell
Package your app for deployment
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
1
Unit 0
Getting Started with Java
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
2
1
Get Started
This lesson walks through the process of installing all the parts needed to write code and run
your Java programs using the NetBeans IDE on both macOS and Windows. There has been
much debate over whether the use of an IDE should be used to teach programming skills. The
other option is to use a text editor to type your code, then use a command prompt window to
compile and run the code. Personally, I prefer to start with an IDE for a few reasons:
• An IDE helps find syntax errors prior to code execution (avoids frustration)
• New programmers can build confidence in their ability to write code quickly
• Allows new programmers to concentrate on understanding the logic of coding, not the
details of the language
• Provides tools to help debug when there are logic problems that are not readily seen in
the code
When you first learn to program, using an IDE provides several advantages. For example,
when typing your code using an IDE, there is instant feedback regarding syntax errors and
even some logic errors, such as trying to use undeclared variables. Java is a strictly-typed
programming language; every variable must be defined with a data type and in many cases
initialized prior to use. Another nice feature of most IDEs is some form of code completion.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
3
Consider this
You’re comfortable programming in a different language than Java, and ar familiar with basic object-oriented concepts.
Now, you want to start programming in Java, the first thing you need to know is the difference in the syntax for Java
compared to other languages. To begin with, one of the key syntactical differences is the use of semicolons in Java.
Other languages, such as Python, use spacing and indentation to dictate blocks of code and the end of a statement. In
Java, every statement must end with a semicolon. When typing code into an IDE, it provides an instant error and a hint
if you forget to include the semicolon. Do you think using an IDE is an advantage when learning a new language?
Another benefit of using the combined environment is the graphical user interface (GUI) that
provides menus, toolbars, semantic coloring of the text as you type your code, immediate
identification of syntax errors, code completion, and even some compile time errors can be
identified when using an IDE.
One of my favorite parts of using an IDE is the debugging tool that is included. This tool can
be used to find errors in your code, often referred to as ‘bugs’. It can also be used to walk
through the view your code execution one statement at a time and even view the values of all
variables included in the program.
There are many different IDEs available for Java programming. Here are a few of the more
common ones:
• NetBeans
• Eclipse
• IntelliJ
• BlueJ
• DrJava
• JDeveloper
• JCreator
Each IDE has its pros and cons, but for this book I have chosen to use NetBeans. NetBeans
has many features to make coding more productive, such as:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
4
Figure 1.1 The JDK includes the Java Language, Tools, and the Java Runtime Environment (JRE)
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
5
It is important to choose the correct download based on your system; for example, I am using
a Macbook Pro, so I chose the download for macOS. (Make sure to select the radio button to
Accept License Agreement before starting the download.) If you are running windows and you
have a 32-bit operating system, choose the x86 version of the downloads.
Figure 1.2 Screenshot from Oracle website with information on JDK downloads
Once the download is complete, run through the installation process by double clicking on the
download and following the installation instructions.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
6
Figure 1.3 Screenshot of Installation options for standalone JDK or NetBeans with JDK
If you already installed the JDK, then it is not necessary to download it again and you can use
the NetBeans website to download the latest version of NetBeans
(https://netbeans.org/downloads/).
Figure 1.4 Screenshot of the NetBeans IDE Download page showing all download options
There are several options to choose from, but to follow along with the examples in this book,
choose Java SE download. Also notice the top of the window and make sure you have chosen
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
7
the correct platform. In Figure 1.4, my platform is Mac OS X. The NetBeans website has a
link to Installation Instructions. It is a good idea to check that link since you might be working
with a newer version of the product.
Once the download is complete, launch NetBeans. In the next section, we will review some of
the environment settings to check before continuing with our activities. Figure 1.4 shows a
screenshot of the installation process on a Mac. As you can see, the installation wizard makes
it easy to install. Start by reading the Introduction, then click the Continue button (see
Figure 1.5). The next screen provides all the license information. You must click the Agree to
button. The Destination Select gives you the option to change the default location, then
click the Continue button again. At the next window, click the Continue button. At the very
end, you will get a summary of the install.
When NetBeans is opened for the first time, you will see the Start Page (see figure 1.6) From
the Start Page, take a look at the links available under the Demos & Tutorials or click the
button ‘Take a Tour’ to learn about NetBeans.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
8
Next, depending on what other programming languages and IDEs you might have used, you
might want to personalize the settings such as the background color, the font size, and so on.
The default profile is called NetBeans and it provides a white background. There are several
themes that are included in the download. On a Windows machine, you can go to
Tools/Options/Fonts & Colors. For a mac, go to NetBeans/Preferences/Fonts & Colors. Many
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
9
programmers prefer a black background, so feel free to change it to your preference. Figure
1.5 show the NetBeans Options window on a Mac.
a. Keymap
b. Profile
c. Category
d. Appearance
In the NetBeans IDE, start by using the File menu, choose New Project. A dialog box appears,
choose Java /Java Application and hit Next.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
10
Give the application a name; for our example, name the project “JavaRocks”, then click Finish.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
11
The IDE creates a project folder with several subfolders and a file with a .java extension. This
is where we write our Java code. Figure 1.8 shows the program that gets created in
NetBeans.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
12
Every Java project must include at least one file that contains a main method. In our first
program, line 3 is the start of this method. The main method extends from line 3 where it
starts with an open curly brace and ends on line 5 with a closing curly brace. In the next few
lessons, we will talk more about exactly what each line of code is doing in this example.
Before we run this new program, let’s add a line of code so we can see it print information to
the console. The console is also part of the IDE. Keeping it simple, replace the comment on
line 4 that currently says // TODO code application logic here with this line of code:
System.out.println(“Java Rocks!!”);
Make sure that you type the line of code exactly as it appears above. Java is case-sensitive, so
you must use a capital S for System and lower case for the remaining command. The words
inside the double quotes can be mixed case - they are considered a literal constant. Next, we
want to save the program, make sure that you don’t change the file name. In Java, the file
name must match the class name exactly. Once you are done, click the green arrow to the
right of the hammer and brush. You should see output similar to Figure 1.9.
Figure 1.11 Screenshot of the output from running the program JavaRocks
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
13
a) comment
b) println statement
c) main method
1.6 Summary
In this lesson, we reviewed the installations necessary to write Java code, compile your code,
and run your code. We also reviewed instructions for downloading an Integrated Development
Environment.
In the next lesson, we will work on writing code for a program that acts like a calculator. This
lesson is being used as an introduction to the syntax of Java and Java libraries. Some
programming languages, such as Python, do not require as much explicit notation such as
curly brackets to indicate blocks of code. Instead, Python stresses lines and indentation
instead of explicit curly brackets used in Java.
TRY THIS: Once you have the Java JDK downloaded and the NetBeans IDE installed, create a new project.
Use the sample code from this lesson and instead of printing "Java Rocks", print your name.
a. False: If I accidentally closed the ‘Start Page’, I can’t get back to the page without restarting
NetBeans. To find the ‘Start Page’, click ‘Help’ in the menu bar and choose ‘Start Page’.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
14
To change the look and feel of the IDE code window, change the _____________:
a. Keymap
b. Profile
c. Category
d. Appearance
a. comment
b. println statement
c. main method
Figure 1.12 Screenshot from NetBeans for the updated code and the output message
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
15
Unit 1
Classes and Objects
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
16
2
Creating Classes
• Make
• Model
• Year
• MPG
• Color
• Move forward
• Move backward
• Stop (or brake)
• Turn left/right
• Honk horn
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
17
Consider This
You have been hired by a local car dealership to provide their IT support. The first project is to create a mailing list for
all their customers. The owner wants to automate the process of sending out reminders for customers that need
maintenance appointments for their vehicles. In order to write a program to automate this process, what class(es) do
you think are needed for this project?
It is time to create our car class in Java. It is possible to use an IDE to create our class, but
since this is our first program, I am going to just use a text editor. To start, I create a file
named Car.java.
Inside the text file, start by using the keyword class followed by the class name. It is
recommended that all class names start with an upper-case letter. Next, I have added all of
the attributes identified for a car using the appropriate data types and variable names. For the
variables that contain descriptive words, I have identified them as String variables. Since the
year is numeric without any decimal points, I declared it as an integer, which in Java is int.
And finally, the field for MPG or Miles Per Gallon is a double since it is a floating-point number.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
18
Figure 2.1 Code listing for the start of the Car class
Note:
The String data type is actually a class, therefore it must be coded with an upper-case S, as opposed to the lower-case
letters for int and double. The String class is discussed in more detail later in this book.
The data fields for a class are often referred to as instance data. It is called instance data
since the values are specific to an instance of the class and are not shared among all instances
of the same class. Instance variables (fields) are defined directly inside the class.
In table 2.1, the first row represents a single object, which is called an instance of the car
class. This specific object has instance data detailing that this car make is a Subaru, model is
a Outback, year is 2017, mpg is 28 and the color is black. This data is not shared with the
other two rows in our table. Each car has its own information.
a. attributes, behavior
b. name, data type
c. child, parent
a. myfirstclass.java
b. MyFirstClass.java
c. anyname.java
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
19
In figure 2.2, I have added methods that represent the behaviors of a car. Each method has
the keyword void before the method name. This keyword indicates that the method does not
return any values.
Figure 2.2 Code listing of the Car class with methods added
The methods that are declared inside of a class can be used once we create an instance of the
class. In other words, once we have an object defined. In the next section I will show you
how to use the Car class to create car objects.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
20
a. moveForward()
b. setColor()
c. honk()
In Java, each object is given a variable name and then the keyword ‘new’ is used to create the
object. The process of creating an object from a class is called instantiation. In other words,
we are creating a single instance of an object using the class as the model. For this activity, I
will create a new car object. In Listing 2.2, starting on line 20 I added a main method to the
program.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
21
#C Using dot notation, the instance data for the myCar object is populated with real values
Note:
When executing a Java program, the Java Virtual Machine (JVM) searches the code for the main method: public
static void main(String[] args). This is a requirement in every Java application. This is the starting point
of execution in Java.
Inside the main method, line 21 creates the first car object using the Car class. Figure 2.3
explains the parts of this statement.
Figure 2.3 Diagram of the statement used to create a new car object from the Car class
This statement creates the new object myCar. Once the object is created, the next step is to
populate the data fields. Lines 22-26 assign values to the data fields in myCar.
In each of these assignment statements, I use dot notation to access the fields for the object
myCar. In this example, the dot notation identifies the object followed by a dot and then the
variable name of the instance data. In our example, we have myCar.make = "Subaru";.
This updates the car make for the object called myCar.
In the next Lesson, I will review some best practices when using object-oriented programming
to create objects and retrieve/modify the instance data using methods.
a. new
b. this
c. that
a. new
b. instantiation
c. encapsulation
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
22
2.4 Summary
In this lesson, you learned:
Creating classes and objects is an essential part of any Java program. Remember: the class is
the blueprint used to create the template or model of our real-world objects. Then, we use the
class to create one or more objects.
In the next lesson, I will add more methods to the class that can be used to retrieve and
modify instance data for an object.
Try this:
A friend owns a pet grooming business. For this activity, we want to create a class in Java to
represent a pet. Each pet must have a name, pet type, owner, and age.
Then write a main method that creates at least three pet objects and provides values for the
instance data of each object.
a. attributes, behavior
b. name, data type
c. child, parent
a. myfirstclass.java
b. MyFirstClass.java
c. anyname.java
a. moveForward()
b. setColor()
c. honk()
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
23
a. new
b. this
c. that
a. new
b. instantiation
c. encapsulation
}
}
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
24
3
Visibility Modifiers
The visibility modifiers determine the access level of the instance data, method, class, etc. In
this lesson I will explain the concept of packages in Java, which is necessary to understand
how visibility modifiers affect your application and review the various types that can be used.
One reason for using these modifiers is to restrict access. Think about a banking application.
One of the classes would probably be for a bank account. The bank account class might have
a customer’s name, home address, birth date, etc. If access to these fields is marked as
public, then there is no way to validate that changes are made correctly. For example, the
birth year could be set to an invalid year such as 2100.
Consider This
The human resources department for Company A uses a Java application to keep track of all employees. The
application has an Employee class that contains all the demographic and pay information about the employee. Only
employees in HR have access to the sensitive information such as an employee’s full name, social security number,
home address, pay scale, etc. What would happen if all of the instance data for the Employee class was marked as
public? How can we protect this data from getting updated with invalid information?
3.1 Packages
In Java, a package is a namespace used to group a set of classes together. So far, our
application consisted of only one file with one class, but most Java applications consist of
many files and many classes. The package allows us to connect these classes together.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
25
When using a package, the package name appears at the very top of your code inside your
class file. Java naming standards recommend that the package name is written in all lower-
case letters to avoid confusion with any class names. To add a class to a package, use the
keyword package followed by the package name, for example:
package packagename;
As we continue to create more complicated classes, one of the benefits of Java is the vast
amount of code already written and tested that is available for general use. These packages
are included in the Java API (Application Programming Interface). The API is a library of
packages that can be used in our applications. Most of these packages are designed for
handling common programming requirements, such as working with String objects or File
objects. This allows us to concentrate on the programming needed to handle the business
requirements for our program.
To leverage other classes in Java that are not part of your current package, we can use the
import statement. The import statement allows us to ‘import’ other packages that contain
one or more classes. For example, any program that reads information from the console uses
the Scanner package and must include this statement: import Java.util.Scanner;
public Y Y Y Y
protected Y Y Y N
none specified Y Y N N
private Y N N N
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
26
It is important to always choose the modifier that is most restrictive but still allows access
when needed. Let’s take a closer look at each type:
• public – this is the least restrictive and allows access to this code from the current
class, the package, any subclasses, and any other classes.
• protected – this modifier allows the same access as public except that it can only be
accessed by the current class, any classes in the same package, and any subclasses.
• default – when the modifier is omitted, it is considered a default visibility. This
restricts access to only the class and classes in the same package
• private – this is the most restrictive and only allows access within the same class
Lesson 2 introduced the topic of classes and objects which are required for any object-oriented
(OO) programming language. In a later lesson, I will review the concept of Inheritance in
much more detail, but to help understand the concepts of visibility modifiers, I want to explain
the relationship of a class and subclass. In Java, we can create a ‘child’ class using another
class as the ‘parent’. This new class becomes a subclass and the parent is called the
superclass. This is one of the strengths of Java, it is referred to as inheritance. Inheritance
allows us to create a class that inherits all the public and protected information from the
superclass and adds any additional information necessary for the subclass. For example, our
Car class could be a subclass of a Vehicle class.
Let’s look at a diagram that depicts two packages. Both packages have two classes, but
package B has a class that is actually a subclass of the Vehicle class in package A.
Figure 3.1 Diagram of two packages to demonstrate the impact of the visibility modifiers
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
27
In this example, Car is a subclass of Vehicle. Package A has two classes: Vehicle and House.
Package B has two classes: Car and Garden. Table 3.2 depicts the impact of using each of the
visibility modifiers with these two packages. The table shows the visibility based on the
modifier in the Vehicle class.
For example, if the Vehicle class has a data field marked protected, then only the classes in
the same package (Vehicle and House) and the subclass (Car) can access that data. Note,
when the data is marked as private in the vehicle class, it is not directly accessible by any of
the other classes.
Table 3.2 Access to the other classes from the Vehicle class
public Y Y Y Y
protected Y Y Y N
none specified Y Y N N
private Y N N N
a. public
b. private
c. package
2. T/F: When the private modifier is used, only a subclass access that data.
3. Which of the following is true about a subclass:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
28
In this example, all the instance data have been updated and marked as private. This is used
to make sure that the data is not updated inadvertently. In OO terms, this allows all the Car
information to be encapsulated in the Car class. Each of the methods in this class have been
updated as public. That way, other programs can use the methods once they create a Car
object, such as myCar.honk();
3.4 Summary
In this lesson, you learned:
Remember to choose the most restrictive modifier that still provides the access required. In
Java, there are four types of modifiers: public, protected, default and private.
In the next lesson, I will add more methods to a class and show you how to put the class in a
separate file.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
29
Try this:
A friend owns a pet grooming business. Using the class you created from Lesson 2, add the
visibility methods to the class, instance data and methods.
a. public
b. private
c. package
2. T/F: When the private modifier is used, only a subclass access that data. False
3. Which of the following is true about a subclass:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
30
p2.petAge = 4;
}
}
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
31
4
Adding Methods
All programming languages have a way to create a block of reusable code. In Python and
other programming languages it is called a function, in Java it is called a method. The idea is
that the method performs some action, but the calling program does not need to know exactly
how it works, just that it will return the correct result or perform the correct action.
Consider This
Have you ever made microwave popcorn? Some microwaves have a button with a label that says ‘popcorn’. When you
place the bag of un-popped popcorn in the microwave and push that button, it starts to heat up the bag until the
popcorn kernels get hot enough to pop. After a certain amount of time, it shuts off and you have a bag of popped
popcorn. This is similar to a method in Java. The microwave has a ‘popcorn’ method.
Can you think of other examples related to common household objects that might be considered an object with one or
more methods?
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
32
for the parameter list (which can be empty), and the method body inside curly braces (which
can also be empty).
In addition to these required elements, methods often include a visibility modifier, and a
parameter list inside the parentheses. The keyword static is included when the method is not
associated with a particular object, like the main method. Static methods are addressed later
in the book. Figure 4.1 describes each part of a method signature, including required and
optional components.
public Y Y Y Y
protected Y Y Y N
default Y Y N N
private Y N N N
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
33
The visibility modifier plays a key role in enforcing data integrity, so choose your modifier
carefully. Try to use the strictest modifier that still provides the access you need.
It is important to point out that a Java method is restricted to returning only one type of data.
For example, a method cannot return both a String and a double value, it has to return either
a String or a number defined as a double. To get around this limitation, it is possible to return
an object and I will address that in a later lesson.
Table 4.2 has several method signatures and example return values:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
34
to change the instance data field for the employee last name. Here is the method signature
for this method:
public void setEmployeeLastName(String lastName)
The parameter list in the method signature identifies the type of data and provides variable
names for each item included in the list. In this example, the method code updates the
employee’s last name, but does not return any information to the calling program.
NOTE Java uses the terms parameters and arguments when working with methods. Some developers use
these terms interchangeably. But generally, the term parameter is used to refer to the variable listed in the
method signature and an argument is the value that is passed to the method during program execution.
The parameter list can have zero, one or many parameter values. The values in the list do not
have to be the same data type. The parameter list data type must match the data type of the
values in the call to the method. In my example, I can only include one String value when I
call the method setEmployeeLastName.
NOTE If the method does not require any information from the calling program, an empty parameter list
must be provided.
If the method executes successfully, it returns control to the statement immediately following
the call to the method. The body of the method has access to the parameters listed in the
parameter list and includes a block of code to accomplish some task.
If the method signature has a void return type, then the return statement can be omitted in
the body of the method. Otherwise, the method body must contain a return statement and
the value returned must match the return type specified in the method signature.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
35
4. In the following code snippet, match the visibility modifier, return type, method name, and parameter
list:
a. calculate Cost
b. moveCharacter
c. 1stPlayer
The benefit of using a setter method is that we can add additional code checking to enforce
data integrity. For example, if we have instance data that contains a last name, we might
want to add logic to make sure the calling program is not setting it to an empty String.
Let’s revisit the Car class from Lesson 3 and update it with a getter and setter method for
each piece of instance data. Listing 4.1 shows the code from lesson 3. Remember, each car
object was given values for the following instance data:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
36
9. }
10. public void stop() {
11. }
12. public void turnLeft() {
13. }
14. public void turnRight() {
15. }
16. public void honk() {
17. }
18. public static void main(String[] args) {
19. Car myCar = new Car();
20. myCar.make = "Subaru";
21. myCar.model = "Outback";
22. myCar.year = 2017;
23. myCar.mpg = 28;
24. myCar.color = "black";
25. }
26. }
#A Since the three variables: make, model, and color are all String variables, I put them together separated by a
comma
This code works great and demonstrates how to create an object from the Car class. Then it
assigns values to each piece of instance data. But it would be easy to make a mistake, such
as providing a year < 1900 or an empty String for the car make. Also, since the instance data
is marked as private, only code in this class can access these fields. What happens if we want
to make this Car class available to other classes in our application?
The solution is to add getter and setter methods. Code listing 4.2 shows the new Car class
with a getter and setter method for all the instance data.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
37
Now, the Car class has methods for retrieving the instance data about any car object and
updating the data. By making these methods public, they can be used by this program and
others. Also, notice that each getter method has a return type, so when the calling program
uses these methods, it must expect the value returned to be the same data type.
The setter methods require the calling program to provide the data that will be used to update
the instance data, this is provided in the parameter list.
Note:
In each setter method, I had to use the keyword ‘this’. When a method uses a parameter that has the same name as
the field for that class, we need to identify which piece of data is part of the object vs. the data included in the
parameter list. So, remember, the keyword ‘this’ refers to the object that is affected by the calling program. Figure 4.1
shows the use of the ‘this’ keyword.
Figure 4.2 Shows how to use the keyword ‘this’ for updating instance data
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
38
Note:
The setter method uses the dot notation which I introduced in Lesson 2. In this example, it is used for accessing the
instance data, i.e.: this.make. In the next section I will explore more dot notation when I start calling the methods
created for the car class.
Now that we have getter and setter methods defined, I will add code to the main method to
use these new methods. For this example, I am only going to include the main method in the
code listing. The main method will:
Update all the information about myCar and print the new information
Figure 4.3 Output listing after executing the code in Listing 4.3
Listing 4.3 Car class using the new getter and setter methods
1. public class Car {
2. private String make, model, color;
3. private int year;
4. private double mpg;
5.
6. //#A
7. public static void main(String[] args) {
8. Car myCar = new Car();
9. myCar.make = "Subaru";
10. myCar.model = "Outback";
11. myCar.year = 2017;
12. myCar.mpg = 28;
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
39
#A Code is omitted to save room, see code listing 4.2 for missing information
#B Each print line statement uses the getter methods to retrieve the instance data for the myCar object
#C Each of these statements update the instance data using the value in the parameter list and calling the setter
methods
#D Print the new values for the myCar object after using the setter methods
#E Try to set the year to an invalid year (2075)
The next section discusses how we can modify the private instance data for our objects.
a. myCar.getModel;
b. myCar.getModel();
c. myCar.setModel();
a. myCar.getMPG();
b. myCar.getmpg();
c. getMPG();
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
40
a. myCar.setYear(1998);
b. setYear(1998);
c. myCar.getYear(1998);
6. Which statement is correct for setting the mpg for myCar to 50.5:
a. myCar.setmpg(50.5);
b. myCar.setMPG(50.5);
c. myCar.setMPG("50.5");
Every car object has information about the MPG rating for the vehicle, so all we really need is
to ask the user how much fuel is in the tank. Then we can take the MPG and multiply it times
the amount of fuel to determine the distance the car can travel before refueling. For example,
if we have a car with an MPG rating of 34 and 10 gallons in the tank, this car can drive 340
miles before it needs to be refueled.
This example needs to know how much fuel is in the tank, so that value must be included in
the parameter list for our new method. Since the method is calculating the remaining
distance, it will return a numeric value. The instance data field for MPG is a double, so we
should expect the final distance to be returned as a double. Here is the method signature and
the code needed to calculate the distance:
public double calculateDistance(double fuel) {
double distance = fuel * mpg;
return distance; }
In this code, the method signature has a return type of double, and the parameter list has one
value for the amount of fuel in the tank. Inside the method, a new double variable is created
called distance that is calculated using the fuel times the mpg. Then, the distance variable is
returned. Listing 4.4 shows the new method and new statements in the main method to call
this method and print the distance the car can travel.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
41
8.
9. public void moveForward() { }
10. public void moveBackward() { }
11. public void stop() { }
12. public void turnLeft() { }
13. public void turnRight() { }
14. public void honk() { }
15.
16. public double calculateDistance(double fuel) { //#B
17. double distance = fuel * mpg; //#C
18. return distance; //#D
19. }
20. public static void main(String[] args) {
21. Scanner in = new Scanner(System.in); //#E
22. Car myCar = new Car();
23. myCar.make = "Subaru";
24. myCar.model = "Outback";
25. myCar.year = 2017;
26. myCar.mpg = 28;
27. myCar.color = "black";
28.
29. System.out.println("Enter fuel remaining in tank: ");
30. double fuelInTank = in.nextDouble(); //#F
31. double distance = myCar.calculateDistance(fuelInTank); //#G
32. System.out.println("The car can travel " + distance + "miles"); //#H
33.
34. }
35. }
#A This import statement provides access to the Scanner class which is used to read and write to the console
#B This method signature indicates that it returns a double and has a double as a parameter
#C Add a new variable to hold the value of mpg * fuel in the tank
#D Return a double value
#E Create a new Scanner object, in, that can be used to read data from the command line
#F Read the value entered by the user at the command line, it is expecting a numeric value that can have a decimal
point
#G Call the calculateDistance method on the object myCar, giving it the value for the fuel in the tank and save the value
returned in the variable distance
#H Print out the new value for the distance remaining with the current fuel
In this last section, I added a method to calculate how far the car can travel with the current
fuel in the tank. This method was added to the Car class, so it is only available to objects
created using the Car class. In the main method, I can call (or invoke) this method using the
car object. In this example, my car object is called myCar, so I use the dot notation to invoke
the method: myCar.calculateDistance(fuelInTank).
Let’s look carefully at the call to the method. Did you notice that I have the variable fuel as
the argument? The call to the method is not the same as the method signature. The
signature provides the instructions for using the method. The call to the method allows me to
pass values to the method, but I don’t include the data type.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
42
Figure 4.4 Diagram showing how the argument is passed to the method through the parameter list
a. myCar.calculateMPG();
b. myCar.calculateMPG(10, 120);
c. calculateMPG(10,120);
2. What value can NOT be returned from calling the method above
a. 12.0
b. "12.0"
c. Twelve
4.4 Summary
In this lesson, you learned:
The objective was to add methods to a class. This lesson included special methods called
getter and setter methods, and we added one of teach for all the instance data in the Car
class. Then we added another method to our class that calculates the remaining distance a car
can travel based on the fuel remaining in the tank and the car’s mpg.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
43
In the next lesson, I will introduce the concept of Arrays and ArrayLists in Java which can be
used to create a variable that represents multiple data items.
Try this:
Using the data integrity rules in table 4.3, update the car class to include this logic in the
remaining setter.
a. A void return type indicates that the method does not return any values
a. The return statement is optional for a method with a return type of void
3. What return type should you use for returning the price of an item?
a. double, the price should allow for floating point values (values with a decimal point)
4. In the following code snippet, match the visibility modifier, return type, method name, and parameter
list:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
44
a. myCar.getModel;
b. myCar.getModel();
c. myCar.setModel();
a. myCar.getMPG();
b. myCar.getmpg();
c. getMPG();
a. myCar.setYear(1998);
b. setYear(1998);
c. myCar.getYear(1998);
6. Which statement is correct for setting the mpg for myCar to 50.5:
a. myCar.setmpg(50.5);
b. myCar.setMPG(50.5);
c. myCar.setMPG("50.5");
1. Given the method signature above, which statement correctly calls the method calculateMPG given the
fuel used and the distance travel for the object myCar:
a. myCar.calculateMPG();
b. myCar.calculateMPG(10, 120);
c. calculateMPG(10,120);
a. 12.0
b. "12.0"
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
45
c. twelve
Listing 4.5 Add data validation logic to the setter methods for the Car class
1. public class Car {
2. private String make, model, color;
3. private int year;
4. private double mpg;
5.
6. public String getMake() { return make; }
7. public String getModel() { return model; }
8. public String getColor() { return color; }
9. public int getYear() { return year; }
10. public double getMPG() {return mpg; }
11.
12. public void setMake(String make) {
13. if(make.length() >= 3 && make.length() < 50) //#A
14. this.make = make;
15. else
16. System.out.println("Invalid make");}
17. public void setModel(String model) {
18. if(model.length() > 4 && model.length() < 100) //#B
19. this.model = model;
20. else
21. System.out.println("Invalid model");}
22. public void setColor (String color) {
23. if(color.length() > 4 && color.length() < 40) //#C
24. this.color = color;
25. else
26. System.out.println("Invalid color");}
27. public void setYear (int year) {
28. if(year >= 1900 && year <=2050) //#D
29. this.year = year;
30. else
31. System.out.println("Invalid year");
32. }
33. public void setMPG(double mpg) {
34. if(mpg >= 0 && mpg < 100) //#E
35. this.mpg = mpg;
36. else
37. System.out.println("Invalid mpg");}
38.
39. // remaining code omitted
#A Validation check added to check the length of the String is between 3 and 49 characters.
#B Validation check added to check the length of the String is between 4 and 99 characters.
#C Validation check added to check the length of the String is between 4 and 39 characters.
#D Validation check to make sure year is valid (between 1900 and 2050)
#E Validation check added to make sure the numeric value for mpg is between 0 and 99.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
46
5
Adding Loops
A loop allows us to repeat a block of code until some condition is met. In Java, the types of
loops include:
for loop – used when you know how many times the loop needs to execute
while loop – most common and flexible loop, continues while a condition is true
do…while loop – same as a while loop, but the test condition is executed at the end of the
loop, therefore the code is always executed at least once
for-each – iterates over a series of values without any counter or sentinel value
This lesson reviews each type of loop and examples of each loop. Each type of loop has some
common errors that can cause an endless loop. This is referred to as an infinite loop and
sometimes the cause is hard to find. So, for each loop I will review some common errors that
can cause an infinite loop.
Consider This
Have you ever gone shopping at the grocery store and only had a few items so you decide to check out using the lane
marked ‘Less than 15 items’ only to realize the person in front of you definitely has more than 15? What would happen
if the grocery store had a program that only allowed up to 15 items when using this checkout lane? What if the person
in line counted incorrectly and they actually have 16 items?
Well, lucky for those people who don’t always follow the rules, most stores do not have these limits set in the
system. but What kind of loop can we use when we don’t know how many items the customer is purchasing?
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
47
When learning Java after learning another language such as Python, the for statement might
seem a little difficult to understand, so let’s take a look at each part of the for loop. Figure 5.3
takes the for loop statement needed for our program and labels each section of the
statement.
Initialization – This section is only executed once at the beginning of the loop execution. It
provides the value of the control variable, in our case we are using counter and setting it to
the value one. The statement ends with a semi-colon. (Note: More than one variable can be
defined in this section.)
Test Condition – This part of the for loop is used to control the number of iterations using a
boolean expression. As long as the test condition evaluates to true, the loop will continue.
Once the expression is false, the loop ends. This part of the loop is evaluated each time the
loop executes. This statement also ends at the semicolon.
Update – To make sure the loop eventually ends, this section is usually used to update the
counter variable so that the test condition evaluates to false when the number of iterations
have been completed.
This diagram shows the flow of logic in a for loop in Java. It starts with the initialization, then
the test condition. If the condition is true, then it executes the block of code. When the
condition changes to false, the loop is finished, and the program continues with the next
statement outside of the for loop.
The update statement is used to change the control variable. This value can be changed by
incrementing it by one, decrementing it by one, and even increment/decrement by some other
value, such as by twos.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
48
Now that we have reviewed the syntax for a count-controlled loop, let’s look at a code snippet
that replicates the counter for microwaving a bag of popcorn. Note: In this example, the
counter is actually starting at 180 and counting down to zero.
Listing 5.1 This is a code snippet for counting down from 180 seconds to zero
for(int time = 180; time > 0; time--)
{
System.out.print(time + ", ");
}
System.out.println("The popcorn is done!! Let’s eat!");
When using a for loop, be careful to make sure that you are updating your control variable
correctly. In this example, if we accidentally increased the time in the for statement, the
number would keep getting bigger and the loop would never end. Here is an example:
for(int time = 180; time > 0; time++)
By using time++, each time the loop executes it would add one to the time variable and it
would never be less than or equal to zero so it would never stop.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
49
NOTE: Another type of error that can occur when using a for loop is to accidentally add a semicolon after the
for statement. The semicolon indicates the end of a statement, so the program would execute the for
statement, then continue to the code inside the for loop but only execute it one time. Here is an example:
This code would only print the message "counting down" once.
The generic flow of a while loop starts at the top of the code, tests if the condition is true. If
the condition is true, it executes the block of code and returns to the top where it tests the
condition again. Figure 5.4 is a flowchart of a generic while loop.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
50
If the condition never changes to false, this causes an infinite loop. Another common error
when using a while loop is to accidentally add a semicolon after the while statement, this
always causes an infinite loop.
Every for loop can be rewritten as a while loop. Consider the popcorn example from section
5.1. We can start by declaring a timer variable and set it to 180. Then, the test condition for
the while loop can check if the value is greater than zero. Inside the while loop, the timer is
decreased by one each time. Here is a code snippet for this while loop:
Listing 5.2: Code snippet to countdown from 180 to zero using a while loop
int time = 180;
while(time > 0)
{
System.out.print(time + ", ");
time = time – 1;
}
System.out.println("The popcorn is done!! Let’s eat!");
For this code snippet, there are at least two ways to easily cause an infinite loop. The first is
to accidentally add a semicolon after the while test condition, so it looks like this:
while(time > 0);
Remember, in Java the semicolon indicates the end of a statement. So, in this case the time
variable starts at 180 and is never changed so it is always greater than zero.
The second situation that causes an infinite loop is forgetting to change the counter inside the
loop body. Listing 5.3 shows the code snippet for an infinite loop.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
51
Listing 5.3: Code snippet with an error that causes an infinite loop
int time = 180;
while(time > 0)
{
System.out.print(time + ", ");
}
System.out.println("The popcorn is done!! Let’s eat!");
The variable to keep track of the time starts at 180, but it is never changed inside the body of
the while loop. Therefore, this loop repeats until the user cancels the program or it runs out of
memory.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
52
The code for this type of loop is very similar to a while loop, except the test condition is at the
end so the loop always executes at least once. Here is an example of a program that prints a
menu and asks the user to choose from a list of options.
Listing 5.4: Use a Do…While Loop to prompt the user with a menu
1. package fruit;
2. import java.util.Scanner;
3. public class Fruit {
4.
5. public static void main(String[] args) {
6. Scanner in = new Scanner(System.in);
7. System.out.println("What is your favorite summer fruit?");
8. int choice = 0;
9. do {
10. System.out.println("1. Apples");
11. System.out.println("2. Oranges");
12. System.out.println("3. Pears");
13. System.out.println("4. Blueberries");
14. System.out.println("Choose one: ");
15. choice = in.nextInt();
16. } while(choice > 4);
17. System.out.println("You chose: " + choice);
18. }
19. }
In this example, the program presents the user with a list of options. Then, when the user
enters a number, it checks to make sure it is not greater than four since there are only four
options. If the number is greater than four, the condition evaluates to true and the menu is
presented to the user again until they select a number from 1 to 4.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
53
To loop through all the items, we can use a for loop, here is an example:
Now, the enhanced for loop uses a simpler and easier to read syntax. The enhanced for loop
is a great choice when you need to access every element in a collection of elements. The bad
part of this type of loop is that you cannot identify where an element exists in a list. For
example, if you wanted to only print the third element you have to use a traditional for loop.
Listing 5.5 creates an array that contains three string values with the names of three video
games. Then the for-each loop prints out each string. Notice the syntax for the for-each loop,
it starts with the keyword for, then in parentheses it has the data type of the elements in the
list followed by a variable name, v. Next is a colon and the name of the list, videoGames. The
code inside the curly brackets has access to the variable v. In this case, I just printed each
value. Figure 5.7 depicts the parts of a for-each loop. The data type must match the type of
values in the collection.
Listing 5.6: Using an Enhanced For Loop to Print a List of Video Games
String[] videoGames = {"Super Mario Odyssey", "Call of Duty: WWII", "Splatoon 2"};
for(String v:videoGames) {
System.out.println(v);
}
In each of the loop examples in this lesson I used curly brackets to enclose the code that is
executed inside the loop. If there is only one statement that needs to be executed in the loop,
then the curly brackets are optional. So, the following two code snippets will produce the
same results.
for(int i = 0; i<10; i++) { //#A
System.out.println(i);
} //#B
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
54
#A This line has an open curly bracket to indicate the start of the code to be executed inside this loop
#B This is the closing curly bracket for the block of code
#C Since there is only one statement, the curly brackets are optional
This is only true when you have one statement that needs to be executed inside the loop!
5.5 Summary
In this lesson, we learned:
There are many times when you need to repeat a block of code. This is usually the time when
you will choose a loop to control how many times to repeat a block of code. If you know the
number of times you need to repeat these statements, then you can use a for loop. A while
loop is used when it is not clear how many times you want to execute the loop, such as
entering prices for items at a grocery store, you don’t know how many items the customer has
ahead of time. The do...while loop is used when you want to execute the block of code at least
once. And finally, use the for-each loop when the program needs to access every element in a
collection.
In the next lesson, I introduce a capstone project that provides an opportunity to explore the
concepts taught in this unit.
Try This:
Use NetBeans to create a new project. In the main method of the .java file, add a loop to print
the numbers starting from 10 to 1, print each number on a separate line. When the loop
finishes print "blastoff!". Run the program to check your code.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
55
3. Challenge: Write a code snippet to print every other number from 1 to 100 (hint, use the update portion
of the for loop to increase the number by two instead of one)
This statement causes an infinite loop. The problem is that there is a semi-colon immediately following
the for loop condition.
int i = 0;
while(i < 10) {...
i++; }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
56
int j = 10;
while(j >= 0) {...
j--; }
Output:
Mario
Princess Peach
Luigi
Bowser
for(String c:colors) {
System.out.println(c);
}
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
57
Solution:
This activity can be completed using either a for loop or a while loop. Since I want to print the
numbers from 10 to 1, I can use a for loop and print the counter value each time. Figure 5.8
shows a sample solution to this problem.
Figure 5.6: Screenshot of a program to print numbers from 10 to one, then Blastoff!
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
58
6
Arrays and ArrayLists
An array is an object that is used to hold a fixed list of data elements (each item in an array is
referred to as an element) that are the same data type. They are extremely useful and often
used in OO programming. You can think of an array as a list of data elements. The Java
collections API has a list interface that is discussed in a later chapter of this book.
An array can be a list of numbers, Strings, characters, or even a list of boolean values. In
Java, Strings act like primitive data types but they are actually objects. So, an array can store
a list of primitive data or a list of objects. For example, an array can be used to hold the
responses of a student who took a true/false quiz, which would be a list of boolean values. If
the quiz had 25 questions, without an array, we would need 25 variables to hold the student
responses. By using an array, we can hold all 25 values with a single variable.
Consider This
Have you ever purchased a loaf of sliced bread at the grocery store? It usually comes in a single package with individual
slices packed inside. What would happen if we needed to have each slice packaged separately? The individual slices
are similar to creating separate variables for a list of data elements that are all the same data type. Instead, it would
be better to use a single package, in programming terms, an array, to keep track of each individual element with only
one variable.
Can you think of other items that would be better if we could package them together instead of individually?
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
59
Figure 6.1 This diagram describes the syntax of using an array to hold 25 boolean values.
It is possible to declare the array in one statement and then assign the size in a second
statement:
Note:
Arrays are declared with a fixed size. An array cannot automatically expand or shrink depending on the number of
elements added or removed from the array. Using a fixed size is helpful if you know the specific number of elements, it
can save processing time and is very efficient for data access. But if the array needs to grow, it requires the creation of
a new larger array and then copying the current list to the new array so additional elements can be added. This is very
inefficient and significantly increases processing time.
Table 6.1 Examples of arrays with each of the primitive data types in Java
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
60
When an array is created, it is considered an object that contains the address of the first
element in the array. Each subsequent element is stored sequentially in memory. Let’s take a
look at a diagram of an array declared as an int array with 5 elements:
int[] numItems = new int[5];
Figure 6.2 This diagram shows how the array numItems is stored in memory.
Notice that each element contains the value zero since the array was initialized as an int data
type. In Java, integer variables are automatically assigned the value zero unless the initial
declaration assigns a specific value. Table 5.2 shows the default values for each primitive data
type.
String null
boolean false
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
61
Figure 6.3 In this diagram, the index values of each element have been added.
As you can see in this diagram, the first element is stored in position 0 and the last element is
stored in position 4. Notice that the length of this array is 5, so the last element is at the
index value of: 5 – 1 = 4.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
62
When creating an array, the length of the array is automatically stored and accessible through
the length property. For example, in the diagram 5.3, we can obtain the size using the
numItems.length statement. It is important to note that the length is the allocated length
and does not reflect how many elements have values or not.
When creating an array, it can be declared as an empty array that populates the elements
later in the code, or we can provide initial values for our array. So far, I’ve shown several
examples of creating arrays without providing values for the elements in the array. Now, here
are some examples of declaring an array with a starting list of elements:
Table 6.3 This table shows arrays that are initialized with values and the length of each array.
char char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 26
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z'};
Note:
Remember, all elements in the array must be the same data type and to find the size of the array, use the dot notation
to access the length property of the array (for example: numItems.length).
Now that we have created some arrays, let’s look closer at how to access specific elements in
an array and how to modify elements in an array. It is important to remember that the index
of the elements in an array starts at zero and ends at length – 1.
Using the example for an integer array in table 5.2, here is how that data is stored:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
63
Figure 6.4 This diagram shows the structure of an integer array called numStudents with the index values for
each item in the array.
This array represents the number of students in four separate sections of an English class. If
we have a new student who just started, we need to increase the number of students for the
new student’s section. If the student is in the third section, we need to change the value from
10 to 11, in other words, add one to the value at index 2 (remember, the indices start at zero,
so the third value is in index value 2).
numStudents[2] = numStudents[2] + 1;
To access an element in an array, we start with the array name, and then place the index of
the element in square brackets. For this example, I am changing the value in numStudents at
index 2 to be increased by 1.
Note:
A common mistake when working with arrays is to forget that the first index starts at zero. Then, if you try to access the
last element, your index value will be one more than the last valid index value and this causes an out of bounds
exception error. For example, if the array numStudents has 4 elements, this statement causes an error:
numStudents[4] = numStudents[4] – 1;
Note that the error message provides the index value that caused the out of bounds error. In this case, it was the value
4, but the last index value is 3.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
64
To traverse every element in an array, it is a common programming practice to use a for loop.
The for loop provides an easy way to evaluate every element in an array. Here is an example
of code that prints every element of an array:
Listing 6.1 Example of a for loop that prints all letters in the array alphabet
1. char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
2.
3. for(int i = 0; i < alphabet.length; i++) //#A
4. { System.out.print(alphabet[i]); } //#B
5. System.out.println();
#A This for loop traverse each element in the alphabet array, starting at zero and stopping at length-1
#B The print statement uses the loop control variable, i, to print each element
Without arrays, this code would require 26 variables, one for each letter of the alphabet. But
with arrays, we can use one variable name and store all values in the array with one variable
name.
The for loop starts by printing the element at position zero and stops at one less than the
length of the array. A for loop can also be used to populate an array. For example, here is
code that creates an integer array and populates the array with even numbers from 0 to 100
(not including 100).
Listing 6.2 This code creates an integer array containing even numbers from 0 – 100
1. int index = 0; //#A
2. int[] evenNumbers = new int[50]; //#B
3. for(int i = 0; i < 100; i++) //#C
4. { if(i % 2 == 0) { //#D
5. evenNumbers[index] = i; //#E
6. index++; //#F
7. }
8. }
#A It is important to have a value to track the location of the element in the array
#B Create an array to hold 50 integers
#C Use a for loop to evaluate each number between 0 and 100
#D Check if dividing by 2 produces no remainder and therefore the value is even
#E If the value is even, then store that value in the next open spot in the array
#F Increase the index by one to the next open spot in the array
NOTE: In Java, the symbol % is used for modulus division. Modulus division divides two integers and only
returns the remainder portion of the operation. For example, 4 % 2 yields zero, but 5 % 2 yields 1.
The next section shows how to create an ArrayList to hold a list of objects.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
65
a. 4
b. 6
c. 5
2. What is the index value of the element containing the value 15:
a. 3
b. 4
c. 2
a. 14.85
b. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
c. 0
a. prices[2] = 15.75;
b. prices[1] = 15.75;
The Arrays class provides numerous methods that make manipulating arrays easy. This
particular class is a static class, which means that it is not invoked using dot notation on an
object, instead, it can be used to perform operations on one or more arrays. Some examples
of the types of manipulations available through this class include:
• binarySearch
• copyOf
• copyOfRange
• equals
• fill
• sort
• and toString
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
66
Each of these operations has multiple variations, but they make working with arrays much
easier. For example, to print the contents of an array, I can use the toString method. Figure
6.5 shows the output of printing an array with and without using the Arrays class.
Figure 6.5 Screenshot of output showing two ways to print an array variable
The code listing used to demonstrate the use of the Arrays class is in Listing 6.3.
Listing 6.3 This code prints and array with and without using the Arrays class
1. package test;
2. import java.util.Arrays; //#A
3. public class ArrayAPIExample {
4. public static void main(String[] args) {
5. double[] prices = {10.50, 5.75, 13.90, 15, 14.85};
6. System.out.println("Print the value of the prices array "
7. + "without using the Arrays class: " + prices); //#B
8. System.out.println("Print the value of the prices array
9. + "using the Arrays class: " + Arrays.toString(prices)); //#C
10. }
#A This line uses the import statement to provide access to the Arrays class
#B Since an array variable contains the reference address of the first element in the array, the value printed with this
statement is just a hexadecimal representation of a memory address
#C Using the Arrays class and the toString method, it is easy to print all elements in the array
1. Given an int array, ages, which statement correctly sorts it in ascending order:
a. sort(ages);
b. Arrays.sort(ages);
c. ages.Arrays.sort;
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
67
An ArrayList can dynamically change size, which is a great feature, but it comes at a cost.
When an array is declared, it must specify a size, but because arrays are a fixed size based on
the array type declaration, they do not require as much memory as their ArrayList
counterparts.
In this section, I will provide a brief overview of ArrayLists so we can use them to hold
objects, but later in the book, Lesson 26 Collections where I will provide even more detail
about ArrayLists and their uses in OO programming.
Similar to arrays, when creating an ArrayList we start with the data type. The big difference is
that an ArrayList can only be used with class data types. In lessons 2-4, I introduced a Car
class and each time I wanted to create a car object, I had to create a new variable. Now, I
can use an ArrayList to hold a list of Car objects with only one variable. Here is an example:
Figure 6.5 This diagram identifies the parts of an ArrayList used to create a new empty ArrayList of car objects
The ArrayList in figure 6.6 contains a list of Car objects. The syntax used to denote the type
of data in the ArrayList is called a diamond operator and was introduced with Java 7. When
using the diamond operator, the compiler only requires the diamond on the left to include a
value. So, we could rewrite this statement as:
ArrayList<Car> usedCars = new ArrayList<>();
This structure is used with Generics which is addressed later in this book.
The variable, usedCars, is essentially a reference to the start of a list of Car objects.
In the next section, I will add elements, modify existing elements, remove elements and
access elements in an ArrayList.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
68
import java.util.ArrayList;
This class comes with the Java API and it includes methods that can be used to add elements,
remove elements, get elements, and even set elements in the list. There are quite a few
methods available, but let’s start with a list of the most commonly used methods with
examples of each method.
element set(index, Replaces the element at the index specified, returns the element that was
element) replaced
Now that I have reviewed how to create an ArrayList and provided some of the methods for an
ArrayList, let’s modify the main method in our Car class to add an ArrayList of car objects.
Table 6.6 shows the information for each car. For this activity, I will create an ArrayList of
used cars, add car objects to the list, print the number of cars in the list and then remove a
car from the list.
Table 6.6 shows the information for three used car objects
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
69
Figure 6.6 This is the output from the code in listing 6.4 which uses an ArrayList to hold a list of used cars.
Listing 6.4 Car class that uses an ArrayList to hold a list of used cars
public class Car {
… //#A
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
… //#B
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
70
Figure 6.7 Shows the stages of the usedCar ArrayList as cars are added and removed
1. What make and model of car is returned from the statement: usedCars.remove(0):
a. Chevrolet Camaro
b. Toyota Camry
c. Dodge Dart
2. For the next few questions, consider the following code is added to the end:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
71
2. If I added the statement: usedCars.add(myCar), where would this car get added to the list?
a. Beginning
b. End
c. Causes an Index Out of Bounds Exception
3. What is the size of the ArrayList after I add myCar to the list:
a. 4
b. 3
c. 5
6.6 Summary
In this lesson, you learned:
In this lesson you learned how to create and use both arrays and ArrayLists to hold lists of
data. Remember, arrays are a fixed size and can only be used with primitive data. ArrayLists
can only hold objects but they are much more flexible for adding/removing items from the list.
In the next lesson, I will introduce a problem and a solution that uses all the topics from
Lessons 1-6.
Try this:
Using the concepts from the previous lessons, create a Student class that includes the student
first and last name, email, and course. Next, create an ArrayList of all students in the course.
Print out the list of students and the number of students in the course.
Try using some of the ArrayList methods to add students, remove students at various
locations in the ArrayList, and even change the student at the beginning of the list using the
set method.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
72
a. 4
b. 6
c. 5
2. What is the index value of the element containing the value 15:
a. 3
b. 4
c. 2
a. 14.85
b. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
c. 0
a. prices[2] = 15.75;
b. prices[1] = 15.75;
c. array elements cannot be changed
1. Given an int array, ages, which statement correctly sorts it in ascending order:
a. sort(ages);
b. Arrays.sort(ages);
c. ages.Arrays.sort;
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
73
1. What make and model of car is returned from the statement: usedCars.remove(0):
a. Chevrolet Camaro
b. Toyota Camry
c. Dodge Dart
2. For the next few questions, consider the following code is added to the end:
3. If I added the statement: usedCars.add(myCar), where would this car get added to the list?
a. Beginning
b. End
c. Causes an Index Out of Bounds Exception
5. What is the size of the ArrayList after I add myCar to the list:
a. 4
b. 3
c. 5
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
74
8. this.fName = fName; }
9. public String getlName() {
10. return lName; }
11. public void setlName(String lName) {
12. this.lName = lName; }
13. public String getEmail() {
14. return email; }
15. public void setEmail(String email) {
16. this.email = email; }
17. public String getCourseName() {
18. return courseName; }
19. public void setCourseName(String courseName) {
20. this.courseName = courseName; }
21. public String toString() {
22. return fName + " " + lName + ", email: "+ email + ", course: " +
23. courseName ;
24. }
25. public static void main(String[] args) {
26. Scanner in = new Scanner(System.in);
27. String firstName, lastName, emailAddress, course;
28. boolean done = false;
29.
30. ArrayList<Student> roster = new ArrayList<Student>(); //#A
31. while (!done) {
32. System.out.println("Enter first name, last name, email, and " +
33. "course name ");
34. firstName = in.nextLine();
35. lastName = in.nextLine();
36. emailAddress = in.nextLine();
37. course = in.nextLine();
38. Student s = new Student(); //#B
39. s.setfName(firstName); //#B
40. s.setlName(lastName); //#B
41. s.setEmail(emailAddress) //#B
42. s.setCourseName(course); //#B
43. roster.add(s); //#C
44. System.out.println("Want to enter another student? (y/n) ");
45. if (in.nextLine().equalsIgnoreCase("n")) {
46. done = true;
47. }
48. }
49. System.out.println("These are the students in the course: ");
50. System.out.println(roster);
51. System.out.println("There are " + roster.size() + " students\n");
52. roster.remove(0); //#D
53. Student newStudent = new Student();
54. newStudent.setfName("Pat");
55. newStudent.setlName("Slattery");
56. newStudent.setEmail("[email protected]");
57. newStudent.setCourseName("English");
58. roster.set(1, newStudent); //#E
59. System.out.println("Students remaining: ");
60. System.out.println(roster);
61. System.out.println("There are " + roster.size() + " students\n");
62. }
63. }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
75
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
76
7
Capstone 1
This lesson is a capstone of these topics providing you with the opportunity to reinforce the
skills learned. In this lesson, I will introduce a problem that is designed to include everything
presented so far in the book.
In this lesson, I will walk through the process of creating a simple payroll application. Let’s
start by thinking about the problem, what are we trying to accomplish? The program needs to
create the weekly payroll for each employee. Sounds simple, but what about overtime? How
about employees who are paid annually? First, it is important to gather the business
requirements for our problem.
For this problem, I will act as the company owner. Here are the requirements for this
assignment:
• The payroll report prints the employee first name, last name, and weekly earnings
• Hourly employees earn overtime for any hours greater than 40 in one week
• Overtime hours are paid at a rate of 1.5 times their regular hourly rate
• Salaried employees are paid their annual salary divided by 52 each week
NOTE: Some years have 53 weeks in a year, but this program will keep it simple and use only 52 weeks.
Now that I have explained our problem, let’s walk through a solution using Java. The next
section describes the process of flowcharting our business problem to be used as a guide for
writing code for our final solution.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
77
For this example, the payroll application is pretty simple. If the employee is paid hourly, the
application asks for the hourly wage and hours worked. Otherwise, the annual salary is
entered for the employee. Based on the employee type, the weekly payroll is calculated. In
the next few sections, I will review the Java code necessary for creating a complete payroll
program.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
78
• First name
• Last name
• Type (hourly or salaried)
• Hourly rate
• Hours worked
• Salary
Listing 5.1 shows the code necessary for the class and the instance data.
The Employee class now has the necessary instance data, the next section adds the getter and
setter methods for each instance data field.
So, for each piece of instance data, I am adding the getter and setter method. Here is the
revised code including these methods. Note: these methods are declared as public so the
main program can access them.
Listing 7.2 Adding getter and setter methods to the Employee class
1. class Employee {
2. private String firstName, lastName; //#A
3. private char employeeType; //#A
4. private double hourlyWage, salary, hoursWorked = 0; //#A
5. public void setFirstName(String fName) { //#B
6. firstName = fName; } //#B
7. public String getFirstName() { //#B
8. return firstName; } //#B
9. public void setLastName(String lName) { //#B
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
79
Listing 7.3 Add a method to calculate the weekly payroll for an employee
1. //code omitted
2. protected double calculateEarnings() {
3. double weeklyEarnings;
4. if (employeeType == 'h') { //#A
5. if (hoursWorked <= 40) {
6. weeklyEarnings = hoursWorked * hourlyWage;
7. } else {
8. weeklyEarnings = 40 * hourlyWage + ((hoursWorked - 40)
9. * hourlyWage * 1.5);
10. }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
80
#A This code checks if the employee is paid hourly (if the type = 'h')
#B This else statement indicates that this employee is not hourly, therefore they must be salaried
The next method that I want to add is a way to format the output for printing the employee
information including the weekly payroll. Every class automatically has a toString() method,
but it does not format the information the way we want. So, in Listing 7.4 I have added a new
toString() method for our Employee class.
#A The \t is an escape sequence and causes the output to include a tab character sequence
#B The \n is also an escape sequence that is used to print the string on the next line
7.5 Wrap It Up
Now that the Employee class is created, we can go back to the main method and start adding
employees. To allow for multiple employees, I am using an ArrayList of type Employee to hold
the list of employees. The program starts by asking the user to enter the employee
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
81
information and then indicate when they are done by answering the query: Do you have more
employees to enter? (y/n).
After all the employees have been stored in the ArrayList, I will iterate through the list and
print out the weekly earnings for each employee. Listing 7.5 shows the complete application.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
82
49.
50. return "First Name: " + getFirstName()
51. + "\tLast Name: " + getLastName()
52. + "\nHourly Rate: " + getHourlyWage()
53. "\tTotal wages: $" + calculateWeeklyEarnings()
54. + "\n";
55. }
56.
57. public static void main(String[] args) {
58. Scanner in = new Scanner(System.in);
59. String fName, lName, response = "y", hourly = "";
60. char type;
61. double hrlyWage = 0, hrsWorked = 0, salary = 0;
62. ArrayList<Employee> employees = new ArrayList<Employee>();//#D
63. while (response.equalsIgnoreCase("y")) {
64. System.out.println("Enter first name: ");
65. fName = in.nextLine();
66. System.out.println("Enter last name: ");
67. lName = in.nextLine();
68. System.out.println("Is this employee paid hourly? (y/n)");
69. hourly = in.nextLine();
70. if (hourly.equalsIgnoreCase("y")) {
71. System.out.println("Enter hourly wage: ");
72. hrlyWage = in.nextDouble();
73. System.out.println("Enter hours worked: ");
74. hrsWorked = in.nextDouble();
75. type = 'h';
76. } else {
77. System.out.println("Enter yearly salary: ");
78. salary = in.nextDouble();
79. type = 's';
80. }
81. Employee tempEmployee = new Employee();
82. tempEmployee.setEmployeeType(type);
83. tempEmployee.setFirstName(fName);
84. tempEmployee.setLastName(lName);
85. if (type == 'h') {
86. tempEmployee.setHourlyWage(hrlyWage);
87. tempEmployee.setHoursWorked(hrsWorked);
88. } else {
89. tempEmployee.setSalary(salary);
90. }
91. in.nextLine();
92. employees.add(tempEmployee);
93. System.out.println("Are there more employees? (y/n)");
94. response = in.nextLine();
95. }
96. for (Employee e : employees) { //#E
97. System.out.println(e.toString());
98. }
99. }
100. }
#ASeveral of the setter methods have logic to validate the data before making the change
#B This method is used to calculate the employee weekly salary
#C Adding a toString method helps print the object in a readable format
#D Create an ArrayList of type Employee to keep a list of employee objects
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
83
It is always important to test your program. So, here is a scenario for a local pizza owner,
Paolo, who is the owner of Paolo’s Original Italian Pizza. He has two full time employees that
are salaried, and five employees that are paid hourly.
Using table 7.1, I will execute our code and print each employee’s weekly earnings.
First name Last name Type Salary Hourly Wage Hours worked Weekly Paycheck
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
84
7.6 Summary
In this lesson, I reviewed the initial business problem of creating a payroll application, used a
flowchart to diagram our potential solution, and then walked through the code necessary for
each part of the flowchart.
• The payroll report prints the employee first name, last name, and weekly earnings
• Hourly employees earn overtime for any hours greater than 40 in one week
• Overtime hours are paid at a rate of 1.5 times their regular hourly rate
• Salaried employees are paid their annual salary divided by 52 each week
TRY THIS:
A friend has started a new business selling produce grown in her own garden. Some items are sold by the
pound, while others are priced based on quantity. For example, tomatoes are 1.99 per pound, but zucchinis
are 2 for 1.00.
Create a Produce class that helps your friend easily calculate the total due for each customer. Some
customers are purchasing multiple items, so use an ArrayList to keep track of all the produce they purchase
during one transaction, then print out the total due.
Add the capability to enter the amount tendered by the customer and calculate the change as a little challenge
to this activity.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
85
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
86
#A An import is required to use the ArrayList class from the Java API
#B Create an empty ArrayList to hold the Produce objects
#C Create a new instance of the Produce class
#D Update the product name and price for the current produce item
#E Add the object just created to the end of the ArrayList
#F Print the produce information, this statement uses the toString method defined in the Produce class
#G Use an enhanced for loop to add the cost of all produce items in this transaction
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
87
Unit 2
Application Programming Interface (API)
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
88
8
Standard Java API
The Java API, Application Programming Interface, contains the set of classes and interfaces
included with the Java Development Environment that are used to build application software.
Each class is written in Java and runs on the JVM, Java Virtual Machine.
The idea of the API is to take commonly used classes and make them available to all
developers, so they don’t need to recreate the code required for these common tasks.
This lesson introduces the topic of the Standard Java API and provides examples of some of
the more commonly used classes included in the library.
Consider This
Have you recently purchased a new smart phone? Or even a new laptop or desktop? Each of these products come with
pre-installed software and apps. So, instead of writing an app to keep track of your contact list, you can use the contact
app that was already pre-installed. There are probably numerous tools on your device that were available when you
first started using the device.
Cell phone and computer manufacturers have decided that some tasks are commonly used by all owners of the
products. So instead of having each owner program their own OS or program the features that allow you dial numbers
and make a call, they come preinstalled.
The Standard Java API includes many classes that a developer normally needs for a software application. For example,
the Scanner class allows us to read data entered from the console window. Another example is the Math class, this
class contains methods for finding the square root of a number or the result of raising a number to a power. Can you
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
89
think of other common tasks that might be required by most developers? Check out the Oracle documentation to see if
that feature exists.
Here is a list of some packages that are commonly used in Java programming:
java.awt – contains classes for creating graphical user interfaces and painting graphics
java.io – used for input and output through data streams, serialization and the file system
java.lang – provides classes necessary to the design of the Java programming language
java.util – contains the collections framework, date and time, and other utility classes
Oracle maintains an extensive set of documentation for the Java API. This is a great resource
and extremely useful for using the various classes and interfaces included in the API. The
most recent version (during the writing of this text) can be found at this url:
https://docs.oracle.com/javase/8/docs/api/
Figure 8.1 A screenshot of the Java Platform Standard Edition 8 API Specification
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
90
To better understand how to use this documentation, let’s drill down on one of the packages.
Since we have already used the ArrayList class in our last unit to hold a list of objects, we will
start with this class.
There are several options for finding the specified class. If you are not sure which package
contains the class, use the list of All Classes in the left column, shown in Figure 8.1. For the
ArrayList, I know that it is included in the java.util package. So, on the top left I chose
java.util, then in the list of classes, I chose ArrayList and the main panel now shows the
ArrayList class.
Figure 8.2 A screenshot of the ArrayList class documentation inside the java.util package
The next step is to scroll down in the main panel to see the list of methods that are included
for this class. Figure 8.3 is a screenshot of the main panel where I scrolled down to the
section on Constructors and Method Summary. The constructors are also methods and these
can be used to create an ArrayList object or instance. The first constructor creates an empty
list with an initial capacity of ten. The second constructor creates an ArrayList that starts with
an initial collection of elements. The last constructor provides the ability to create an ArrayList
with an initial capacity other than the default of ten.
The method summary section lists all methods available when using an ArrayList in our
application. The code for implementing these actions has already been written and tested so
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
91
it is now available to all developers. This eliminates the individual developer from reinventing
the wheel (or the code in this case) for adding an element to the ArrayList.
The first four methods in the list are variations of adding elements to the list. The first item
includes a capital E and a small e to represent the Element class being added. Remember,
only objects can be added to an ArrayList. In our Car class from lesson 5, to add an object to
the ArrayList, we used:
usedCars.add(oldCar1);
This is an example of using the method add(E e) from this list. Notice that there is a return
type listed for this method, boolean. It returns the value true if the element was successfully
added.
Generic class
If you look at figure 8.2, you will see the notation: Class ArrayList<E>, where the value E inside of the diamond (< >)
acts as a placeholder for the specific class type. This notation is used to indicate a generic class. Generics enable
classes to be parameters when defining other classes. For example: ArrayList<String> names, uses the
ArrayList class to create a list of objects that are instances of the String class. Unit 4 has a detailed lesson on
Generics in Java.
Non-static methods require an object to act upon. But static classes are independent of any
specific instance of the class. The Math class is a great example of static methods. The Math
class has numerous static methods, for example, if we want to find the square root of 160, we
don’t have to create an object to use the Math class. Instead, we can use dot notation on the
class itself:
Math.sqrt(160);
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
92
Figure 8.3 A screenshot of the documentation for the methods included in the ArrayList class
Listing 8.1 shows an example of code that uses an ArrayList to hold a list of ice cream flavors.
In this code snippet, I have created an initial list of flavors and then created a second
ArrayList with two more flavors, add this second list to the original list. A String object
represents a sequence of characters. In the java.lang package there are several interesting
classes, including Boolean, Byte, Character, Double, Float, Integer, Long, and Short. These
classes are called Wrapper classes and I will provide insight into their use in section 8.3.
Figure 8.4 A screenshot of the output showing a list of ice cream flavors created with an ArrayList
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
93
8. iceCream.add("Teaberry"); //#B
9. System.out.println("Elements in the iceCream ArrayList: "
10. + iceCream);
11.
12. ArrayList<String> flavors = new ArrayList<String>();
13. flavors.add("Fudge");
14. flavors.add("Neopolitan");
15. System.out.println("Elements in flavors: " + flavors);
16.
17. iceCream.addAll(flavors); //#C
18. System.out.println("Ice Cream plus flavors: " + iceCream);
19. }
20. }
a. fruit.add(5);
b. fruit.add("apple");
c. ArrayList<String> list = new ArrayList<String>(fruit);
d. ArrayList<Double> list2 = new ArrayList<Double>(fruit);
The Scanner class can also be used to read data from a file.
Once the Scanner object is created, there are several methods that can be used to parse the
input into tokens. For example, the Scanner class has a method that can check the next value
to determine the type of data. If you are expecting the value to be an integer, there is a
method that returns true or false depending on the data. There are methods for all the
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
94
primitive data types, even a method that checks for any data at all, hasNext(). Each method
listed in Table 8.1 returns a value of true or false.
Method
hasNext()
hasNextBoolean()
hasNextByte()
hasNextDouble()
hasNextFloat()
hasNextInt()
hasNextLine()
hasNextLong()
hasNextShort()
Similar methods exist for actually reading the values. It is important to note that the hasNext
method only check for next token in the scanner’s input and does not actually remove the
data from the input stream. For example, we can use the hasNextInt() method to check for an
integer. If the value is an integer, then the result is true, but we must then use nextInt() to
retrieve that value. Listing 8.2 is code that can be used to test that the user entered an
integer value.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
95
Another useful class is the Object class. This class can be used to refer to any Object,
regardless of its original Class type. For an example of using the Object class, refer to figure
8.5 which shows the sample output from executing the code in listing 8.3.
In this example, I used two of the methods from the Object class: toString() and
getClass(). Other helpful methods include clone() and equals(Object o). Since Strings
are stored as objects in Java, we cannot use the == to compare two String objects. So, if we
want to compare these two objects, the code must use the .equals(Object o) method from the
Object class to make the comparison. If we tried to use ==, the program would try to
compare the reference value of each object, which contains the location in memory for each
object. This is only the same when two objects are pointing to the exact same location, in
other words, they are aliases of each other. Also, in this example, I have explicitly
imported the java.lang.Object class, but it is not required. The java.lang package is
imported by default into every Java program.
System.out.println(obj.equals("Wednesday"));
a. true
b. false
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
96
Table 8.2 This table shows the corresponding wrapper class for each primitive data type.
Integer(int value)
int Integer
Integer(String s)
Double(double value)
double Double
Double(String s)
Boolean(boolean value)
boolean Boolean
Boolean(String s)
Character(char value)
char Character
Character(String s)
Float(float value)
float Float
Float(String s)
Short(short value)
short Short
Short(String s)
Byte(byte value)
byte Byte
Byte(String s)
Long(long value)
long Long
Long(String s)
Table 8.2 lists the constructors for each of the wrapper classes. It is easy to create objects
from either the corresponding primitive data type or even a String. For example:
Integer a = new Integer(5);
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
97
Here is an example, many educational institutions use Learning Management Systems (LMS)
to help track students in a class, along with their grades during a semester. When designing
the LMS, the developer needs to allow for a course that has a small number of students, but it
also has to handle courses with very large numbers of students.
To keep track of the grades for a particular assignment, it makes sense to use an ArrayList so
it can grow and shrink as needed. Once the ArrayList is declared, a loop can ask the user to
enter grades using -1 as the sentinel value to indicate there are no more grades to be
entered.
Listing 8.4
1. ArrayList<Double> grades = new ArrayList<Double>();
2. double grade = in.nextDouble();
3. while(value >= 0) {
4. grades.add(grade); //#A
5. System.out.println("Enter next grade: ");
6. grade = in.nextDouble();
7. }
#A Line 4 shows how the grade variable is autoboxed from double to Double when added to the ArrayList
Autoboxing is the term used to describe the conversion from a primitive data type to its
corresponding wrapper class. This occurs automatically by the compiler when a primitive data
type is added to an ArrayList. The compiler also unboxes automatically when the values are
taken from the ArrayList and put into a primitive data type. Listing 8.4 shows the code for
finding the average of a series of grades.
Listing 8.5 Code used to read grades and find the average
1. import java.util.ArrayList;
2. import java.util.Scanner;
3. public class Grades {
4. public static void main(String[] args) {
5. Scanner in = new Scanner(System.in);
6. ArrayList<Double> grades = new ArrayList<Double>(); //#A
7. System.out.println("Enter first grade: ");
8. double value = in.nextDouble(); //#B
9. while (value >= 0) {
10. grades.add(value); //#C
11. System.out.println("Enter next grade: ");
12. value = in.nextDouble();
13. }
14. double total = 0, count = 0;
15. for(double s: grades) { //#D
16. total += s;
17. count++;
18. }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
98
Table 8.3 This table shows a subset of the methods for the Integer class.
x.equals(y)
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
99
*Static methods
In table 8.3, some of the methods have the class name preceding the method name, such as
Integer.compare(x,y). This syntax indicates that the method is associated with the class and not a specific
instance of that class.
Non-static methods require an object to act upon. But static classes are independent of any specific instance of the
class. The Math class is a great example of static methods. The Math class has numerous static methods, for example,
if we want to find the square root of 160, we don’t have to create an object, we can use Math.sqrt(160);
a. numbers.add(new Integer(5));
b. numbers.add(5);
c. int x = numbers.get(0);
a. numbers.add(new Integer(5));
b. numbers.add(5);
c. int x = numbers.get(0);
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
100
a. negative value
b. zero
c. postive value
a. negative value
b. zero
c. postive value
8.4 Summary
In this lesson, you learned:
As you can see from the examples in this lesson, the Java API contains many useful classes
and interfaces. As we continue to discuss object-oriented topics in Java, we will rely heavily
on the code made available by the Standard Java API.
This lesson also introduced the topic of Wrapper classes. A wrapper class converts a primitive
data type to an object. Each primitive data type has a corresponding wrapper class. There
are several ways to convert between the object and the primitive value, the easiest is
autoboxing and unboxing since this is done automatically by the compiler. But there are
several methods that can be helpful especially if you want to convert a number inside a String.
In the next lesson, I will explore the String and StringBuilder classes.
Try this:
Given the information for the Arrays class in figure 8.6, which is in the Java.util package,
write code that creates two integer arrays and then compares the arrays to determine if they
are equal. Instead of looping through each element, use the documentation provided to use
the equals(int[] a, int[] b) method to compare the two arrays.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
101
Figure 8.6 Screenshot of Java API documentation for the Arrays class
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
102
System.out.println(obj.equals("Wednesday"));
a. true
b. false
a. numbers.add(new Integer(5));
b. numbers.add(5);
c. int x = numbers.get(0);
a. numbers.add(new Integer(5));
b. numbers.add(5);
c. int x = numbers.get(0);
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
103
a. negative value
b. zero
c. postive value
a. negative value
b. zero
c. postive value
Figure 8.7 Screenshot of output from executing the code in listing 8.4
Listing 8.4 Use the .equals method to check if two arrays contain the same values
1. import java.util.Arrays;
2. public class Test {
3. public static void main(String[] args) {
4. int[] numbers = {1, 2, 3, 4, 5, 6, 7};
5. int[] numbers2 = {2, 3, 4, 5, 6, 7, 8};
6. if(Arrays.equals(numbers, numbers2)) //#A
7. System.out.println("The two arrays are equal! ");
8. else
9. System.out.println("The two arrays are not equal! ");
10. System.out.println("First array: " + Arrays.toString(numbers)); //#B
11. System.out.println("Second array: " + Arrays.toString(numbers2));
12. }
13. }
#A Compare two integer arrays using the method from the Arrays class
#B Use the toString method from the Arrays class to print all values of each array
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
104
9
String and StringBuilder Classes
This lesson introduces the topic of strings in Java. In Java, strings are objects. A string
represents as a sequence of individual characters, such as a word or sentence. The String
class is widely used in Java and has over sixty methods and thirteen constructors. in addition
to the String class, Java also has a StringBuilder class.
Consider This
I’m sure you have been on the receiving end of a piece of mail generated by a marketing firm. Although my physical
mail (sometimes referred to as snail mail) has decreased over the years, I still receive solicitations weekly for a new
credit card, or maybe even a home equity loan. These mailings have become more personalized over the years,
including my name in the actual letter.
This is an example of how a program can be used to merge text. Many programs need to process text and often
navigate a large amount of text looking for specific data. For marketing, the company usually has a large list of names
and addresses that is the input to a program. This information has to be separated into first name, last name, address
line 1, optionally an address line 2, etc. As you think about this process can you think of other types of text that
appears on things we own? How about the information printed on a cereal box? Or even the information in this text
book. These are all examples of programs that needed to process text and in Java that means they need to read and
manipulate strings.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
105
In this example, the grocery item value is considered a string literal, which is a sequence of
characters enclosed in double quotes. Behind the scenes, the literal is stored as an array of
characters and the variable name contains the reference value to find that array in memory.
Figure 9.1 Diagram of a string saved as individual characters with a reference variable that points to the start of
the array
NOTE:
It is important to note that String literals are immutable (cannot be changed). Java stores string literals in a string pool.
All String literals are enclosed in double quotes.
It is often helpful to find the length of a string object. The String class has a method,
.length(), which returns an integer value representing the number of characters in a string,
including white space characters such as the end line symbol ("\n"). The code snippet below,
finds the length of a string entered by the user, then prints out the length:
Figure 9.2 Shows how to use the .length method and how to combine strings
Notice the plus sign in the println statement. In this example, when a string is combined with
an integer, it automatically converts the integer value as another string and puts them
together. Here we have a string, a number, then another string. All three values are printed
as one string. For example, if the user enters the sentence “Today is Wednesday”, the output
would be:
The sentence has 18 characters.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
106
There is also a method that can be used to concatenate (or put together) two strings, it is
.concat(). Here are some examples of using this method:
String s1 = "apples";
String s2 = "oranges";
String s3 = s1.concat(" and ").concat(s2);
System.out.println(s3);
In the example, I had to create a new variable to hold the result of combining s1 and s2
(notice in this example I am actually chaining two calls to the concat method to create the
final version of the String which is “apples and oranges”). Remember, strings cannot be
changed directly in Java, they are immutable. In the next section, I will review formatting
numbers in a string.
a. 19
b. 18
c. 17
d. 20
NOTE: In Java, the word null is actually reserved as a special value that is recognized by the compiler to
indicate that the object is only a reference and does not actually contain any value. Consider it a reference to
nothing. In my example, it allows me to create a new string variable without adding any extra characters. The
null value is used often in object-oriented programming. It provides an easy test for an object to see if it has
been instantiated. Remember out Car class from lesson 2? If we create a Car object, but don’t use the new
keyword and don’t initialize it in any way, it creates a null object, Car car1; Right now, car1 is considered a null
object.
In Lesson 8 we learned about the wrapper classes that exist for all of the primitive data types.
Each numeric wrapper class has a valueOf() method that retrieves the numeric value from a
string. This is helpful when parsing string data to find the numeric values in the String. Let’s
look at a program that starts by asking the user to enter a list of numbers separated by
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
107
commas. Using that list, the program needs to find the average and then print all the values
as integers.
In order to separate the numbers from the commas, I start with the String class method
.split(). This method uses a delimiter to split the string, in this case it will split it every time
it encounters a comma followed by a space. The split method removes the specified value and
returns an array of string values. Once the array is created, I can use the wrapper class
method, valueOf(), to convert the string to a number. Then, it is easy to process the Integer
ArrayList and find the average.
Figure 9.3 Screen shot of the output from code in Listing 9.1
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
108
#A The String method, split(), is used for separating strings into parts
#B Use the valueOf() method to covert the strings to integers
#C Use formatting to print the average to only two decimal points
In this example, I demonstrated how to split a string into smaller strings and convert strings
to numeric values so they can be used in a mathematical computation.
a. input.split(";")
b. input.parseString(";")
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
109
When working with strings, it is often helpful to access individual characters in the string. A
combination of the .length() and .charAt(int index) methods can be used together to
access each individual character in a string. Here is a code snippet that prints each character
in reverse order:
for(int i = sentence.length() - 1; i >= 0; i--) {
System.out.print(sentence.charAt(i));
}
It is important to remember that the characters in a string start at index 0, so the last
character is located at length – 1. If the program tries to access the character at the index
length, it will be out of bounds. In this code snippet, I started the index value at the last
character and subtract one each time. Once the value gets to -1 it will stop.
For example, if the program needs to ask the user for a response such as “yes” or “no”, it
might help to convert the string to either all upper case or lower case first. That way if the
user enters “Yes” or “yes”, we know they are the same answer. Here is a simple code snippet
that converts the user response to all lower case before we check to see if the value matches
“yes” or “no”:
response = in.next().toLowerCase();
if(response.equals("yes")) System.out.println("You entered yes");
Another option is to use the comparison method that ignores upper and lower case letters and
just checks to see if the words match:
if(response.equalsIgnoreCase("yes")).
Before moving on to the next section, I want to review how to use the substring method. This
method returns part of the original string. If only one index value is included in the argument
list, then it will start at that value and return everything from there until the end.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
110
If the substring method has two values, then it starts at the first index value and stops at one
less than the second value. Here are some examples, given the original string: String name
= "Peggy Fisher";
Figure 9.2 Diagram of the string variable name showing the index values of each character
Here is the code to retrieve the first name and last name using the substring method:
String firstName = name.substring(0,5);
String lastName = name.substring(6);
Notice that the first statement starts at position zero but stops at one position prior to the
space so that the entire first name is now in the variable firstName. The next statement starts
at position 6 and goes to the end, so it now has the string "Fisher".
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
111
The alternative is to use a StringBuilder object when we know that the String object might
need to be updated in one of these ways: appending strings, inserting strings, replacing
characters or string subsets, reversing a string, deleting all or part of a string.
To explain the methods that facilitate these actions in the StringBuilder class, Listing 9.2
shows a complete program that uses some of these methods. This program asks the user to
enter a word or phrase, then checks to see if the string is considered a palindrome. A
palindrome is a word or sentence that is spelled the same way forward and in reverse, such as
racecar, civic, level, kayak, noon, and so on.
Notice that I do not need to import the StringBuilder class, it is also part of the java.lang
package which is automatically imported for all Java programs.
In Listing 9.2, the code starts by creating a new StringBuilder object, text. Then using the
.append method from the StringBuilder class, the word/phrase entered by the user is added to
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
112
the empty object. To test if this is a palindrome, the program creates a second object that
contains the same value in reverse. Notice that line 11 creates a second StringBuilder object
that is then assigned the value of the original string in reverse order using the methods on line
12. Now it is easy to test if this is a palindrome but just comparing the two strings character
for character to see if they are the same.
NOTE: since StringBuilder objects have a toString() method, it is possible to make this code even shorter by
using this if statement:
if(text.toString().equals(textReversed.toString()))
System.out.println(text + " is a Palindrome!!");
The StringBuilder can be used when we need to combine two strings without creating a third
string. Consider a program that starts by asking the user for their name and then prints out a
greeting using their name. What StringBuilder methods should this program use? Listing 9.3
shows one version of how this program can be written:
Listing 9.3 This program prints a greeting using the user name and time of day
1. import java.util.Scanner;
2. public class Greeting {
3. public static void main(String[] args) {
4. Scanner in = new Scanner(System.in);
5. StringBuilder greeting = new StringBuilder(); //#A
6. System.out.println("Enter your name: ");
7. String name = in.nextLine();
8. greeting.append("Hello, "); //#B
9. greeting.append(name); //#C
10. System.out.println(greeting);
11. }
12. }
Now, let’s add a step to insert a value into our greeting. To keep things simple, we can add
“and welcome” to the message, so it will say “Hello, and welcome”. See the revised code
listing 9.4:
Listing 9.3 This program prints a greeting using the user name and time of day
1. import java.util.Scanner;
2. public class Greeting {
3. public static void main(String[] args) {
4. Scanner in = new Scanner(System.in);
5. StringBuilder greeting = new StringBuilder();
6. System.out.println("Enter your name: ");
7. String name = in.nextLine();
8. greeting.append("Hello, ");
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
113
9. greeting.append(name);
10. greeting.insert(6, "and Welcome,"); //#A
11. System.out.println(greeting);
12. }
13. }
#A Insert the words “and Welcome, “ into the StringBuilder object greeting
The StringBuilder class also offers several other methods that can be used to retrieve a single
character using .charAt(index), or delete a character or sequence of characters. It can even
find the first occurrence of a character and return the index value of the character. Check out
the JavaDoc for more information about this important class.
(https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html)
StringBuilder quote = “It is often easier to ask for forgiveness than to ask
for permission”;
a. substring(int x)
b. equalsIgnoreCase(Object obj)
c. toString()
9.5 Summary
In this lesson, you learned:
This lesson reviewed the use of the String and StringBuilder classes in Java. When
programming in general it is often necessary to read and manipulate text either from the user
or from a file. Remember, a string can be converted to a StringBuilder using a constructor
and a string builder object can be converted to a string using the toString() method.
In the next lesson, I will introduce the topic of the static classes and methods.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
114
TRY THIS: Write code that reads in a list of first names separated by commas and store them in a String
array. Then use the StringBuilder class to print a greeting for each name, such as “Hello, Peggy. How are you
today?”. Start by creating a new StringBuilder object that contains “Hello, . How are you today?”, then insert
the name and print the result. (remember to delete the name from the StringBuilder object each time, so the
previous name does not get included in the output). Here is some sample output from the program:
Figure 9.5 This is sample output from the Try this activity.
a. 19
b. 18
c. 17
d. 20
a. input.split(";")
b. input.parseString(";")
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
115
StringBuilder quote = “It is often easier to ask for forgiveness than to ask
for permission”;
a. substring(int x)
b. equalsIgnoreCase(Object obj)
c. toString()
Listing 9.4 This code asks for a list of names, then uses a StringBuilder to prints
personalized greetings
1. import java.util.Scanner;
2. public class Greeting {
3. public static void main(String[] args) {
4. Scanner in = new Scanner(System.in);
5. StringBuilder greeting = new StringBuilder();
6. System.out.println("Enter a series of names separated by commas:");
7. String names = in.nextLine();
8. String[] name = names.split(", "); //#A
9. greeting.append("Hello, . How are you today?"); //#B
10. for(int i = 0;i<name.length;i++) {
11. greeting.insert(7, name[i]); //#C
12. System.out.println(greeting); //#C
13. greeting.delete(7,(7+name[i].length())); //#D
14. }
15. }
16. }
#A Use the split method to create separate strings for each name using the comma as a delimeter
#B Add the greeting to the StringBuilder object using the append method
#C Insert the name to personalize the greeting in the StringBuilder object, print the message
#D Remove the inserted name to prepare for the next name
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
116
10
Static Methods and Variables
This lesson introduces the topic of the static keyword in Java. In Java, using the keyword
static indicates that the method is a class method or the variable is a class variable as
opposed to an instance method or instance variable. Every Java application uses the static
keyword at least once for the main method:
public static void main(String[] args) {…}
In this lesson I will review the impact of using the static keyword for both methods and
variables. In addition, since the keyword final is often used when creating static variables, this
lesson reviews the impact of defining static final variables.
Consider This
Recently a friend of yours decided to start selling t-shirts online with custom graphics. You are working with them to
create a Java application to keep track of the inventory. For this example, let’s concentrate on the inventory of shirts
only (I’m sure there are other supplies needed for the business such as ink, screenprints, etc.). The project starts by
creating a TShirt class with instance data about the size of the shirt, color, graphic, and price.
When we create TShirt objects, they each have distinct copies of the instance variables that are not shared from one
object to the other. It might be helpful to have some variables shared with all the TShirt objects. For example, maybe
your friend wants to include an item number for each shirt, starting at 100 and then incrementing the value each time
a new shirt is created. We need to add the item number field to our instance data, but we also need to keep track of the
next available item number for the next shirt.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
117
The next item number variable is not associated with a specific shirt, but it is used to get the next number and then it is
increased by one each time. So, we need to add a variable to our instance data for the item number and a second
static variable, next item number, to the class which starts at 100. This variable must be declared as static so the
compiler knows there is only one copy of this value.
This statement returns the value 76 and places that value in the variable biggest. Since I
don’t need an object, I must use the class name with the dot and the method name. The
method does not act upon a specific object.
As I stated in the lesson introduction, every Java application has at least one static method,
the main method. The main method is declared as static since there can only be one instance
of the main method for each application. The Java virtual machine looks for the specific
method signature: public static void main(String[] args) to find the starting point of
any application. Java applications can have one or many separate files that work together to
form the application. But there can only be one main method, so by declaring it static, it
ensures there is only one. If you try to execute code that does not include a static main
method, you get an error message: “Error: Could not find or load main class …”.
There are rules about whether a static method can call another static method, or can a static
method call an instance method. Table 10.1 shows the rules for static methods and variables:
instance can access instance variables can access instance methods directly
method
instance can access class (static) can access class (static) methods directly
method variables
Class methods can access class (static) can access class (static) methods directly
variables
Class methods cannot access instance cannot access instance methods directly, they must use an object
variables reference
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
118
NOTE: class methods cannot use the this keyword as there is no instance for this to refer to.
Listing 10.1 is a code snippet that shows an example of a class that contains three methods
and six variables. Two of the methods are static and the third method is an instance method
(any method without the keyword static is considered an instance method). The static
methods are: assignNextNumber and main. The print method is an instance method since it
does not include the keyword static.
#A Static variable nextItemNumber is used to keep track of the next item number
#B This is a static method used to assign the next item number, then increase it by one
#C This is an instance method that prints out the shirt item number
#D Create a new tshirt object
#E Provide values for the instance data
#F Use the static method to get the next available item number
#G Print the tshirt item number
In this example, line 13 causes a compile time error, this occurs because we cannot call a
non-static method from a static method. In this case, I’m trying to call the non-static method
print from the static main method. To fix this error, it is possible to use the TShirt object
created on line 9 to call the instance method and print the item number for this t-shirt:
tee1.print();
Since print is an instance method, we must access it through an object that is created using
the class TShirt.
Figure 10.1 shows the variables and methods that are static on the left. The right is a list of
instance variables and methods. There can only be one variable for nextItemNumber and one
main method. All TShirt objects are given copies of the instance data and the price is
assigned to 14.99 by default. This can be changed once an object is created. But if most of
the t-shirts cost 14.99, this saves time by automatically assigning this value.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
119
Figure 10.1 This diagram depicts the access of the static and instance methods in the class TShirt
To decide if a method should be static, consider the question, does the program need to call
this method independent of any objects? If the answer is yes, then it should be static. If the
method only makes sense when attached to an object, then it should be an instance method.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
120
a. veh.numberOfVehicles = veh.numberOfVehicles + 1;
b. numberOfVehicles += 1;
c. veh.numberOfVehicles += 1;
2. Which statement correctly obtains the vin number for vehicle veh?
a. veh.getVin();
b. getVin();
c. veh.getVin(String make);
a. veh.print();
b. print(String vin);
c. print();
Static variables are useful when the information is the same for all instances of a class. For
example, if we had an Employee class and all employees worked for Linkedin, we could create
a static variable for the company name in the Employee class that allocates space for that
variable once, even if we have 1,000 employees. A static variable is shared across all
instances of a class. Here is an example:
class Employee {
String name;
static String company = "Linkedin";
//other demographic information
}
Let’s revisit the TShirt class from the prior section to review the static variable
nextItemNumber.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
121
#A Static variable nextItemNumber is used to keep track of the next item number
#B This is a static method used to assign the next item number, then increase it by one
#C Print the tshirt item number using the dot notation since print is an instance method
Static variables are often used to either keep a running total of all objects or to provide values
that are not dependent on a specific object. In our TShirt class, a variable is defined to hold
the next item number. Each object has a unique item number. On line 2, I have declared a
static variable called nextItemNumber and assigned it a starting value of 100. Since this
variable is considered static, there is only one copy of this variable that is shared by all the
TShirt objects. This number gets updated every time the static method assignNextNumber()
is called. Notice that this method first returns the current number so that the calling TShirt
object is assigned the next number, then the ++ is executed and one is added to the number
so it is ready for the next TShirt.
NOTE: The ++ operator adds one to the variable. It can be located before the variable, in which case it adds
one before completing the statement. If it is located after the variable, it adds one after the statement has
executed. In this case, the variable is updated after it is returned to the calling program so that it has the next
number is stored and ready for the next TShirt object.
If you have ever opened a bank account, you know the bank assigns each customer a unique
bank account number. In order to identify the next available account number, the bank needs
a static variable in addition to the account number associated with the bank account object. If
I open an account today, I might get a bank account number of 1234. The next customer
should get account number 1235, and so on. Each customer has a unique number, but the
bank account class must also have a static variable with the most recently assigned account
number that is updated every time a new account is opened.
Listing 10.2 contains another example, an Astronaut class that includes static and instance
variables.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
122
The variable for the company name is defined as static since all the astronauts in our example
work for NASA (Although Howard Wolowitz is actually a character from the Big Bang Theory).
The class also includes a static variable that is used to get the next ID number, which must be
unique for each astronaut. In the main method, line 14 prints out the company name using
the variable from the Astronaut class. Remember, a static variable is accessible to all
methods in the same class without first creating an object. Notice the instance data fields
referenced in the main method use the dot notation to access the data that is not defined as
static.
Notice that this class assigns the next ID number to each astronaut and then increases the
value by 1.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
123
variable is used for constant values, for example, the definition of double final PI =
3.14159; This definition can be used for any constants that need to be defined in our code.
When using the keywords static final with a primitive data field, the value cannot be
changed. But, it is different is the variable represents an object such as an ArrayList. Listing
10.3 shows an example of defining an ArrayList as static final and then adding values to
the ArrayList, even though it is defined as final. Here is the output that is produced from
executing the code in Listing 10.3:
Listing 10.4 Code used to create an empty static final ArrayList, the call addPlanets
method to update
1. import java.util.ArrayList;
2. public class Planets {
3. private static final ArrayList<String> planets = new ArrayList<String>();
//#A
4. public static void addPlanets() {
5. planets.add("Earth"); //#B
6. planets.add("Mars"); //#B
7. planets.add("Uranus"); //#B
8. planets.add("Venus"); //#B
9. planets.add("Mercury"); //#B
10. planets.add("Jupiter"); //#B
11. planets.add("Saturn"); //#B
12. planets.add("Neptune"); //#B
13. }
14. public static void main(String[] args) {
15. addPlanets(); //#C
16. System.out.println(planets); //#D
17. ArrayList dwarfPlanets = new ArrayList<String>();
18. dwarfPlanets.add("Pluto");
19. planets = dwarfPlanets;
20. }
21. }
In this example, the program can add the values to the planets ArrayList even though it has
the keywords static final. That values can be added because that action does not attempt to
update the reference value of the original planets ArrayList. In line 19, the code is trying to
assign the planets ArrayList to the new ArrayList of dwarf planets, but this attempts to change
the reference value and the compiler produces an error “cannot assign a value to final
variable planets”.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
124
A static variable that includes the attribute final, must be initialized before use. This is
different from other static variables which are automatically assigned default values. Table
10.2 shows the values that are automatically assigned to a static variable if it not otherwise
initialized.
Table 10.2 shows the values assigned to each type of static variable.
boolean false
objects Null
10.4 Summary
In this lesson, you learned:
This lesson reviewed the difference between static and instance methods, and static and
instance variables. This lesson also addressed what happens when we add the keyword final
to a static variable. In the next lesson, I will introduce the topic of interfaces in Java.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
125
Try this:
Create a Planet class that has the following:
Create a method that converts the distance from earth from miles to kilometers (to keep it
simple, use this conversion: 1 M = 1.6 KM)
In the main method, create a new planet object, update the name, distance from earth and
the description.
a. getter methods
b. setter methods
c. accelerate method
d. calculate fuel efficiency method
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
126
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
127
11
Using Interfaces
This lesson introduces the topic of interfaces in Java. An interface is considered a reference
type in Java and serves several purposes. It acts as a rule or contract for any code that
implements the interface. All functionality identified in the interface must be implemented.
The interface contains a collection of abstract methods, constants, default methods, and static
methods. Interfaces are used for dependency injection, unit testing and play a key role in
design patterns.
Consider This
Nowadays almost all vehicles contain a navigation system. And, I’m sure you have heard about the latest technology
for self-driving cars. It is obvious that the navigation system and the car audio system must communicate with each
other.
If we break this process down into the system used by the car manufacturer, which includes the software to provide
steering, braking, etc. and another company that provides navigational support, these two companies need some
common communication to work together. But the car manufacturer does not need to know the details of the
programming behind the task of identifying the best route to the airport and the navigation company does not need to
know how the car steers or brakes. They just need to know how to interface with each other, so the car can turn when
the navigation says to turn.
So, the programmers devise an interface that acts as a contract between the two software applications. The
interface must detail what methods can be can be invoked to make the car travel. Then the navigation company can
write their code to invoke the methods described in the interface to auto drive the car.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
128
Let’s start with an example, if we created a video game and we wanted to allow the game to
be played on multiple gaming systems, we could create an interface that identifies the specific
methods required for the controller to play the game. The gaming systems might include
Sony PlayStation, Microsoft Xbox, Nintendo Switch, or even the PC. Each of these
manufacturers has a specific type of controller interface that needs to perform the actions
identified in the interface, but they each use different buttons, keys, toggles, and so on.
Diagram 11.1 shows how the ControllerInterface is implemented by each type of controller.
Figure 11.1 shows how each type of controller implements the ControllerInterface
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
129
6. }
#A Define an interface
#B Define abstract methods, notice the methods are only signatures, no body is defined here
Listing 11.1 shows the code for the ControllerInterface. Notice that the methods only contain
the signature, they do not have any code in the body, and they end with a semicolon.
In this example, the controller classes must define how the controller hardware is used. For
example, most PC games use the keys W, A, S, and D to control the movement of the
characters. But if the user is using an Xbox Controller, then they use the analog stick on the
controller. So, the controller classes must implemente the logic for each action defined by the
interface.
An interface contains only constants, abstract method signatures, default methods, and static
methods. Default and static methods contain a method body, but the abstract method
signature is just a placeholder for a method that must be defined by the program that is
implementing the interface. Java does not require the keywords public abstract for the
methods, it assigns these values by default. For clarity in this text, I will include both public
and abstract, but remember they are optional. It is also important to note that interfaces
cannot be instantiated, which means you cannot create an object with the keyword new.
The default method was added with Java 8 to allow programmers to update an interface while
still maintaining backwards compatibility with programs that already implement the older
version of the interface. The default method must have an implementation defined in the
interface.
A benefit of using an interface is that you can implement more than one interface. Another
method for declaring classes that share methods is inheritance. Java uses inheritance to allow
one class to inherit the behaviors of another class. Here is a typical example used to describe
this process. If we start with a class representing all animals, this is a very broad category.
We don’t usually see a rabbit and say “There goes an animal across the grass!”. Instead we
say, “There goes a rabbit (or bunny) across the grass!”. Other examples include dogs, cats,
racoons, and so on. The definition of rabbit, dog, cat or racoon are subclasses of the Animal
class because they share some of the same behaviors and characteristics. So, we create the
subclasses for rabbit, dog, etc by extending the animal class. This is referred to as
inheritance, the rabbit class inherits from the animal class. A downfall to inheritance is that
only one class can be inherited by another class. On the other hand, a class can implement
one or many interfaces.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
130
#A Define an interface
#B Define abstract methods, notice the methods are only signatures, no body is defined here
Remember, each method included in the interface is considered public and abstract by default.
Notice that the methods only contain the signature, they do not have any code in the body,
and they end with a semicolon. Now, any program that implements our vehicle interface must
provide valid definitions for each abstract method. The class that implements the interface
must maintain the same return type and parameters (including data type and the number of
parameters) as the method signature from the interface.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
131
Figure 11.2 Screen print of sample output from executing the code in listing 11.2.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
132
NOTE: Since an interface is considered a reference type, we can assign a variable to the interface, but we
must instantiate it with a concrete (not abstract) class.
In addition to implementing interfaces that we define, there are interfaces in the Java API that
are very useful to know and understand. When working with objects, it can be extremely
helpful to implement the comparable interface. The comparable interface has an abstract
method, compareTo(Object obj) which returns an int value. The return value is either a
negative number, zero, or a positive number as defined here:
If the object in the parameter list is greater than the calling object
else if the object in the parameter list is equal to the calling object
return zero
it would return a negative value since apples comes before oranges alphabetically.
The interface can be used to compare Strings, wrapper class objects and user-defined class
objects. This is great when you have a class and you want to include the ability to compare
two objects from this class.
When using the comparable interface, the compareTo(Object obj) must be defined since it is
an abstract method in the interface. To make this method more generic, the compiler
understands the keyword Object as a datatype. Depending on what part of the object is being
compare, it might be necessary to cast the object as a concrete class object. For example, if
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
133
we want to compare two vehicle objects, the compareTo method defined in the Vehicle class
can cast the Object obj as a Vehicle object before starting the comparison:
Vehicle v = (Vehicle) obj;
In this example, the object in the parameter list is now a Vehicle object and can be used to
compare to another Vehicle object. Code listing 11.3 shows how to use the Comparable
interface for the Vehicle class. Note that the code is implementing two interfaces separated by
commas. Multiple interfaces can be implemented, but don’t forget to define all abstract
methods for each interface.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
134
More interfaces can be found in the Java API, the Comparable interface is often for sorting
objects.
11.4 Summary
In this lesson, you learned:
This lesson reviewed how to create and implement interfaces in Java. An interface is a
reference type that provides a contract with the program that is implementing it. All abstract
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
135
methods from the interface must be defined. Multiple interfaces can be implemented by
separating them with commas. In the next lesson, we will work on a cumulative project that
includes all of the lessons so far. This is considered a capstone lesson.
Try this:
Use the ControllerInterface from section 11.1 and create the following:
A class that implements the ControllerInterface for each type of controller in figure 11.1
Create a main method that uses the interface as the data type and then instantiate a new
object using one of the controller classes
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
136
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
137
1. package videogames;
2.
3. public class PCController implements ControllerInterface {
4. public void onOff() { System.out.println("PC Keyboard turn on/off");}
5. public void move() { System.out.println("Move");}
6. public void jump() { System.out.println("Jump"); }
7. public void setNumberPlayers(int numPlayers) {this.numPlayers =
numPlayers;}
8. private int numPlayers = 0;
9. }
1. package videogames;
2.
3. public class XBoxController implements ControllerInterface{
4. public void onOff() { System.out.println("XBox turn on/off");}
5. public void move() { System.out.println("Move");}
6. public void jump() { System.out.println("Jump"); }
7. public void setNumberPlayers(int numPlayers) {this.numPlayers =
numPlayers;}
8. private int numPlayers = 0;
9. }
1. package videogames;
2.
3. public class NintendoController implements ControllerInterface{
4. public void onOff() { System.out.println("Nintendo turn on/off");}
5. public void move() { System.out.println("Move");}
6. public void jump() { System.out.println("Jump"); }
7. public void setNumberPlayers(int numPlayers) {this.numPlayers =
numPlayers;}
8. private int numPlayers = 0;
9. }
1. package videogames;
2.
3. public class PlayStationController implements ControllerInterface{
4. public void onOff() { System.out.println("PlayStation turn on/off");}
5. public void move() { System.out.println("Move");}
6. public void jump() { System.out.println("Jump"); }
7. public void setNumberPlayers(int numPlayers) {this.numPlayers =
numPlayers;}
8. private int numPlayers = 0;
9. }
#A This is the package name that groups all the files together in one application
#B Declare an object for each type of controller
#C Invoke the on/off method to print a message for each controller
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
138
12
Capstone
In lessons 8 - 11, I discussed how to access and use the Standard Java API, the difference
between the String and StringBuilder class, static methods and variables, and finally the
definition and uses of interfaces in Java.
This lesson is a capstone of these topics providing you with the opportunity to reinforce the
skills learned. In this lesson, I will introduce a problem that is designed to include everything
presented so far in the book.
This assignment involves creating an application for a book publishing company, ACME
Publishing. ACME publishing offers both hardcopy and e-books. Here are the requirements for
this assignment:
As I’ve stated before, everyone programs differently. So, the order in which you create the
classes for this application might vary from my approach. I have decided to start by creating
an Author class, then a Book class. Finally, I’ll add an ACMEPublishing class which contains
the main method. For this project, there is no need for an interface.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
139
The user must be prompted to enter the author information on one line separated by commas.
For example: Peggy,Fisher,123 Main Street,[email protected],717-555-1212.
The Author class must also assign a unique Author ID to each author. To make sure we only
have one place where the next author id is stored, the Author class must create a static int
variable, ie: static int nextAuthorID = 001; which is increased by 1 after it is assigned to
an author. In addition, since every book must be associated with a unique author, we need a
get method to retrieve the author id so that it can be used when creating a book object
(covered in section 12.3). It is a good idea to supply get and set methods for all instance data,
but to save space, I have only added the get method for the authorID field.
The last method that is included in the Author class is a toString method that is used to
format the author information. By default, all classes have access to a toString method, it is
included in the Object class. But the default toString method simply prints the reference
value of the object. Instead, it is often helpful to add a specific method that is used in place of
the default method. The use of the @Override keyword allows the class to provide a
substitute implementation of the toString method. Figure 12.1 shows sample output of how
the Author class is formatting the author information.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
140
#A All classes have the same package name, this allows each class to be in a separate file
#B Create a static variable for the next author id, this variable is shared with all author objects
#C Create instance variables for the author information
#D Create a method used to populate the instance data for a specific author, this special method is called a constructor
and more details are included in Unit 3
#E The getter method for authorID field
#F Override the toString method to format the author information when printed
NOTE: I feel it is important to note that this application does not include extensive error checking for any
fields that could have invalid data. We covered error checking for instance data fields in Lesson 4.2. Please
refer to that lesson to get an idea of how we added code to validate the values entered by the user to enforce
data integrity. Error checking should be added to all instance data fields as appropriate, for example, the
phone number field should be check for 10 digits (with or without hyphens and parentheses). Due to the
additional length of the code if all of the error checking was added, I decided to keep the programs simple. But
a production version of these programs must include error checking.
• Book title
• Book type (‘h’ – hard copy, ‘e’ – electronic copy, ‘b’ – both)
• Number of pages
The Book class also needs the authorID, but this value is supplied using the ID created when
the Author object was created. The user must be prompted to enter the book information on
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
141
one line separated by commas. For example: Get Programming with Java,b,325. This
represents the title “Get Programming with Java” which is published as hard copy and
electronic, and has 325 pages.
When the main method creates a new book object, it uses the data entered by the user to
pass values in the argument list that are used to populate the instance data. It also uses the
getAuthorID method from the Author class so it can link the author to this book. Similar to
the abbreviated list of getter and setter methods in the Author class, I’ve decided to omit the
list of getter and setter methods for the Book class to save room in the text. The only get
method is defined to get the author id to print all books associated with that author.
For the Book class, I have also provided an override method for the toString method. Figure
12.2 shows sample output of how the Book class is formatted with the book information.
Listing 12.2 shows a sample Book Class.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
142
#A All classes have the same package name, this allows each class to be in a separate file
#B Create instance variables for the book information
#C Sample error logic has been added to test for a correct book type of ‘h’, ‘e’, or ‘b’
#D Override the toString method to format the book information when printed
There is one major difference when working with the Strings for the book object. Since the
Book class includes an int variable for the number of pages, and a char variable for the book
type, these values must be converted from String to the appropriate data type. For the int
value, I am using the Integer wrapper class and the parseInt method. For the character, I
am using the charAt method for a String object to retrieve the character.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
143
It is always good to think about the types of data that the user might input. For each book
object, the user needs to enter the title, type, and number of pages. In order to correctly
convert the type and number of pages to their respective values, it is a good idea to strip out
any extra white space (which includes spaces). For my version of the main method, I am
using the replaceAll method from the String class: replaceAll(" ", "").
HINT: Remember, strings are immutable, so when you use the replaceAll, you must create a new string to
hold the new value.
Figure 12.3 shows the sample output from running the ACMEPublishing application and Listing
12.3 shows the sample code used to produce this output.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
144
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
145
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
146
55. }
56. }
57. System.out.println(printInfo);
58. }
59. }
#A Import the Scanner, and ArrayList classes from the Standard Java API
#B Start of the main method
#C Create the two ArrayList objects to hold the list of authors and books
#D Read in the entire line of data separated by commas
#E Store each separate data field in a string array using the comma as the delimiter
#F Add the object to the ArrayList
#G Remove spaces from the book type data fields
#H Convert the string for the number of pages to an integer after removing any spaces
#I Create a StringBuilder object to hold the output
#J After adding the author to the StringBuilder object, loop through all the books to find any books with the same
author id
12.4 Summary
This lesson provided an activity that included all the topics from lessons 8-11. In this lesson, I
reviewed the initial business problem of creating a book publishing application that asked the
user to enter the author information followed by one or more books they have written.
• Obtainin`g and parsing the author information for the book including:
o author id, author name, address, email address, and phone number
• Allowing the application to create book objects with the following information:
o author id, book title, book type, number of pages
• Printing out the author and the book information
In the next unit, I will continue to work with classes and objects by presenting a real-world
example, a banking application.
Try this:
Create a Student class that has the following:
• Include the following instance variables: studentName, GPA, collegeName (where the
college is always “Penn State University”)
• Implement the Comparable Interface
• Find the average GPA for all students
• Read information about each student from the console, read it as strings separated by
commas (first name, last name, and GPA)
• Assign each student a unique student ID
• In the main method, create student objects, store these objects in an ArrayList
• Print a roster of all students and student id
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
147
Figure 12.4 Sample output from executing the Student class program
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
148
21. }
22. public int compareTo(Object obj) { //#I
23. Student s = (Student)obj; //#I
24. if(this.GPA > s.GPA) //#I
25. return 1; //#I
26. else //#I
27. return -1; //#I
28. }//#I
29. @Override
30. public String toString() {
31. return fName + " " + lName + ", Student ID: " + ID + " GPA: "+ GPA +
32. ",University: " + collegeName +"\n";
33. }
34. public static void main(String[] args) {
35. boolean done = false;
36. String response = "y";
37. ArrayList<Student> roster = new ArrayList<Student>();
38. while(done == false) {
39. Student s = new Student();
40. s.readStudentInfo();
41. roster.add(s);
42. System.out.println("More students: (Y/N)");
43. response = in.next().toLowerCase();
44. in.nextLine();
45. if(response.equals("n"))
46. done = true;
47. }
48. StringBuilder output = new StringBuilder(); //#J
49. for (Student s_info : roster) {
50. output.append(s_info.toString()); //#J
51. }
52. System.out.println(output);
53. double highest = roster.get(0).GPA;
54. int highestIndex = 0;
55. double total = roster.get(0).GPA, average;
56. for(int i = 1; i < roster.size(); i++) {
57. total += roster.get(i).GPA;
58. if(roster.get(i).GPA > highest) {
59. highestIndex = i;
60. highest = roster.get(i).GPA;
61. }
62. }
63. average = total/roster.size();
64. System.out.println("The student with the highest GPA is: "
65. + roster.get(highestIndex).toString());
66. System.out.println("Average GPA is: "+average);
67. }
68. }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
149
#H Assign the student an ID number, then add one to the static student id field
#I Implement the compareTo method to compare the GPA of two students
#J Create a StringBuilder object to store all the output that needs to be printed
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
150
Unit 3
Programming with Objects
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
151
13
Overloading Methods
This lesson introduces the topic of overloading methods in Java. In Java, a class cannot have
two methods with the exact same method signature because the compiler would not be able
to distinguish between the two methods. The Java compiler checks for this at compile time
and generates an error message when this happens. But there are situations where the
programmer needs to perform a similar function that is just slightly different, for example,
maybe the number of values that are passed through as arguments to the method vary. To
keep the code readable, it is helpful to give these methods the same name but allow them to
have different method signatures.
Before discussing method overloading further, let’s review the nomenclature for a method
signature. A parameter is a variable in a method signature, it includes a data type and
variable. When a method is called, the arguments refer to the data you pass into
the method's parameters. Figure 13.1 shows a code snippet describing the arguments as the
variables passed to the method and the parameters are the variables that receive these values
and are made available to the statements inside the method.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
152
Figure 13.1 Code snippet identifying the arguments and parameters for a method call
Consider This
The postal service has certain elements that must be included when mailing a letter or postcard, but those elements
can differ if the mail is going to a PO Box, an apartment, a house address, a military address, or an international
address to name a few.
Many companies outsource their marketing efforts by providing mailing lists that another company uses to print
postcards or mail letters to their current and potential customers. The marketing company must have different
methods to print the addresses based on the values in the file. For example, the file might contain a first name, last
name, address line 1, address line 2, city, state, and zip code (with or without an extended zip code). If the file contains
all of these elements, then the method is expecting seven values from the calling program. But not every customer has
an address line 2, so a second method signature can have the same values except for a String variable for the second
address line.
Both methods need to print a mailing label, but the information in the argument list might be different.
Figure 13.2 Examples of the three ways to overload the same method
The example above shows the original method called printPage which does not have any
arguments and does not return any values. Each subsequent method is slightly different, v.1
shows the same method name but this time with two arguments: int pageNum and String
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
153
title. Next, v.2 changes the data type of the first variable from int to double, this is
enough to overload the method. Finally, v.3 reverses the arguments so that the String value
comes before the int value.
The compiler determines which method to call based on the values passed as arguments to
the method. Figure 13.3 shows an example of a statement that invokes each of the methods
from figure 13.2.
Note
the names of the parameter variables are not used to determine if a method is overloaded, only the data type of the
parameter, the number of parameters, and the order of the parameters are important when overloading a method. The
variable names can be the same or different.
It is also important to note that changing the return type is not considered overloading a method. So, if I changed
the method signature to: public String printPage(){…}, this would cause a compile time error since the
compiler would not be able to differentiate the methods.
In other words, if the method signature is exactly the same, but the return type is different, this will cause a compile
time error. It is not considered an overloaded method if ONLY the return type is different. The problem is that the
compiler would not know which method to invoke since it only checks for the signature and it does not know what type
of value is returned inside the method.
Figure 13.4 is an example where the compiler produces an error message for the second
method signature since the only change is the return type. The error message is:
method printPage() is already defined in class Lesson13_Example.
Figure 13.4 is an example of an error message generated when incorrectly overloading the printPage method
In the next section I will show some examples of overloaded methods and the code that calls
these methods. Remember, when writing an overloaded method, the compiler checks to
make sure the method signature is not already defined. The compiler also checks to make
sure that there is a method that matches the arguments in the statement calling the method
to the parameters in the method signature, similar to the example in figure 13.3.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
154
2. Given the method signature, public double getAverage(int num1, int num2, int num3), which
method signature(s) correctly overload this method:
1. First and last name, address line, city, state, zip code
Peggy Fisher
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
155
Ambler, PA 19001
2. Only address line, city, state, zip code (instead of name, use: Current Resident)
Current Resident
Carpinteria, CA 23901
Tish Macclay
PO Box 756
Scituate, MA 02566
Listing 13.1 shows the start of our class along with the three methods required for the
scenarios listed above.
Note:
When creating the print methods for the Address class, I have chosen to use the data type String for the zip
code. Although a five-digit zip code is all numeric, if the data type was an int, the print statement would require
extra formatting to print out any leading zeroes. And, many post offices are now requiring the extended zip code which
is in a format: 99999-9999, so using a String data type makes it easy to adjust if any address records have the
extended zip code.
Listing 13.1 Code for overloading three print methods to print an address
1 public class Address {
2 public void print(String fName, String lName, String //#A
3 address1, String city, String state, String zip) {
4 //code to print address omitted
5 }
6 public void print(String address1, String address2, String city, String
state,
7 String zip) { //#B
8 //code to print address omitted
9 }
10 public void print(String fName, String lName, int POBox,
11 String city, String state, String zip) {
12 //code to print address omitted
13 }
14 }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
156
It is important to look closely at the examples above. Notice that the first and third methods
have the exact same return type, method name and number of arguments. The difference is
the data types of the argument list. The third method has an integer value for the PO Box and
one less String value (it does not need address line 1 since it is using a PO Box). That is
enough to correctly overload the first method so there are no compile errors in this code.
Remember, a method can be overloaded by:
In the next section, I will show you examples of using each of the three methods to generate
a mailing list.
class Student {
public void printStudent(int studentNum, String fname, String
lname, double GPA) {
//code to print student info goes here
}
public void printStudent(int studentNum, String name, String
studentMajor, double GPA) {
//code to print student info goes here
}
}
2. Using the code from the first problem, which statement correctly provides the start of an overloaded
method:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
157
Let’s use the Address class in Listing 13.1 as a starting point for examples on calling the
overloaded methods. There are three versions of the print method, each overloaded by
changing the parameter list. In the main method, I will create an Address object and then use
the print method to print three different types of addresses. Figure 13.5 shows sample output
from executing the code in Listing 13.3.
Listing 13.1 Code for overloading three print methods to print an address
1 public class Address {
2 public void print(String fName, String lName, String //#A
3 address1, String city, String state, String zip) {
4 //code to print address omitted
5 }
6 public void print(String address1, String address2, String city, String
state,
7 String zip) { //#B
8 //code to print address omitted
9 }
10 public void print(String fName, String lName, int POBox,
11 String city, String state, String zip) {
12 //code to print address omitted
13 }
14 }
Figure 13.5 Sample output printing three addresses using overloaded methods
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
158
Listing 13.2 Complete program to print three addresses using overloaded methods
1 public class Address {
2 public void print( String fName, String lName, String
3 address1, String city, String state, String zip) {
4 System.out.println(fName + " "+lName+"\n"+address1 +
5 "\n"+city+", "+state+" "+zip+"\n");
6 }
7 public void print(String address1, String city, String state, String zip)
{
8 System.out.println("Current Resident\n"+address1 +
9 "\n"+city+", "+state+" "+zip+"\n");
10 }
11 public void print(String fName, String lName, int POBox, String city,
12 String state, String zip) {
13 System.out.println(fName + " "+lName+"\nPO Box "+POBox +
14 "\n"+city+", "+state+" "+zip+"\n");
15 }
16 public static void main(String[] args){
17 Address address1 = new Address(); //#A
18 address1.print("123 First Street", "Carpinteria", "CA", "23901"); //#B
19 address1.print("Peggy" ,"Fisher", "123 Main Street", "Ambler",
//#C
20 "PA", "19001");
21 address1.print("Tish","Macclay", 756, "Scituate", "MA", "02566"); //#D
22 }
23 }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
159
todo.print("Peggy Fisher");
a. 5, 10, 14
b. 10, 14
c. 5
d. 10
3. What is wrong with adding this statement: todo.print("Mow the lawn", "Peggy", 5, true);
Here is an example, if we have a class called Computer, we might want to create a computer
object for a laptop and another object for a desktop computer. The laptop object might only
have the brand name, but the desktop computer might include the brand name and
information about the monitor, keyboard and mouse. Listing 13.4 shows the code for a
Computer class with two overloaded constructors, one for a laptop and one for a desktop
computer.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
160
Now let’s take a look at how we can use a class that has overloaded constructors. For this
example, I will refer to the Computer class from listing 13.4. The same process applies to
overloaded constructors, the calling method decides which constructor to call based on the
argument list. In my example, there are two overloaded constructors, one for creating a
laptop object and one for creating a desktop object. We can add a third constructor that does
not include any arguments, this constructor is called when creating an object that does not
include any initial arguments to be passed to the constructor. The no-parameter constructor
can be used to create an object based on common values for the instance data. For this
example, most of our customers order surface laptops made by Microsoft. So, the no
parameter constructor creates an object with the brand value set to Microsoft. Figure 13.6
shows a screenshot of sample output for executing the code in listing 13.5.
Listing 13.5 shows the code with the additional overloaded constructor and a main method
that creates three computer instances.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
161
7 this.brand = brand;
8 }
9 public Computer(String brand, String monitor, String keyboard, //#C
10 String mouse){
11 this.brand = brand;
12 this.monitor = monitor;
13 this.keyboard = keyboard;
14 this.mouse = mouse;
15 }
16 public static void main(String[] args) {
17 Computer laptop1 = new Computer(); //#D
18 System.out.println(laptop1.brand);
19 Computer laptop2 = new Computer("Macbook Pro"); //#E
20 System.out.println(laptop2.brand);
21 Computer desktop = new Computer("Dell XPS", "Samsung Monitor", //#F
22 "Logitech Keyboard", "Ergonomic Mouse");
23 System.out.println(desktop.brand + ", " + desktop.monitor + ", " +
24 desktop.keyboard + ", "+desktop.mouse);
25 }
26 }
#A Overload the default construct with one that sets the default brand to “Microsoft Surface”
#B Overloaded constructor used to create an instance of the Computer class for a laptop
#C Overloaded constructor used to create an instance of the Computer class for a desktop computer
#B Call the overloaded default method
#C Call the overloaded method for a laptop which only takes one String value
#D Call the overloaded method that takes four String arguments
Listing 13.6 Updated Code for a ToDoList application that includes multiple constructors
1 public class ToDoList {
2 String task;
3 int priority;
4 boolean repeat;
5 public ToDoList() {
6 task = "Empty Dishwasher";
7 priority = 1;
8 repeat = true;
9 }
10
11 public ToDoList(String task, int priority, boolean repeat){
12 this.task = task;
13 this.priority = priority;
14 this.repeat = repeat;
15 }
16 public void print(String name){
17 System.out.println(task + ", priority: "+ priority+
18 ", repeat: "+repeat + "\nAssigned to: "+name);
19 }
20 public void print(){
21 System.out.println(task + ", priority: "+ priority+
22 ", repeat: "+repeat);
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
162
23 }
24 public static void main(String[] args){
25 ToDoList todo = new ToDoList("Homework", 1, true);
26 todo.print();
27 todo.print("Bob Fisher");
28 }
29 }
13.6 Summary
In this lesson, you learned:
This lesson reviewed how to write overloaded methods in Java. An overloaded method is
useful when your class requires a method that can have different arguments in the parameter
list. For code readability, it is helpful to use the same method name, but the parameter lists
must be different. For example, a method used to calculate the average of three numbers
might have one version that accepts all integer values and a second version that has all
double values as arguments. In the next lesson, I introduce another topic related to methods,
overriding methods.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
163
Try this:
When shopping for televisions, you have many options. Some TVs are considered Smart TVs since they come with
Internet access and sometimes they even have apps preloaded. Create a class called Television that has at least two
constructors, a no parameter constructor for TVs without Internet and a second overloaded constructor for TVs with
Internet features. The smart TV constructor should include two additional boolean variables: hasEthernet and hasWiFi.
Some smart TVs have both Ethernet and WiFi. Test your class by creating both types of TV objects. Figure 13.7
provides an example of the output for this class.
2. Given the method signature, public double getAverage(int num1, int num2, int num3), which
method signature(s) correctly overload this method:
class Student {
public void printStudent(int studentNum, String fname, String
lname, double GPA) {
//code to print student info goes here
}
public void printStudent(int studentNum, String name, String
studentMajor, double GPA) {
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
164
2. Using the code from the first problem, which statement correctly provides the start of an overloaded
method:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
165
todo.print("Peggy Fisher");
a. 5, 10, 14
b. 10, 14
c. 5
d. 10
3. What is wrong with adding this statement: todo.print("Mow the lawn", "Peggy", 5, true);
Listing 13.6 Updated Code for a ToDoList application that includes multiple constructors
1 public class ToDoList {
2 String task;
3 int priority;
4 boolean repeat;
5 public ToDoList() {
6 task = "Empty Dishwasher";
7 priority = 1;
8 repeat = true;
9 }
10
11 public ToDoList(String task, int priority, boolean repeat){
12 this.task = task;
13 this.priority = priority;
14 this.repeat = repeat;
15 }
16 public void print(String name){
17 System.out.println(task + ", priority: "+ priority+
18 ", repeat: "+repeat + "\nAssigned to: "+name);
19 }
20 public void print(){
21 System.out.println(task + ", priority: "+ priority+
22 ", repeat: "+repeat);
23 }
24 public static void main(String[] args){
25 ToDoList todo = new ToDoList("Homework", 1, true);
26 todo.print();
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
166
27 todo.print("Bob Fisher");
28 }
29 }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
167
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
168
14
Overriding Methods
This lesson introduces the topic of overriding methods in Java. In Java, a class can extend
another class (referred to as the parent class) if we want the classes to share some or all of
the data and methods in the parent class. This is called inheritance. Figure 14.1 is a diagram
showing inheritance where class B is the parent class to class A. The extended class is
considered a subclass or a child class of the parent class.
A method in a child class overrides a similar method in the parent class when it has the exact
same method signature. This allows the implementation of the child method to be different
than the parent method.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
169
Remember, the method signature includes the return type, the method name, and a
parameter list.
Consider This
You are working around the house and you need a tool. That tool is going to be very different if you are gardening or
working on a carpentry project. For example, when gardening, you might be mowing the lawn with a lawn mower. That
lawn mower can be operated using gasoline or it can be an old-fashioned reel mower.
But if you are working on a building a deck, the tools might be a circular saw or even something as simple as a
hammer and nails.
In this example, tools can be objects that require electric, gas, or operate manually. In other words, power tools vs.
manual tools. The term tool represents a wide variety of items. When thinking in terms of Java and modelling these
items, tool can be considered the parent or super class. Then each tool can be represented by a subclass of tool. A
lawn mower is a tool. The term “is-a” is often used to evaluate the relationship between two objects. When this is
true, then we have an example of inheritance, a term used in object-oriented programming to represent this parent-
child relationship.
The parent tool class might have a method to start the tool, ie: public void start() {}. But we know
that the action of starting a gas powered lawn mower is quite different from a push reel mower. So, we might have two
subclasses representing PowerTools and ManualTools. Each of these subclasses would override the start
method accordingly.
Next, we can define additional classes that share these attributes, but behave slightly
different. The pages of a cookbook usually have pictures, a list of ingredients, instructions for
combining the ingredients, and instructions for cooking or baking the item. A textbook has
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
170
text, images or pictures, and possibly exercises. A novel is usually only text or text and
images.
A Novel, Cookbook, and Textbook can all be defined by extending the Book class. Each of
these additional classes are called subclasses of the Book class. This is often referred to as a
parent-child relationship. We can use our “is-a” test, a Novel is-a Book, a Cookbook is-a Book,
and a Textbook is-a Book. Figure 14.1 is a diagram of this relationship.
Figure 14.3 Book class and subclasses: Cookbook, Textbook, and Novel
Figure 14.4 Sample output demonstrating an overridden method from the Book class
Listing 14.1 Code for the Book class and the subclasses Cookbook, Textbook , and Novel
1 public class Book {
2 public String title, publisher;
3 public String[] authors;
4 public int numPages;
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
171
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
172
So, to avoid this from happening, we can override the toString() method when we create new classes.
Remember, all classes extend the Object class, but we can provide an overridden toString() method to make the
output more meaningful. For example, a possible toString() method for our Book class might print the title and
publisher, here is the sample output:
@Override
public String toString(){
return "Title: "+title+" \nPublisher: "+publisher;
}
More information on the Java Object class can be found in the Oracle Docs, simply search Java
Object Class.
https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html
2. Which line(s) of code could be added to print the author names in addition to the book title?
3. Assume this code is added to the printPage method in the Book class only:
What is the expected output from executing these two lines of code in the main method:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
173
4. The code below is intended to extend the Book class and override the printPage method. What is wrong
with this code:
a. Nothing, this code correctly extends the Book class and overrides the printPage method
b. The overridden method cannot have any arguments in the argument list
c. The class name, Autobiography, is too long
d. The println statement in the printPage method cannot include a variable
Remember, a class that is extended by other classes is considered the super class. So, in our
subclass, we can refer to the parent constructor using the keyword super. This keyword refers
to a method in the parent class and it is used so we don’t have to write the same method
twice, once in the parent class and again in the child class. In the Book example, each
subclass refers to the constructor in the Book class using the keyword super followed by a list
of argument values that are required for the Book constructor.
Figure 14-5 shows how the Cookbook class uses the Book constructor to initialize the values
for the book title, publisher, author(s), and the number of pages. Notice that the instance data
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
174
is only defined in the Book class and it is defined as public. This allows the subclasses to
access all of these data fields directly.
Figure 14-5 Diagram depicting the use of the super keyword to invoke a method in the parent class from a
subclass
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
175
Figure 14.6 shows the output from executing the code in Listing 14.3. In this example, it
shows how the cookbook object is a type of Book. But, book is not an instance of Cookbook
class.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
176
Figure 14.6 Sample output from executing the code in Listing 14.3
Listing 14.3 shows only the code to test the instance variables of the classes Book and
Cookbook where the Cookbook extends the Book class.
#A This conditional statement checks if the object cookbook is an instance of Book, which is true
#B This conditional statement checks the opposite to see if the book object is an instance of Cookbook, which is false
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
177
1. Using the code in Listing 14-3, what output is produced if these statements are added to the main
method:
2. Which line(s) of code could be added to test if the mower object is an instance of the Tool class?
3. Which line(s) of code could be added to test if the reelMower object is an instance of the Tool class?
14.5 Summary
In this lesson, you learned:
This lesson introduced how to write methods that override other methods in Java. An
overridden method is useful when your application requires a parent class with subclasses that
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
178
might behave differently from the parent. In addition to this scenario, this lesson also
reviewed using the keywords super and instanceof when working with parent-child classes. In
the next lesson, I will introduce another topic related to inheritance called polymorphism.
Polymorphism is closely related to what we learned here on overriding methods in subclasses.
Try this:
Create an application that models Plants. The Plant class has two subclasses, IndoorPlant and
OutdoorPlant. All plants need water and sunlight, but outdoor plants need to be covered if the outside
temperature is less than 32 degrees Fahrenheit. Figure 14.7 shows sample output from this application:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
179
2. Which line(s) of code could be added to print the author names in addition to the book title?
3. Assume this code is added to the printPage method in the Book class only:
What is the expected output from executing these two lines of code in the main method:
4. The code below is intended to extend the Book class and override the printPage method. What is wrong
with this code:
a. Nothing, this code correctly extends the Book class and overrides the printPage method
b. The overridden method cannot have any arguments in the argument list
c. The class name, Autobiography, is too long
d. The println statement in the printPage method cannot include a variable
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
180
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
181
1. Using the code in Listing 14-3, what output is produced if these statements are added to the main
method:
2. Which line(s) of code could be added to test if the mower object is an instance of the Tool class?
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
182
3. Which line(s) of code could be added to test if the reelMower object is an instance of the Tool class?
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
183
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
184
15
Polymorphism Explained
This lesson introduces the topic of polymorphism in Java, the benefits of using polymorphism
and the difference between the two types of polymorphism: compile time and runtime
polymorphism.
The term polymorphism originated as a way to refer to a biology topic where a species can
have many different forms or stages. In programming, instead of referring to species, we refer
to classes and how objects defined by different classes can respond to the same method
differently. Here is a simple example, if you are in a room with a few other people and
someone says to everyone, “move”, what would happen? Some people might sit if they were
standing, people sitting might stand, some people might take a step forward. Different people
are told the same thing, but they behave differently.
Consider This
A track and field coach usually has a team of students who participate in many different types of track and field events.
If the coach had three team members, a runner, a javelin thrower, and a pole vaulter together and he shouted “Ready,
Set, Go”, each team member would start their event.
The runner would start to run, the javelin thrower would throw the javelin, and the pole vaulter would attempt to
vault over the bar.
These three students can be defined by a generic Person class. But each team member would also be a subclass:
Runner, JavelinThrower, PoleVaulter. The subclasses would each extend the Person class. Then the “Ready, Set, Go”
method would be overridden for each type of athlete.
This example shows how objects defined by different classes can behave differently when invoking the same
method call, in this case, the statement “Ready, Set, Go”.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
185
Gaming System
Make: Sony
Model: 3
Console: Playstation
Computer
Make: Dell
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
186
Model: XP
Type: Laptop
Size: 19 inches
Figure 15.1 screenshot of sample output using the overridden print method in each subclass
Notice that each type of electronic device has some variation of instance data. The television
has an indicator for whether it is wifi capable, the gaming system has the console type, and
the computer has an indicator for laptop vs. desktop. The superclass, Electronic, has a print
method, and each subclass overrides that method with a custom implementation. Then at
runtime the JVM invokes the appropriate print method based on the object reference type.
This is how polymorphism works. So, each object is told to ‘print’, but each object has a
different version of the print method.
a) Polymorphism allows different objects to behave differently when calling the same method name
b) Polymorphism uses overridden methods
c) Polymorphism is the same as inheritance
• A single reference variable can be used to reference objects of multiple data types
• Polymorphism allows a subclass to use the more general definitions provided by a
superclass and override methods to provide specialized method implementations
specific to the subclass
• Since runtime polymorphism requires subclasses that override the superclass methods
with alternative implementations, this enables code reuse of existing classes without
the need to recompile
• Polymorphism enables an object behavior to be determined at runtime
• Compile time polymorphism occurs when a class has method overloading, this is often
used for constructors which allows different ways to instantiate an object
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
187
#A this statement calls the overloaded method with three int parameters
#B this statement calls the overloaded method with three double parameters
#C this method finds the average of three int values
#D this method finds the average of three double values
These methods are considered overloaded since they have the same name but different
parameter lists. The compiler checks to make sure the method signature is not the same.
Since the list of parameters is different, the compiler can check any statement that calls the
findAverage method to determine if the argument list matches the first method parameter list
(double, double, double) or the second parameter list (int, int, int). As long as the method
call matches one of these two methods, it will not generate an error and the correct method
will be invoked. This is a type of polymorphism (where two methods with the same name
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
188
behave differently) that is checked at compile time. If the parameters were not different, then
this would cause a compile time error.
Now let’s talk about method overriding, which is checked at runtime. In general terms,
when an object is created using a superclass, it can have a reference to a subclass object
which has overridden a superclass method. So, the call to the overridden method is
determined at runtime since the compiler does not necessarily know whether the variable has
a reference type of the superclass or subclass. This process in which a call to the overridden
method is resolved at runtime is known as dynamic binding or runtime polymorphism.
Figure 15.1 is a diagram with a superclass called Electronic which has three subclasses.
According to this diagram, a Television is an Electronic, a Computer is an Electronic and a
GamingSystem is an Electronic. Each class has a print method. Since the name and
parameter list (which is empty) are the same, we know that each subclass is overriding the
superclass print method.
Figure 15.2 Hierarchy chart of an Electronic superclass and three subclass: Television, Computer,
GamingSystem
Based on this diagram, we can use the following statement to define an Electronic reference
variable that is refencing a Television object:
Electronic tv = new Television("Samsung", "Smart", "60 inches");
Now, if we want to print the television information, we use this statement: tv.print(); The
compiler checks to make sure that Television is a subclass of Electronic and if the subclass has
a print method. In this case, it does have a print method. At runtime, the JVM invokes the
print method from the Television class and not the method from the Electronic class. This
allows the same method name to perform a different action which is the definition of
polymorphism. This action is resolved at runtime and not compile time.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
189
15.4 Summary
In this lesson, you learned:
This lesson reviewed the programming definition of polymorphism in Java. This lesson also
introduced the benefits of using polymorphism. The last section reviewed the differences
between compile time and runtime polymorphism. The next lesson is still on polymorphism
where I will walk through a real-life example of how we can use polymorphism.
Try this:.
You have been hired as an intern at a local Bike shop. The shop owner wants you to work on
an inventory system. The shop sells the following types of bikes:
• Mountain Bike
• Road Bike
• Racing Bike
All three types of bikes have some common characteristics, such as make, model, color. But
then each bike type has some specific characteristics. For example, a racing bike has
information about the gear shift. A road bike might need more detailed information about the
frame material and weight. I am not an expert in biking, but for this example, each type of
bike is unique but also shares some overall characteristics of the other bikes.
Using this information and the following code for a Bike class, create a subclass that
overrides the print method for a MountainBike. Add a variable for the seatheight of the
mountain bike and include that in the print method. Then create a Bike reference variable
that is instantiated as a MountainBike and prints the additional information about the seat
height. Finally, using polymorphism, call the print method to print the information about the
MountainBike.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
190
a Polymorphism allows different objects to behave differently when calling the same method
b Polymorphism uses overridden methods
c Polymorphism is the same as inheritance
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
191
Listing 15.1 Bike Class with subclass Mountain Bike using an overridden print method
1 public class Lesson15_TryThisSolution {
2 public static void main(String[] args) {
3 Bike b = new MountainBike("Mountain Bike", "REI", "Diamondback", //#A
4 10, 20, 27.5);
5 b.print(); //#B
6 }
7 }
8 class Bike {
9 public String type, make, model;
10 public int gear;
11 public int speed;
12 public Bike(String type, String make, String model) {
13 this.type = type;
14 this.make = make;
15 this.model = model;
16 }
17 public Bike(String type, String make, String model, int gear, int speed) {
18 this.type = type;
19 this.make = make;
20 this.model = model;
21 this.gear = gear;
22 this.speed = speed;
23 }
24 public void print() {
25 System.out.println("Bike info: " + type + ", " + make + ", "
26 + model);
27 }
28 }
29 class MountainBike extends Bike {
30 public double seatHeight;
31 public MountainBike(String type, String make, String model, int gear,
32 int speed, double seatHeight) {
33 super(type, make, model, gear, speed);
34 this.seatHeight = seatHeight;
35 }
36 @Override //#C
37 public void print() {
38 System.out.println("Mountain Bike info: " + type + ", " + make + ", "
39 + model + ", seat height: " + seatHeight);
40 }
41 }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
192
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
193
16
Polymorphism In Action
This lesson shows examples of polymorphism in Java. As I stated previously, there are two
types of polymorphism. Method overloading (Lesson 13) is an example of static polymorphism
and it occurs at compile time. Method overriding (Lesson 14) is considered dynamic binding
and it occurs at run-time.
Consider This
Consider the geometric term, shape. For example, we can say that a circle is a shape, and a rectangle is a shape. But if
we want to find the area of these two shapes, the formula is quite different. The area of a circle is Π * radius squared.
The area of a rectangle is length * width.
So, in this example, we have a superclass called Shape, and several subclasses. For this example, let’s just use
Circle and Rectangle. A Circle is-a Shape, a Rectangle is-a Shape so they both pass the inheritance test. There might be
some characteristics of all shapes that are included in the Shape class. But we know that each subclass must have a
unique method for calculating the area.
If we have our superclass, Shape, and we create subclasses that extend Shape called Circle and Rectangle then we
can create objects that behave differently when the invoke the same method name, calculateArea. For example, we
can create a Shape object, then we can set the shape variable reference to a new Rectangle object. Here is the sample
code:
Shape s = new Rectangle();
The reference address of the Rectangle object is stored in the shape reference variable. This is valid since a Rectangle
is-a Shape. In Java, a reference variable is polymorphic because it can reference objects of a different type from its
own, as long as they are subclasses of its type. This is an example of polymorphism.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
194
Figure 16.1 Hierarchy diagram for the Sports Teams and Students on these teams
Now that we have our diagram of the classes and their relationships, the next step is to
identify the attributes and behaviors for each class. For this example, here are the
requirements for each class:
SportsTeam: FootballPlayer
• Type of sport • All the athlete information
• Team name • Position
• List of athletes on the team • Stats
Student: TennisPlayer
• First and last name • All the athlete information
• Grade • Singles/doubles
• Age • Stats
• GPA
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
195
Athlete: FieldHockeyPlayer
• All the student information • All the athlete information
• Size (S, M, L, XL, XXL) • Position
• Active or inactive • Stats
• Eligibility (based on GPA)
SoccerPlayer
• All the athlete information
• Position
• Stats
a. An Athlete is a Student
b. A TennisPlayer is a Student
c. A TennisPlayer is an Athlete
d. A Student is an Athlete
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
196
Figure 16.2 Abbreviated UML diagram for the sports team application
UML Explained
UML diagrams are used to help visualize a class. UML stands for Unified Modeling Language. It is often used to depict
a class and includes the class name in the top compartment, followed by a list of attributes in the middle compartment,
and a list of methods in the bottom compartment.
Next to each attribute and method, you might see a symbol indicating the visibility, such as:
+public
-private
#protected
Here is an example of a UML diagram:
Figure 16.3
The diagram in figure 16.2 shows each class and the methods defined in each class. It is
especially important to note that each class has its own version of a toString method. Since
the Athlete class extends the Student class, this is an example of overriding a method. The
same is true for each of the subclasses under Athlete, they each override the toString method
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
197
in the Athlete class. Examples of how this works is included in the next section. First, let’s see
the code for each of these classes, then I will point out how polymorphism is used in this
example.
#A Create four students: (2) field hockey players, 1 football player, 1 tennis player
#B Use the setGoalsScored method for a field hockey player to set the number of goals scored
#C Create a student object
#D Create an array to hold all the field hockey players
#E Create an array to hold the list of all students (remember, each athlete is a student)
#F Add all the students to the Student array
#G Use an enhanced for loop to go through all the students
#H Check if the student is a field hockey player (using the instanceof keyword)
#I If it is a field hockey player, add them to the field hockey array
#J Create a new sports team for the field hockey team
#K Add the field hockey players to the team
#L Print out all players on the field hockey team
In Listing 16.1, we start to see a glimpse of polymorphism. Notice that on lines 16-19, I am
adding my athletes to the students array. Since each type of athlete (FootballPlayer,
SoccerPlayer, etc.) extends Athlete and the Athlete class extends Student, we can assign each
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
198
#A If the array element is not set to an object, it will be null, so it should not be added to the team list
#B This statement calls the setEligibility method to check the GPA of the student, if it is < 2.0, they are ineligible
#C If the athlete is active and has a GPA of 2.0 or above, they are added to the team list
#D This method overrides the toString method in the Object class
#E Polymorphism is used to determine which toString method to call, in this case, the Athlete.toString() method
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
199
The SportsTeam class is designed to create a roster of eligible athletes for each sports team.
This class accepts a list of potential athletes in the method starting on line 10. To avoid
encountering a null pointer exception, line 12 checks to make sure each value in the athletes’
array has been instantiated. Then it checks to see if each athlete is active and eligible, if the
athlete is eligible, then they are added to the list of team members. There is also a toString
method that prints the team name and a list of athletes on the team. In this example it might
seem strange to have the override statement on line 21, but even though the SportsTeam
class does not explicitly extend any other classes, remember, all classes extend the Object
class by default. So, the toString method in the SportsTeam class overrides the toString
method in the Object class. The next listing is for the Student class.
The Student class is designed to represent all students. It contains information about the
student’s name, age, grade, and GPA. This class is the superclass to the Athlete class. This
makes sense since every Athlete must be a Student. Note that this class has two public
methods:
public double getGPA()
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
200
Since these methods are public, they become accessible to any subclass that extends the
Student class.
Here is our first subclass of the Student class. The athlete class is not specific to a certain
sport, it is representative of all students who play sports. It includes access to all the public
and protected characteristics of the Student class, and then adds any additional characteristics
specific to all athletes. In this example, I have added two boolean variables that are used to
indicate if the athlete is active/inactive and eligible/ineligible. In the code listing 16.4 on line
12, you can see that the program is referencing the getGPA method in the Student class.
Since that method is defined as a public method, it is available to all the subclasses. This is
an example of how inheritance can be used in Java.
The method starting on line 21 is an overridden version of the toString method. So, when
an object reference is for an Athlete object, if the code calls the toString method, it will
execute this method. Inside this method I am using the keyword super to reference the
toString method in the Student class. This enables my program to use the code already
written for part of the String that gets returned from a call to this method.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
201
Since these methods are public, they become accessible to any subclass that extends the
Athlete class in addition to the two public methods from the Student class.
In the FieldHockeyPlayer class, it has access to all of the following methods from the Athlete
class and the Student class:
public double getGPA()
public void setEligibility(boolean)
public void setStatus(boolean)
public boolean getEligibility()
public boolean getStatus
public String toString()
Since the toString method is actually overridden in the FieldHockeyPlayer class, it gets invoked
whenever a variable references a FieldHockeyPlayer object. This is the power of
polymorphism, here is an example:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
202
Now that we have all the classes defined, let’s review how the virtual machine determines
which method to invoke. Remember, if a class extends another class, it can access any public
or protected attributes and methods of the superclass. For example, in code listing 16.6, I
start by defining a variable that references a Student object. Next, I am going to update the
reference value of this variable to a FieldHockeyPlayer data type. At this point, the variable
has access to the public met
Figure 16.4 Hierarchy diagram for the Sports Teams and Students on these teams (reprinted)
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
203
Using the diagram in Figure 16.1, I’ve created a table with sample code that instantiates
several types of objects. Most of the statements are valid, but there is one statement that
causes a compile time error: Incompatible types: Student cannot be converted to
Athlete. Review the table and notice the use of the superclass and subclass references.
Student s = new Student (); Valid The variable s is a reference to a Student object
Student a = new Athlete(); Valid The a variable points to an Athlete object, but the
reference type is a Student (which is allowed since
Athlete is a subclass of Student)
When working with inheritance, it is sometimes difficult to understand what is allowable when
using a superclass or subclass to create various objects. A general rule is that the variable
declaration on the left-hand-side must be the same or a superclass of the instantiated object
on the right-hand-side. The benefit of creating a variable using the parent class is that the
variable name can be reassigned to any of the subclasses. But, don’t be fooled, since the
variable is considered a reference to a parent object, it only has access to public data and
methods in the parent class and access to any methods that are overridden in the child class.
The next section discusses how we can work with upcasting and downcasting to
get around this limitation.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
204
a. Incompatible types
b. No error, the statement is correct
c. Missing arguments
d. Syntax error
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
205
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
206
#B Since we included the check to make sure this object is a FieldHockeyPlayer, we can use this to downcast from
Student
One important note when using upcasting and downcasting is the order of precedence of the
dot operator. In my example, I am casting the Student object s to a FieldHockeyPlayer object
before adding it to the fhPlayers array. If I needed to access any of the instance data or
methods from the FieldHockeyPlayer class, I can use this same logic. I can cast the Student to
a FieldHockeyPlayer, but I must enclose the casting portion with parentheses so that it is done
first. Table 16.2 shows valid/invalid access to the FieldHockeyPlayer class methods given the
Student reference variable s. These statements would be defined in the main method from
Listing 16.6.
Student s = new FieldHockeyPlayer(…); Invalid This statement causes an error since the
(FieldHockeyPlayer)s.setGoalsScored(4); compiler tries to execute the dot operator
first. But the Student object s does not
have a method called
setGoalsScored().
Student s = new Athlete(…); Valid Since the object is first cast to an Athlete,
((Athlete)s).setEligibility(true); this statement is now valid.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
207
a. SoccerPlayer sp = (SoccerPlayer)a;
b. Student s = a;
c. Athlete a = (Athlete)(s);
a. SoccerPlayer sp = (SoccerPlayer)a;
b. Student s = a;
c. Athlete a = (Athlete)(s);
Given the classes for Student, Athlete, and TennisPlayer, and the code below to answer the
following questions:
TennisPlayer tp1 = new TennisPlayer("Abhiram", "Nirman", 17, 11, 4.0,
true, "L", true);
Athlete tp2 = new TennisPlayer("Bethan", "Palmer", 15, 10,
3.5, true, "S", false);
Student tp3 = new TennisPlayer("Yung-jin", "Ryoo", 14, 9,
3.75, true, "M", false);
Student s1 = new Student("Zahraa", "Khalil", 14, 9, 3.95);
1. Which statement does NOT use the toString method in the TennisPlayer class first:
a. tp1.toString();
b. s1.toString();
c. tp2.toString();
d. tp3.toString();
2. Which statement(s) can access the getStatus() method of the Athlete class:
a. tp1.getStatus();
b. s1.getStatus();
c. tp2.getStatus();
d. tp3.getStatus();
3. Which class toString method is called first with this code snippet:
((Athlete)tp3).toString();
a. Athlete
b. TennisPlayer
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
208
c. Student
d. none, it gives you an error message
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
209
16.5 Summary
In this lesson, you learned:
I realize this was a long lesson with a lot of information. This lesson reviewed how to create
objects that are derived from the same class hierarchy but behave differently, this is called
polymorphism in Java. And finally, we learned how to determine which method is invoked
when multiple methods exist with the same method signature. In the next lesson, I introduce
another topic related to comparing objects.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
210
Try this:.
Figure 16.4 shows the class hierarchy of an Electronics class, plus a new class CellPhone. The
CellPhone class represents another type of Electronics and it should include an overridden
print method. For this activity, add a CellPhone class to the code from listing 16.7 and then
create the following objects in the main method that invoke the print method in the CellPhone
class:
Figure 16.6 shows the hierarchy of the Electronics class with a new CellPhone class added
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
211
#A The main method creates an Electronics object, calls the print and setMake methods
#B The electronics class is the superclass
#C The Television class extends the Electronics class and overrides the print method
#D The Computer class also extends the Electronics class and overrides the print method
a. An Athlete is a Student
b. A TennisPlayer is a Student
c. A TennisPlayer is an Athlete
d. A Student is an Athlete (not every student is an athlete)
2. If we add a new class that extends Computer called Laptop, which of the following is valid:
a. SoccerPlayer sp = (SoccerPlayer)a;
b. Student s = a;
c. Athlete a = (Athlete)(s);
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
212
a. SoccerPlayer sp = (SoccerPlayer)a;
b. Student s = a;
c. Athlete a = (Athlete)(s);
NOTE: It can be difficult to differentiate between upcasting and downcasting. In this activity,
the answer to Question 1 shows code that changes an Athlete object reference and casts it as
a SoccerPlayer reference. So, it is going from the superclass to a subclass, hence downcasting.
Question 2 does the opposite, it takes a subclass object and casts it as a superclass implicitly
in the assignment statement.
Given the classes for Student, Athlete, and TennisPlayer, and the code below to answer the
following questions:
TennisPlayer tp1 = new TennisPlayer("Abhiram", "Nirman", 17, 11, 4.0,
true, "L", true);
Athlete tp2 = new TennisPlayer("Bethan", "Palmer", 15, 10,
3.5, true, "S", false);
Student tp3 = new TennisPlayer("Yung-jin", "Ryoo", 14, 9,
3.75, true, "M", false);
Student s1 = new Student("Zahraa", "Khalil", 14, 9, 3.95);
1. Which statement does NOT use the toString method in the TennisPlayer class first:
a. tp1.toString();
b. s1.toString();
c. tp2.toString();
d. tp3.toString();
2. Which statement(s) can access the getStatus() method of the Athlete class:
a. tp1.getStatus();
b. s1.getStatus();
c. tp2.getStatus();
d. tp3.getStatus();
3. Which class toString method is called first with this code snippet:
((Athlete)tp3).toString();
a. Athlete
b. TennisPlayer
c. Student
d. none, it gives you an error message
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
213
#A Creates an Electronics object set to a new CellPhone instance (must include three arguments)
#B Creates a CellPhone object
#C Calls the print method in the CellPhone class (because it overrides the Electronics class)
#D Calls the print method in the CellPhone class
#E Prints the style value for the CellPhone object
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
214
17
Comparing Objects
• Understand the difference between comparing objects vs. primitive data types
• Compare objects for equality
• Use the Comparable interface and override the compareTo method to compare objects
When comparing primitive data types such as numbers, Java uses the mathematical symbols
that we are all familiar with: >, >=, ==, <, <=. Java also includes an exclamation point to
negate any comparison. But these symbols alone do not help us compare objects. Instead, we
need to define methods that provide comparisons such as equals, less than, and greater than.
In this lesson, you will learn how to compare objects.
Consider This
Imagine a neighborhood where all the houses were built by the same contractor. She made each house the same with
the two bedrooms, two bathrooms, a living room, a kitchen, a laundry room, and a one car garage. The owners of the
houses might have changed the type of roof (metal vs. shingle) or the exterior color of the house. Each house in the
neighborhood has a different house number. So, if your address is 123 Main Street, the house next door might be 124
Main Street.
A realtor wanted to have a report that compared these houses. If they compare the address location, it would not be
the same. But if they wanted to know if they have the same layout, then that would be true since all the houses were
built the same. So, it is important to understand if we are comparing two houses based on their characteristics or their
location.
The same is true about objects in Java. A reference variable for an object in Java contains the memory address of
that object. So, even if we create two House objects and they have the exact same information, the address location of
each object would be different. To compare these House objects, we need to identify what information should be used
in the comparison. For example, we can check to see if they have the same number of rooms and the same roof
material.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
215
There are times when we also want to know if two object reference variables contain the same memory address.
This comparison is done by comparing the reference variables. This is similar to checking the street address of two
houses to see if they are actually the same house.
Figure 17.1 shows what happens when comparing two primitive data values
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
216
Can you think of an instance where p1 might be equal to p2? If we are interested in whether
or not both values have the same reference value, then they are equal. In this case, the
objects are considered aliases of each other. In this example, I can accomplish this by having
p2 point to p1:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
217
Now, p1 and p2 have the same reference value and point to the EXACT same object in
memory. Therefore, when we compare them using the == sign, the statement is considered
true. In the next section, I will show you how to add a method to compare two objects for
equality.
Listing 17.1 contains code for a Person class and a main method
1 package lesson17_examples;
2 public class Lesson17_Examples {
3 public static void main(String[] args) {
4 int x = 35;
5 int y = 5;
6 if(x == y) //#A
7 System.out.println("x is equal to y");
8
9 Person p1 = new Person("Cy", "Young", 35);
10 Person p2 = new Person("cy", "young", 35);
11 if(p1 == p2) //#B
12 System.out.println("p1 is equal to p2");
13 if(p1.age == p2.age) System.out.println("p1 age is equal to p2 age"); //#C
14 if(x == p1.age) System.out.println("x is equal to p1 age"); //#D
15 }
16 }
17 class Person {
18 String fname, lname;
19 int age;
20 public Person(String fname, String lname, int age) {
21 this.fname = fname;
22 this.lname = lname;
23 this.age = age;
24 }
25 }
a. p1 is equal to p2
b. p1 is equal to p2
p1 age is equal to p2 age
x is equal to p1 age
c. p1 age is equal to p2 age
x is equal to p1 age
d. x is equal to p1 age
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
218
Listing 17.2 contains code for a Person class with an extra method for comparing Person
objects
1 package lesson17_examples;
2 public class Lesson17_Examples {
3 public static void main(String[] args) {
4 Person p1 = new Person("Sheila", "Gelin", 35);
5 Person p2 = new Person("Sheila", "Gelin", 35);
6 Person p3 = new Person("Ray", "Villalobos", 25);
7 if(p1.equals(p2)) System.out.println("p1 is equal to p2"); //#A
8 if(p1.equals(p3)) System.out.println("p1 is equal to p3"); //#A
9 }
10 }
11 class Person {
12 String fname, lname;
13 int age;
14 public Person(String fname, String lname, int age) {
15 this.fname = fname;
16 this.lname = lname;
17 this.age = age;
18 }
19 public boolean equals(Object obj) { //#B
20 if (obj instanceof Person) {
21 if (this.fname == ((Person) obj).fname
22 && this.lname == ((Person) obj).lname
23 && this.age == ((Person) obj).age) {
24 return true; }
25 }
26 return false;
27 }
28 }
#A This statement uses the new equals method defined in the Person class to test for equality
#B This method checks to see if the first name, last name and age are the same
In the new equals method, each field from the Person class is compared. If they are all equal,
the method returns true. If the object data is not the same or if it is not an instance of the
Person class, it returns false. Notice that the equals method is invoked on lines 7 and 8 in
Listing 17.2. The method uses the object on the left-hand side (lhs) as the calling object, in
this case p1 is the calling object for both statements. In the parentheses, the program passes
an object as the argument to the method. The first statement uses p2, the second statement
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
219
uses p3. In the equals method, the values of the calling object are referred to by the keyword
this. The objects p2 and p3 are passed to the argument variable obj which is defined as an
Object. Remember, every class inherits from the Object class, so we can use that to define an
Object variable and have it reference a Person object. But, in order to compare the fields from
our calling object to the information in our argument object, we must cast it as a Person
object. Finally, notice the use of the instanceof keyword to check if the argument is a Person
object.
Figures 17.4 and 17.5 are diagrams depicting how the objects are passed to the equals
method with annotation to help explain how the variables in the method refer to different
objects.
Figure 17.4 shows what happens when three Person objects are created
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
220
Figure 17.5 is a diagram showing how the objects are passed to the equals method for comparison
NOTE: it is also possible to use the .equals method from the String class to compare the first name and last
name instead of the == operator, this code produces the same results as above:
By adding the equals method to the Person class, the programmer can define the criteria for
comparison based on the business requirements. For example, if the business requirements
want to compare two Person objects and consider them equal if they have the same first name
and last name, regardless of age, the code could be changed to only test those two
characteristics of the objects. Listing 17.3 shows a revised version that only checks for first
and last name to be the same.
Listing 17.3 revised listing to only compare first and last names
1 package lesson17_examples;
2 public class Lesson17_Examples {
3 public static void main(String[] args) {
4 Person p1 = new Person("Sheila", "Gelin", 35);
5 Person p2 = new Person("Sheila", "Gelin", 35);
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
221
#A The equals method has been updated to only check for first name and last name
Person p4 = p3;
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
222
comes first based on our business requirements. This type of comparison is usually needed to
help sort a list of objects.
In my example, the business requirements might require that the application has the
ability to sort the Person objects by last name. Lucky for us, Java provides a Comparable
interface that can be used to define the process for comparing two objects. We start by
implementing the Comparable interface and then provide an overridden method for the
abstract method, compareTo(Object o). Code listing 17.4 shows an example of how to use
the Comparable interface. To save space, I have only added two Person objects and sorted
them by last name. I’ve also added an overridden toString method to return the person name.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
223
#C When implementing Comparable, the program MUST provide an overridden implementation of the compareTo()
method
#D Compare the last name of each object, if the calling object is first alphabetically, return -1
#E If the last name is exactly the same regardless of capitalization, return 0
#F If the last name of the calling object comes after the last name of the argument object, return 1
a. Wise, Kaitlyn
Wise, Hannah
b. Wise, Hannah
Wise, Kaitlyn
c. Wise, Hannah
Wise, Hannah
d. Wise, Kaitlyn
Wise, Kaitlyn
a. Wise, Kaitlyn
Jones, Courtney
b. Johnson, Courtney
Wise, Kaitlyn
c. Jones, Courtney
Johnson, Courtney
d. Johnson, Courtney
Jones, Courtney
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
224
17.4 Summary
In this lesson, you learned:
• that primitive data types can be compared using <, <=, >, >=, or == but the same is
not true for objects
• how to add a new method to compare two objects for equality
• to implement the Comparable interface to compare two objects based on business
requirements
This lesson reviewed how to compare objects in Java. Most classes are defined with one or
many attributes. In order to compare two objects, the application must add logic to identify
what attributes to compare and the criteria for comparing them. In the example, the Person
class defined three attributes: first name, last name, and age. In order to compare two
objects, it is necessary to identify what attributes are included in the comparison. The
business requirements might only want to know if all person objects are the same age. But
another requirement might be to sort all the person objects by age from oldest to youngest.
So, in this lesson we learned how to check objects for equality and how to add logic for
comparing two objects. In the next lesson, I will be combining Lessons 14-17 in a cumulative
capstone project.
Try this:.
A bank account might have an account number, the customer first and last name, and a
beginning balance. If we want to compare two bank account objects, we need to determine
which values to compare. For this activity, start with a BankAccount class that implements
Comparable. Add the four instance data fields and then provide an equals method that
determines if the accounts are duplicates. This is needed since the list of accounts might have
accidentally assigned the same information to two account objects.
Listing 17.1 contains code for a Person class and a main method
1 package lesson17_examples;
2 public class Lesson17_Examples {
3 public static void main(String[] args) {
4 int x = 35;
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
225
5 int y = 5;
6 if(x == y)
7 System.out.println("x is equal to y");
8
9 Person p1 = new Person("Cy", "Young", 35);
10 Person p2 = new Person("cy", "young", 35);
11 if(p1 == p2)
12 System.out.println("p1 is equal to p2");
13 if(p1.age == p2.age) System.out.println("p1 age is equal to p2 age");
14 if(x == p1.age) System.out.println("x is equal to p1 age");
15 }
16 }
17 class Person {
18 String fname, lname;
19 int age;
20 public Person(String fname, String lname, int age) {
21 this.fname = fname;
22 this.lname = lname;
23 this.age = age;
24 }
25 }
a. p1 is equal to p2
b. p1 is equal to p2
p1 age is equal to p2 age
x is equal to p1 age
c. p1 age is equal to p2 age
x is equal to p1 age
d. x is equal to p1 age
Person p4 = p3;
which statement(s) are true: (all of them)
a. if(p3 == p4)
b. if(p3.equals(p4)
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
226
c. if(p3.fname == p4.fname)
d. if(p3.lname == p4.lname)
a. Wise, Kaitlyn
Wise, Hannah
b. Wise, Hannah
Wise, Kaitlyn
c. Wise, Hannah
Wise, Hannah
d. Wise, Kaitlyn
Wise, Kaitlyn
a. Wise, Kaitlyn
Jones, Courtney
b. Johnson, Courtney
Wise, Kaitlyn
c. Jones, Courtney
Johnson, Courtney
d. Johnson, Courtney
Jones, Courtney
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
227
#A Creates three bank account objects where ba1 = ba2, but ba3 is slightly different
#B Test the equals method with two objects that are the same
#C Test the equals method with two objects that have a slight difference (this message should not print)
#D Create an equals method that takes in an object and returns a boolean
#E Create a BankAccount object and set it to null
#F Test if the object in the argument list is of type BankAccount
#G If the object is an instanceof BankAccount, then assign it to the variable ba
#H Check if the variable ba is not null (which means the argument value was a valid BankAccount object)
#I Compare all four values of calling object to ba (which was passed as an argument to the method)
#J If all fields are the same, return true
#K If all fields are not the same, return false
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
228
18
Capstone
The capstone for this unit concentrates on the learning objectives from lessons 13-17 but also
includes everything we have learned so far in this book. The lesson starts with a set of
business requirements. Based on these requirements, I will walk through the steps to
complete an application. The business problem we are going to address is providing a report of
upcoming projects for a general contracting business. A general contractor is hired for various
type of projects from building a house to minor repairs. For this application, the contractor
wants to keep track of the employees working on a project, the project customer’s name and
address, and the start and end date for the project.
1. Create a project with a start date, end date, customer name, address of the project,
description, estimated cost, overhead percentage for the contractor, and a list of
workers
2. Print out the list of projects including the project address location
3. Compare two projects and determine which project must be done first based on the
start date
• Electrician
• Plumber
• Carpenter
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
229
The workers are paid hourly, but they also each have additional expenses. It is also important
to understand that the general contractor might not need all of these workers for every
project. For example, if the contractor is building a new house, she needs all three types of
workers. But if she is only adding an extra room onto an existing house, she might only need
an electrician and a carpenter.
For this lesson, the application is designed with a minimal amount of information about
each project, but it is used to demonstrate the concepts from this unit. It also provides the
framework for a larger, more comprehensive application such as adding inventory tracking for
the general contractor. The next section reviews the classes need for this application.
The electrician, plumber and carpenter are types of workers, so each of these classes will
extend the worker class. Figure 18.1 shows the initial UML diagram for these classes. More
instance variables and additional methods might be needed later, but this is a good starting
point.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
230
Figure 18.1 contains a diagram of the initial UML diagrams for each class
Using this approach to create the classes for this project, I can create a list of workers who are
associated with a specific project. This design creates a list of workers which can be a regular
Worker, an Electrician, a Carpenter, or a Plumber. Notice that each subclass of the Worker
class overrides these methods: doWork, calculatePay and toString. Using polymorphism I can
invoke the overridden methods for each type of worker when calculating their total project
cost which is made up of wages and expenses. Polymorphism is also used when each subclass
overrides the toString method and the JVM decides which specific version of the toString
method to invoke.
One of the requirements for this project is to have the ability to compare two projects and
identify which projects should be started first. To provide this comparison, the Project class
implements Comparable and then overrides the compareTo method.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
231
• start date
• end date
• customer name
• project description
• address location of the project
• list of workers
The constructor for this class is setup to take in the project name, owner name, address of the
project, and the start/end dates of the project. Since some projects might not have start and
end dates assigned yet, there are two overloaded constructors for this class. Listing 18.1
shows the first part of the Project class, I have split it into pieces to better describe what is
occurring in each section.
#A The project class implements comparable to compare the start dates of any two projects
#B Use the LocalDate class to store the start/end date of the project
#C This is considered an overloaded constructor since it does not have the same number of parameter values
NOTE: When I first started writing the main method for this application, I started using the Date class, but
quickly realized that parts of the Date class are deprecated (which means they are no longer supported).
Instead, I switched to using the java.time package and the LocalDate class to store the dates used in this
application. I recommend checking out the JavaDoc from Oracle on the java.time package which is part of the
Java API located here: https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
232
Next, I have included a method to add the workers to the project using an ArrayList so I can
easily add/remove/update the workers assigned to this project. There is also a method to
calculate the cost based on the workers payroll plus any overhead amount for the general
contractor. This general contractor does not earn an hourly wage, instead she assigns an
overhead percentage which is added to the total cost for the project. This covers her time and
expenses. The overhead amount is normally 10%, but the application has the ability to
change that value depending on the degree of difficulty of the project.
Notice in the method to calculate the Project cost, I used an enhanced for loop to obtain the
information about all the workers in the ArrayList. This is helpful if you are not sure how
many workers are assigned to each project, the code loops through the ArrayList and stops
when it reaches the last worker.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
233
#A This is the overridden compareTo method that compares the two start dates
#B The if statement can be written in a more condensed version:
return ((Project) o).startDate.compareTo(this.startDate);
#C This method overrides the Object toString method to return a String with all the project details
In the project class, notice that it contains two overridden methods. The first is the
compareTo method, this is required when you implement the Comparable interface from the
Java API. In this class, I have provided logic to compare the start date of any two projects.
In the compareTo method, the project compares the start date of the project that is invoking
the method and passing the other project as an argument to the compareTo method.
By implementing the compareTo method in the Project class, it allows me to easily
compare two projects. For this example, I am comparing the start dates of each project, but
this method can easily be updated to compare other components of the project. Just
remember that the compareTo method returns and integer value with the following values:
• negative number if the first object comes before the second object
• zero if they are equal
• positive number if the first object comes after the second object
This gives the programmer control on what is compared and what determines the order. We
could change our project to compare two projects and identify which client name comes first
alphabetically for example.
The second overridden method is the toString method. Remember, every class
automatically inherits from the Object class which has a toString method. If I did not provide
an overridden method, any time I called the toString method it would simply return the
reference address of the object. Instead, in the Project class, the overridden version of the
toString method formats and returns all the information about a project for printing.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
234
address, and a second constructor for addresses with a second street line. The second street
line is often used for identifying an apartment number or even a PO Box.
#A The Address class has an overloaded constructor for any address objects with a second street line
#B The toString method is overridden to return the address in a formatted String
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
235
10 }
11 public Worker(String fName, String lName, Address address,
12 int idNumber, double hours, double rate) {
13 this.fName = fName;
14 this.lName = lName;
15 this.address = address;
16 this.idNumber = idNumber;
17 this.hoursWorked = hours;
18 this.hourlyRate = rate;
19 }
20 public void setHoursWorked(double hours) {
21 hoursWorked = hours;
22 }
23 public void setHourlyRate(double rate) {
24 hourlyRate = rate;
25 }
26 public double calculatePay() {
27 return hoursWorked * hourlyRate;
28 }
29 @Override
30 public String toString() { //#B
31 return fName + " " + lName + " \nCompensation: $"+calculatePay();
32 }
33 }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
236
#A The Carpenter class extends the Worker class which enables it to use the public attributes of the Worker class
#B This statement uses the Worker constructor to initialize the name, address, id number, hours and rate
#C The doWork() method is overridden, this is allowing the Carpenter to do specific carpentry work
#D The toString method is overridden to return the Carpenter information in a formatted String
#E Since the Carpenter might have additional lumberCosts, the calculatePay method is also overridden
#A The Electrician class extends the Worker class which enables it to use the public attributes of the Worker class
#B This statement uses the Worker constructor to initialize the name, address, id number, hours and rate
#C The doWork() method is overridden, this is allowing the Electrician to do specific electrical work
#D The toString method is overridden to return the Electrician information in a formatted String
#E Since the Electrician might have additional wiringCosts, the calculatePay method is also overridden
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
237
#A The Plumber class extends the Worker class which enables it to use the public attributes of the Worker class
#B This statement uses the Worker constructor to initialize the name, address, id number, hours and rate
#C The doWork() method is overridden, this is allowing the Plumber to do specific electrical work
#D The toString method is overridden to return the Plumbing information in a formatted String
#E Since the Plumber might have additional plumbing costs, the calculatePay method is also overridden
A future version of this application might include more information for each type of worker.
There are definitely more differences between each type of worker, but this gives you an idea
of how the project can be started.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
238
constructor since this worker has a second address line for the apartment number
• Add three workers, an electrician, plumber, and carpenter that can be used on these
projects
• Add these workers to an ArrayList so we can assign them to a project
• Add all three workers to the house project
• Set the lumber costs to $2000
• Set the general contractor overhead to 18% for this large project
• Print out the project information
• Repeat the process for the small outdoor motion lighting project
• Compare the start dates to determine which project needs to start first and print the
appropriate message
Now that all the classes are created, we turn our attention to the main method. The goal of
the main method in this example includes logic to demonstrate all the topics covered in this
unit. A few important concepts are shown in Listing 18.7 (lines 28-30) where the Worker class
is used to create a reference variable that points to a subclass object. These lines are
enabling polymorphism.
Since all the workers are created using the superclass Worker, line 37 shows how I had to
cast the worker as the specific subclass that was used when it was created to allow access to
methods defined in the subclass that were not overridden methods.
Before reviewing the code for the main method for this application, here is a printout of
some sample output:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
239
Listing 18.7 part 1 shows the main method that includes the code to create all the Address,
Project, LocalDate, and Worker objects.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
240
5
6 public class Lesson18_Example {
7 public static void main(String[] args) {
8 Address client1 = new Address("123 Main Street", "Anywhere", "PA", //#A
9 "19001");
10 Address client2 = new Address("44 South Main Street", "Cleveland", "OH",
11 "42111");
12 LocalDate start1 = LocalDate.parse("2019-11-03"); //#B
13 LocalDate end1 = LocalDate.parse("2020-05-29");
14 Project p1 = new Project("House", "Shira Gotshalk", client1, //#C
15 start1, end1);
16 LocalDate start2 = LocalDate.parse("2019-06-26");
17 LocalDate end2 = LocalDate.parse("2019-07-27");
18 Project p2 = new Project("Motion Lights", "Maggie Thygeson",
19 client2, start2, end2);
20
21 Address eAddress = new Address("467 Seminole Avenue", "Jenkintown",
22 "PA", "19446");
23 Address cAddress = new Address("88 Stallion Circle", "Horsham",
24 "PA", "19022");
25 Address pAddress = new Address("9821", "Apt B", "Siglerville",
26 "PA", "19345");
27
28 Worker e = new Electrician("Peg", "Fisher", eAddress, 1234, 15, 20); #D
29 Worker c = new Carpenter("Yusef", "Eberly", cAddress, 2456, 17.40, 30);
30 Worker p = new Plumber("Harley", "Davidson", pAddress, 3214, 25, 20);
#A The project address is required when creating a new project, so it must be created first
#B Using the LocalDate class from the java.time package which was added in Java 8
#C Create a new project for building a house
#D Create three worker objects: an electrician, carpenter, and a plumber
Next is the second part of the main method. This is where the workers are added to the
project. The first project uses all three types of workers and extra costs are assigned for each
worker. The second project only requires an electrician, so the plumber and carpenter are
removed from the list of workers and the wiring costs are updated for the electrician prior to
creating the project. Finally, the projects are printed using the overridden method toString.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
241
46
47 workers.remove(p); //project 2 does not need a plumber //#I
48 workers.remove(c); //project 2 does not need a carpenter
49 ((Electrician)e).setWiringCosts(300); //#J
50 workers.get(0).sethoursWorked(20); //set the hours worked to 20 //#K
51 p2.addWorkers(workers);
52 System.out.printf(p2.toString(), p2.getName(),
53 p2.getTotalCost(), p2.getOverhead());
54
55 if (p2.compareTo(p1) < 0) {
56 System.out.println("\nThe "+p2.getName()+" project is "
57 + "scheduled before "+p1.getName());
58 } else {
59 System.out.println("\nThe "+p1.getName()+" project is "
60 + "scheduled prior to "+p2.getName()); }
61 System.out.println("\n");
62 p2.printPayroll();
63 }
64 }
18.3 Summary
In this lesson, you learned:
• How to write an application that uses overloaded methods specifically for constructor
methods
• How to create overridden methods in a subclass
• How to create a list of superclass objects that are instantiated as specific subclasses
• Based on the type of worker, update specific values for each project such as lumber
costs, wiring costs by casting the superclass as one of the subclasses
• How to use the Comparable method and overriding the compareTo method to compare
the start date of any two projects
This lesson provided an activity that included all the topics from lessons 13 - 17. In the next
unit, I will continue to work with classes and objects. The first lesson in the next unit is all
about the difference between pass by value vs. pass by reference.
Try this:
Use the Contractor application and add the required code to print out a payroll statement by
project that includes:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
242
Figure 18.3 shows a sample of the output from print a payroll report.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
243
#A To reduce the amount of space required, please refer to listing 18.1 for the omitted code
#B The method loops through all the worker objects, it then tests for a specific subclass to print the appropriate worker
type
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
244
20 project2.addWorkers(workers);
21 // System.out.printf(project2.toString(), project2.getName(),
22 // project2.getTotalCost(), project2.getOverhead());
23 //
24 // if (project2.compareTo(house) < 0) {
25 // System.out.println("\nThe outdoor light project is scheduled "
26 // + "before the addition");
27 // } else {
28 // System.out.println("\nThe addition is scheduled prior to the "
29 // + "outdoor lighting project");
30 // }
31 System.out.println("\n");
32 project2.printPayroll(); //#B
33 }
34 }
#A To reduce the amount of space required, please refer to listing 18.7 for the omitted code
#B Call the printPayroll method in the Project class
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
245
Unit 4
More Programming with Objects
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
246
19
Pass by Value vs. Pass by Reference
In this lesson, you will learn that all arguments are copied into the parameter variables when
a method is called. For this lesson, I want to have a consistent naming for the values
described, so here is a diagram of the terms in this lesson:
Figure 19.1 Diagram identifying the key terms for a method call
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
247
In figure 19.1, I have identified the key terms that are used when calling a method. Methods
are designed to allow the calling program to pass in values as arguments. In this lesson, I will
review scenarios that pass primitive data types, Strings and other objects. For each scenario,
I will identify if it is a pass by value or pass by reference.
Consider This
Most of the programs that are written use methods to help allow for code reuse and to make the program easier to
read. When calling a method, it is important to understand the purpose of the method, what information does the
method need and what information is returned.
We can pass information to a method; the original value is always copied to the parameter variables in the method
header. In Java, the variable names can be identical between the calling program and the method parameter list. This
does not cause a syntax error since Java allocates memory for each new variable in the method parameter list. These
variables start with the same value as the calling program, but they can be changed by the method. When the method
returns control to the calling program, the memory is released, and the variables are no longer accessible. In this case,
the original values are unchanged.
It sounds like all variables are created equal, but it is important to remember that primitive data types have values
stored with the variable name in memory, but object variables only store the memory address of the object.
So, when an object variable is copied to a parameter, the address is copied. Think of this as a house address. If we
provide the address, it is possible to make changes to the house without updating the address. Then, when control is
returned to the calling program, the house still has the changes.
But if we think of an example of a primitive data type, let’s say quantity, and we start with a quantity of 5 oranges.
That value is copied to our method where it might change the quantity to 6, but when the method returns control to the
calling program, we still only have 5 oranges. That value is not changed.
Let’s look at an example. The output in figure 19.2 is from the code snippet in Listing 19.1.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
248
Figure 19.2 This figure is a screenshot of the output from executing the code in Listing 19.1
Listing 19.1 Sample code that takes a number and returns the value of the number
doubled
Listing 19.1 shows the code snippet used to create the output in figure 19.2. The variable
value from the main method starts as the value 10.0. When it is passed to the doubleMethod,
the value of the argument variable on line 14 is copied into another double variable also called
value on line 4. The method then uses the parameter variable and multiplies it by two, then
returns the new value to the main method which is then stored in the variable doubledValue.
In this example, I added print statements to the main method before and after the call to the
doubleMethod. Once the method returns control to the main method, the parameter variable
value is no longer accessible.
NOTE: In the example, the variable names of the argument and the parameter are both the same. When the program
executes, the JVM creates two of the same variable names in memory with their respective values, it does NOT consider
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
249
these the same variable. The variable inside the doubleMethod is only available inside the method. It is considered a
local variable that is only accessible to the code inside the method. After the return statement is completed, the
variable is released from memory as shown in figure 19.3.
Figure 19.3 shows how the memory is updated for each of the labelled statements, #A, #B,
#C and #D. Starting with line 9, two variables are created in memory and initialized with
numeric data: value = 10.0 and doubledValue = 0.0. Next, line 14 passes the value of 10.0 to
the new parameter variable defined for the method on line 4, this appears in the
doubleMethod section of the diagram. This value is multiplied by 2 and returned to the calling
program on line 5. At that point, the value 20.0 is then placed in memory for the variable
doubledValue. Once the return statement is executed, the method variable called value is no
longer accessible and this is indicated in the diagram with a circle and strike through line.
Figure 19.3 This figure shows how the variables are created in memory and updated throughout the code
snippet
Every argument value is copied into the corresponding parameter, but if it is a primitive data
type the original argument value is never changed by the method. The method creates a local
copy of the value that can be manipulated inside the method, when control is passed back to
the calling method, this value is no longer available.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
250
This process works the same for all primitive data types. Remember, a method can contain
parameters of multiple primitive data types or even multiple parameters of the same data
type. It can also contain a mix of primitive data types and object references. This section
describes what happens to the variables defined as primitive data types. At the end of the
lesson, I will review an example that has both primitive and object reference data types. Each
time the method is called, the argument values are copied to the corresponding parameter
variables. Once the method returns control to the calling method, the parameter variables are
no longer accessible.
Before moving on to object reference types, let’s look at one more example that has multiple
parameter values. Figure 19.4 shows the sample output from executing the code snippet in
Listing 19.2
Figure 19.4 is a screenshot showing the values of quantity, cost, and totalCost after executing the calculateCost
method
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
251
In this example, the method name is calculateCost and it has two parameter variables for
quantity and cost. The quantity variable is of type int and the cost variable is a double. Both
of these variables are considered pass by value. The method multiplies the two values and
returns the total cost to the calling program. The method also sets the values to zero after it
calculates the total cost. Since all the values are pass by value, this does not change the
values in the main method.
In the next section, I will explain what happens when the value is an object reference. In this
case, the method copies the reference address and creates an alias to the location of the
information for that object in memory. So, when the information is updated, and the method
returns control to the calling program, the object values are still updated.
a) 0
b) 15
c) 20
d) Nothing, there is a compile time error
a) 0
b) 15
c) 20
d) Nothing, there is a compile time error
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
252
3) What is the value of the variable start after executing line 15?
a) 15
b) 14
c) 16
d) 0
4) What is the value of the variable total after executing line 16?
a) 10.0
b) 10.60
c) 0.60
d) 0
Figure 19.5 This figure shows the employee information before and after calling the setHourlyRate method.
Listing 19.4 Create an Employee object from the Employee class and update the hourly
rate
1. package lesson19_example;
2. class Employee {
3. public String fName, lName;
4. private double hourlyRate;
5. public Employee(String fName, String lName, double hourlyRate) {
6. this.fName = fName;
7. this.lName = lName;
8. this.hourlyRate = hourlyRate;
9. }
10. public String toString(){
11. return fName + " " + lName + " Hourly Rate: "+hourlyRate;
12. }
13. public void setHourlyRate(double hr) {
hourlyRate = hr; }
14. }
15. public class Examples {
16. public static void updateRate(Employee emp, double newRate) { //#C
17. emp.setHourlyRate(newRate); } //#D
18.
19. public static void main(String[] args) {
20. Employee e = new Employee("Joey", "McQuiston", 7.50); //#A
21. System.out.println("Employee before: " + e.toString());
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
253
Pass by reference occurs any time the argument variable contains an object. The term pass by
reference refers to the fact that the reference address of the object is copied from the
argument value into the corresponding parameter value.
In this example, there is an Employee class that contains the first name, last name, and the
hourly rate for each employee. In the main method, an Employee object is created and the
reference address is stored in the variable e on line 21. The reference address to the
Employee object is then passed to the updateRate method along with a new value for the
hourly rate on line 23.
The updateRate method has two parameter variables, one for the reference value to the
employee object called emp and a second parameter variable for the new hourly rate called
newRate. Now that the updateRate method has a copy of the address for the employee
object, it uses that address to find the memory location of the employee object and then it
updates the hourly rate. When the method returns control to the calling program, the
reference address to the employee object is not changed, but the hourly rate value stored at
that reference is now updated to the new rate.
I also added print statements to show the value of the employee object before and after
calling the method to update the hourly rate. Figure 19.5 shows the output from executing the
code in Listing 19.4 and is reprinted here for easy reference.
Figure 19.6 This figure shows the employee information before and after calling the setHourlyRate method.
This printout shows the values of the employee before and after calling the update hourlyRate
method. Notice that the hourly rate is updated in the second print statement which occurs
after the call to the updateRate method.
To help understand how pass by reference works, figure 19.6 shows a diagram of how the
values are stored in memory. In this figure, an Employee object is created with a String for
the first name and last name and a primitive data type for the hourly rate. The reference
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
254
address of the Employee object, e is copied to the parameter variable called emp. At this point
in the program execution, e and emp are pointing to the same object, that is, the same
location in memory. Next, the updateRate method changes the hourlyRate for the emp
object to 15.50. When control is returned to the main method, the employee object, e, also
shows the new rate since it refers to the same object in memory as emp.
Figure 19.7 shows how the Employee object is updated by the call to the setHourlyRate method
In this example, an object was created and the reference address to the object was passed to
a method. This is actually copying the address from the calling method argument to the
parameter variable so they both contain the same value, the location of the object in memory.
In our example, the location value is never changed, but if any of the values at that location
are updated, the updates will persist when the method ends and returns control to the calling
program. This can be confusing, so try to remember that arguments containing primitive data
types cannot be altered by the method, but arguments that contain an object reference
address can have the contents of the object updated the by the method.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
255
a. Mike Shepard
b. Sue Shepard
c. Null
a. Mike Shepard
b. Sue Shepard
c. Null
19.3 Summary
In this lesson, you learned:
This lesson explained the differences between pass by value and pass by reference. When
calling a method, the program might need to pass a value to the method. If the value is a
variable that contains a primitive data type, then the value is copied to a new variable defined
in the method parameter list. If the value is a reference to an object, then the reference
address of the object is copied to a new variable in the parameter list. The difference is that
changes to the object persist after the method returns control to the calling program.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
256
To update a variable defined with a primitive data type, the method must return the updated
value and the calling program must then assign the value back to the original variable. In the
next lesson, I will introduce the topic of garbage collection in Java. This topic also relates to
the persistence of data during program execution and after program execution.
Try this:
The code snippet in listing 19.6 is supposed to create a student record, then calculate the
average GPA for a year and then print out the information. But every time the program runs,
the GPA prints zero. For this exercise, identify where the problem is located and make the
appropriate corrections.
Listing 19.6
1. public class ErrorExample {
2. public static void main(String[] args) {
3. Student s1 = new Student("Peg", "Fisher");
4. double gpa = 0;
5. findGPA(gpa, 3.2, 4.0, 3.4, 3.8);
6. s1.setGPA(gpa);
7. System.out.println(s1.firstName + " " + s1.lastName + " GPA: "+
8. s1.gpa);
9. }
10. public static void findGPA(double averageGPA, double semester1,
11. double semester2, double semester3, double semester4){
12. averageGPA = semester1 + semester2 + semester3 + semester4/4.0;
13. }
14. }
15. class Student {
16. String firstName;
17. String lastName;
18. double gpa = 0.0;
19. public Student (String fName, String lName) {
20. firstName = fName;
21. lastName = lName;
22. }
23. public void setGPA(double gpa) {
24. this.gpa = gpa;
25. }
26. }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
257
a) 0
b) 15
c) 20
d) Nothing, there is a compile time error
a) 0
b) 15
c) 20
d) Nothing, there is a compile time error
3) What is the value of the variable start after executing line 15?
a) 15
b) 14
c) 16
d) 0
4) What is the value of the variable total after executing line 16?
a) 10.0
b) 10.60
c) 0.60
d) 0
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
258
a. Mike Shepard
b. Sue Shepard
c. Null
a. Mike Shepard
b. Sue Shepard
c. Null
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
259
#A Add an assignment to the value returned from the method with the gpa
#B Change the method return type to double and remove the gpa parameter value
#C Add a return statement to return the gpa
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
260
20
Garbage Collection
• Understand how Java allocates memory for objects using the Heap
• Understand how Garbage Collection (GC) works in Java
Even though memory has become less expensive and more compact, there are still physical
limits to how much memory an application is allocated during runtime. Early versions of Java
required the programmer to manually search for unused objects and remove them to
recapture this space. In this lesson, I will explain how this process is now automated and why
it is important.
Consider This
Have you ever been in the middle of downloading a movie to your phone just to find out that you didn’t have enough
space? Your phone has some automatic deletion, but there are times when you need to manually delete content. If
every app that you use during one day on your phone remained running, it would not take long for the memory to get
used up and the battery to die.
In Java, there is a process to remove unused data called garbage collection. This process frees up memory and allows
new objects to be added to the heap.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
261
objects start out in the young generation, specifically in eden. Figure 20.1 shows a picture of
a sample heap in Java.
So, the question is how does the JVM know when an object is eligible for deletion. In the next
section, I will explain how the garbage collection process works.
a. Eden
b. Survivor space
c. Tenured
The permanent generation storage area is used for metadata that is required by the JVM. It
also contains the Java SE library classes and methods. When this area fills up it automatically
triggers a major garbage collection. This process reviews all objects in the old generation and
identifies any objects eligible for GC.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
262
In this simple example, immediately after the object is created and then used in a print
statement, the reference variable is set to null. This tells the JVM that the storage space on
the heap that holds the values: [Ana, Gomez, 23] can be marked as available again. The
values are not actually erased, but the memory is released for future use by other objects and
the reference variable no longer has the memory address for this object. As a matter of fact, if
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
263
the program tries to print the information after setting the variable to null, it will generate an
exception message: java.lang.NullPointerException. Figure 20.2 shows this process
graphically.
Figure 20.2 is a diagram of the heap in Java before and after setting an object to null
Notice in the diagram that the information for Ana Gomez is still in the heap after the variable
s1 has been set to null but there is no way to access the information. Once the variable
reference is set to null, the object is available for garbage collection and the space can be
reassigned.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
264
In this example, the first reference variable, s1, points to the student: [Ana, Gomez, 23] and
the second variable, s2, points to the second student: [Joe, Wise, 19]. Next, the program
reassigns the reference variable s2 to the value of the reference variable s1. Now, both
variables have the same memory address pointing to the values for the student: [Ana, Gomez,
23] and the information for Joe Wise is no longer accessible. Diagram 20.3 shows a visual
representation of this example.
Figure 20.3 is a diagram of the heap in Java before and after assigning an object reference variable to another
object reference
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
265
In this diagram, the top portion shows how two reference variables are created and they each
point to unique student objects with a different memory address for their respective student
information. When the statement s2 = s1 is executed, the second student reference variable
is now pointing to the first student reference object. So, s1 and s2 both contain the same
object reference address, therefore the second object is unreachable. Now the second object
is eligible for garbage collection. In the bottom portion of the diagram, we can see that the
second object no longer has any reference variables, so it is essentially removed.
In this example, the code creates two students in the main method. Then it calls the method
createNewStudent(), to create a third student. The third student object is created inside this
method, so when the method ends, the program does not have a reference to that object any
more. So, the object and the reference variable are eligible for GC. In this example, lines 7 &
8 does not compile since the new student object (student3) is no longer visible. The error
message says error: cannot find symbol student3.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
266
Figure 20.4 Shows how objects created in a method are eligible for GC after the method executes
In the figure 20.4, the bottom section is used to show the object that are created inside the
createNewStudent method. The method creates a third object to hold information about a
third student. Now, the variable student3 has the memory address for the student: [Isabella,
McKnight, 19].
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
267
In this code example, a new reference variable is created for an Address object called test. In
the main method, two more Address reference variables are created (lines 5 and 6). When
they are created, they contain an instance of the Address variable test since it is defined as
part of the Address class. Next, the test variable for each object is set to the other variable
reference value. Now, test1.test references to test2, and test2.test references test1. Finally,
lines 9 and 10 are used to set test1 and test2 to null. So, at this point, the two test objects
point to each other and there is no other reference variable to these objects. They are now
considered an island of isolation and eligible for GC. Figure 20.5 shows a graphical
representation of how an island of isolation can be created.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
268
It is important to note that all application threads are stopped during the minor garbage
collection process. This is often referred to as a Stop the World Event.
Quick Check 20-2: Use this code listing to answer the questions below:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
269
1. When is the student object that contains this information [Evy, Knapp, 18] eligible for GC?
a. Line 3
b. Line 4
c. Line 5
d. After program execution is complete
a. Line 3
b. Line 4
c. Line 5
d. After program execution is complete
a. Line 5
b. Line 7
c. Line 9
d. After program execution is complete
20.3 Summary
In this lesson, you learned:
This lesson reviewed how the JVM manages allocating space on heap when new objects are
created and then aged through the heap. All new objects start in the space labelled the young
generation and then move to the old generation if they are still active.
This lesson also identified the processes that are used to make the objects eligible for GC.
These include: nullifying an object, reassigning a reference variable, creating objects inside a
method, and creating an island of isolation where the objects are no longer reachable.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
270
a. Eden
b. Survivor space
c. Tenured
Quick Check 20-2 Solution: Use this code listing to answer the questions below:
1. When is the student object that contains this information [Evy, Knapp, 18] eligible for GC?
a. Line 3
b. Line 4
c. Line 5
d. After program execution is complete
a. Line 3
b. Line 4
c. Line 5
d. After program execution is complete
a. Line 5
b. Line 7
c. Line 9
d. After program execution is complete
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
271
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
272
21
Java Collections: List
This lesson introduces the topic of collections in Java, and the types of collections available.
After the overview, this lesson concentrates on the List interface. It includes the benefits of
using and the difference between the types of Lists. A collection is an object that represents
another group of objects. Often you will hear the term, a collections framework, this is an
architecture for representing and manipulating collections.
Consider This
A convenience store has a rack full of candy items. The rack is close to the register where the customers check out, so
the items are frequently removed from the rack and need to be restocked. To keep a list of the items on the rack, we
must consider a few key questions, such as can there be duplicate items, how often are items added or removed? In
this lesson, you will see that this type of list fits the criteria for a LinkedList.
• List – contains an ordered set of objects that can have duplicates (note: ordered does
not necessarily mean sorted), for example: [Jeep, Chevy, Ford, Jeep]
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
273
• Set – a collection of objects that does NOT contain any duplicates, for example: [Jeep
Chevy, Ford]
• Queue – a collection that uses a specific order for adding and removing elements, such
as first in, first out (FIFO), for example: [customer3, customer2, customer1]
• Map – this type uses a map to associate unique keys to a value in the collection,
therefore it does NOT allow duplicate keys, for example: (zipCode, cityName), (17084,
"Reedsville")
Each interface in the framework has one or more classes that implement the interface. Figure
21.1 shows a diagram of the Java Collection Framework where you can see the interfaces and
the classes that implement the interfaces. In this diagram, I have only listed a subset of all
the available classes and interfaces, but these are the most widely used. In the next few
lessons, I will review the four major interfaces: List, Set, Queue, and Map.
In the diagram, the rectangles represent the interfaces that are part of the Collection
framework including the Map interface. The Map interface does not directly extend the
Collection framework, but it is still considered part of the overall Collections framework. List,
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
274
Set and Queue all extend the Collection interface, which means they inherit the methods
defined in the Collection interface.
Remember, we can’t instantiate an object as an interface, for example: List l = new List<>(),
so each interface has classes that implement the respective interfaces. For example, ArrayList
implements the List interface, so any object defined as an ArrayList automatically has access
to the methods defined in the List interface: List l = new ArrayList<>(). Take a moment to
familiarize yourself with the various interfaces and classes in the framework. Here are two
useful links to the JavaDoc for the Collection Interface:
Java 8: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html
Java 11:
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html
a. List
b. Set
c. Queue
d. Map
a. List
b. Vector
c. HashSet
d. LinkedList
a. Map
b. SortedMap
c. HashMap
d. LinkedHashMap
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
275
Figure 21.2 A decision tree for choosing the right Collection in Java
Follow each question by answering yes/no until you reach the appropriate collection type. For
example, if we have a list of customers that have ordered items online, we can follow the
decision tree to determine which type of collection to use to hold the list of customer orders.
This list does not contain a key/value pair, so next we check to see if duplicates are allowed.
Since a customer may return and purchase more items, duplicates are allowed. Next, do we
need to access elements at a specific index, for this example, we choose the yes path. We
want to fill the orders on a first come, first serve basis, so we continue to the question about a
significant amount of data. Again, we might have a high volume of sales and new customers
are frequently added and removed once their order is filled, so we end up with a LinkedList.
Here is a sample code snippet using a LinkedList:
List<String> customerList = new LinkedList<String>();
These are not strict rules that have to be followed, but this helps to choose the most efficient
collection type for your application.
1. You have a collection of elements that need to be sorted in their natural order, and each element has a
unique string associated with its value, which is best suited for your needs?
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
276
a. ArrayList
b. HashMap
c. HashSet
d. TreeMap
Table 21.1 Shows each type of List and a brief description of their differences
ArrayList A list of elements that can grow and shrink as needed. These elements can be added, removed, or
modified using an index value. When elements are removed, the list must adjust all remaining
elements to fill the open spot. When the list is full, it automatically doubles the size and copies all
current elements to the new ArrayList.
LinkedList One difference between a LinkedList and an ArrayList is the way the elements are added to the list.
A LinkedList maintains its insertion order. It is more efficient when adding/removing elements
because it does not need to re-adjust the list.
Vector A Vector is synchronized where the ArrayList and LinkedList are not. When the list is full, it
automatically doubles the size and copies all current elements to the new Vector.
We can create any of these list types with a variable declared as a List reference type since it
is the super class for each of these subclasses. Here is a code snippet that uses an ArrayList to
hold the color values of the rainbow:
Code Listing 21.1 sample code to create a list of string objects for the colors of the
rainbow
1. List<String> rainbow = new ArrayList<>();
2. rainbow.add("red");
3. rainbow.add("orange");
4. rainbow.add("yellow");
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
277
5. rainbow.add("green");
6. rainbow.add("blue");
7. rainbow.add("indigo");
8. rainbow.add("violet");
Lesson 6 has more detailed information on how to create and use ArrayLists since it is a
commonly used data structure for storing lists of data. An ArrayList is considered a Collection
since it implements the List interface.
NOTE: Unlike ArrayLists, arrays are not part of the Collections framework.
A LinkedList uses a doubly linked list to store the elements in the list. Let’s start by looking at
an example of a singly linked list that contains test scores for four students on a recent test:
In this example, each node in the list contains a value and a pointer. The pointer contains the
reference address to the next node in the list. If the value in the next node is NULL, then it is
at the end of the list. As you can see, this type of list only allows you to go in one direction.
You can start at the head of the list or if you have the reference address to an element in the
list, you can access that element and iterate over the remaining elements, but you can’t go
backwards.
The LinkedList data structure in Java works the same way but it allows you to go forward and
backward through a list of elements. That is why it is considered a doubly linked list. When
using a LinkedList, each element stores a reference location for the next and previous element
in the list. The first and last element are identified by looking at the reference value, the first
element has a null pointer for the previous element, and the last element has a null pointer for
the next element. There is also a reference value to the start of the list, referred to as the
head of the list. One important difference about a LinkedList is that it does NOT use index
values to reference objects. Here is a code snippet for creating a LinkedList and a diagram of
the list that gets created:
List<String> ingredients = new LinkedList<>();
ingredients.add("apples");
ingredients.add("pie crust");
ingredients.add("sugar");
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
278
Figure 21.4 This diagram represents a doubly linkedlist in Java for apple pie ingredients
The next list type is called a Vector. A Vector can grow and shrink as needed, and it can be
referenced using index values. The Vector Class is a carryover from older versions of Java. A
key difference is that vectors are synchronized in Java. This means that they are thread safe,
any method that uses a Vector will not allow access until the method returns control to the
calling. A Vector is similar to an ArrayList, but it is considered thread safe. If your program is
not using threads, this should not be a problem and you can use an ArrayList.
Thread
A thread in Java is the term used to describe the path followed when executing a program. All Java programs have at
least one thread, this is the main thread. The JVM creates the main thread when the program starts by finding the
method declaration for the main method. Remember, every Java program MUST have one and only one main method.
Java supports multi-threaded applications which is a powerful tool if your application needs to process large amounts of
data concurrently.
In this code, I start by creating a new Vector of Strings. Next, I added three furniture items
to the vector. Remember, vectors work very similar to an ArrayList, but they are
synchronized. So, each application thread can only access the elements in the vector when all
other threads have released the objects.
Consider a library. You can go to the library and check out a book. While you are reading it,
no one else can check it out. When you are done, you return it to the library and now the next
person can access the book. This is similar to the concept of synchronization in Java.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
279
Collection Interface. These methods are automatically inherited by each of these sub-
collections. Table 21.2 lists a subset of the methods that are included in the Collection
Interface.
Method Description
boolean contains(Object o) returns true if this collection contains the specified element
boolean containsAll(Collection<?> c) returns true if all of the elements are in the collection
boolean equals(Object o) compares the specified object with the collection for equality
int hashCode() returns the hash code value for this collection
Iterator<E> iterator() returns an iterator that can be used to traverse all elements
boolean remove(Object o) returns true if element is found and removed from collection
boolean removeAll(Collection<?> c) returns true if all elements are found and removed
Object[] toArray() returns an array that includes all elements from the collection
The methods listed in Table 21.2 are from the Collection Interface. In addition to this set of
methods, each of the interfaces that implement Collection also have additional methods. For
example, the List interface allows for adding an element to a certain index value: boolean
add(int index, E element).
Code Listing 21.2 Sample code to help demonstrate how to use List in Java
1. List<String> colors = new ArrayList<>();
2. List<Integer> grades = new LinkedList<>();
3. List<Character> alphabet = new Vector(26);
4.
5. List<String> rgb = new ArrayList<>();
6. rgb.add("red");
7. rgb.add("green");
8. rgb.add("blue");
9.
10. List<Integer> numbers = new LinkedList<>();
11. numbers.add(100);
12.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
280
For each of the common methods, Table 21.3 shows a sample code snippet for an ArrayList,
LinkedList and Vector. The examples use the code in Listing 21.2. For this example, each row
uses the list from the previous row as a starting point.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
281
boolean colors.retainAll(rgb); []
retainAll(Collection<?> c)* grades.retainAll(numbers); []
alphabet.retainAll(letters); [b]
alphabet.toArray();
* In the table above, I wanted to take a closer look at the retainAll method. This method is similar to the intersection of
two lists. So, only elements that occur in both lists are returned from this method.
The table starts with the ArrayList, LinkedList, and Vector from listing 21.2. To help
demonstrate the methods, I made the ArrayList a list of String objects, the LinkedList contains
Integer values, and the Vector contains Character values. The third column shows the result of
the list after each method statement is executed.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
282
21.5 Summary
In this lesson, you learned:
This lesson started by introducing the Collection framework in Java. The framework has
various collections that can be used to store, retrieve and manipulate data. Choosing the right
collection is important to ensure your application runs efficiently and securely. This lesson
reviewed the criteria that results in the creation of a List data structure. Next, the lesson
reviewed the process to create each type of list, including ArrayList, LinkedList, and Vector.
The next lesson continues the discussion of Collections and reviews the Set Interface and the
classes that extend Set.
Try this:.
Have you ever created a playlist of songs? How do you listen to the songs on the playlist? I’m
guessing that sometimes you listen to each song sequentially or even in reverse. You might
have a favorite song in the middle of the list that you listen to frequently. Looking at our
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
283
decision chart, follow the path to choose a list type and write the code for creating the list.
There are several possible options, so choose one and then create the list.
a. List
b. Set
c. Queue
d. Map
a. List
b. Vector
c. HashSet
d. LinkedList
a. Map
b. SortedMap
c. HashMap
d. LinkedHashMap
1. You have a collection of elements that need to be sorted in their natural order, and each element has a
unique string associated with its value, which is best suited for your needs?
a. ArrayList
b. HashMap
c. HashSet
d. TreeMap
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
284
2. import java.util.ArrayList;
3. import java.util.LinkedList;
4. import java.util.List;
5. import java.util.Vector;
6.
7. public class Lesson21_List {
8. public static void main(String[] args) {
9. List<String> dogs = new ArrayList<>();
10. dogs.add("Whippet");
11. dogs.add("Beagle");
12. dogs.add("Golden Retriever");
13. dogs.add(0,"Labrador Retriever");
14. System.out.println(dogs);
15.
16. List<String> movies = new LinkedList<>();
17. movies.add("Doctor Strange");
18. movies.add(1,"Avengers");
19. movies.add("Black Panther");
20. System.out.println(movies);
21. }
22. }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
285
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
286
22
Java Collections: Set
This lesson introduces the types of Set collections Java. It includes the benefits of using and
the difference between the types of Sets. A Set is an object that represents another group of
objects that does not allow for any duplicates.
Consider This
A local zoo is merging with another zoo and they want to create a brochure with the complete list of the types of
animals that will now be in the new zoo. For this program, then want to enter the types of animals from each zoo, but
they don’t want duplicates. They also want to have access to the animal names alphabetically to print on the brochure.
This scenario is perfect for using a TreeSet, since that does not allow for duplicates and it requires the items to be
sorted.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
287
Figure 22.1 Diagram of the Set portion of the Java Collection Framework
a. HashSet
b. Set
c. TreeSet
d. LinkedHashSet
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
288
Figure 22.2 A decision tree for choosing the right Collection in Java, notice the highlighted section for Set types
The highlighted portion of the decision tree indicates the questions used to choose a Set type.
Follow each question by answering yes/no until you reach the appropriate collection type. For
example, in our Consider This section, we start with the Set interface since there can be no
duplicates. Next, is the order important? In our example it is important since we want the
animals to be in alphabetical order. The last question is whether or not it needs to be sorted,
and we answered yes, so we would use a TreeSet.
These are not strict rules that have to be followed, but this helps to choose the most efficient
collection type for your application.
1. You want to store a collection of books (which can contain duplicates) and you want to have access to
print them out based on a position in the list, which is best suited for your needs?
a. ArrayList
b. HashMap
c. HashSet
d. TreeMap
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
289
Table 22.1 provides information about each of the Set classes: HashSet, LinkedHashSet, and
TreeSet. One common attribute to all Set collections is that they do not allow for duplicate
values.
Table 22.1 Shows each type of Set and a brief description of their differences
LinkedHashSet Combines a hash set with a linked list, elements are stored using a hash code, and then added
to a linked list
By using a linked list to store the elements, it maintains the insertion order which makes it
different from the HashSet
It allows for null values
If you have a list of elements and you only want to identify the unique items in the list, you
can add the list collection to any of the Set types listed above and only one copy of each
unique element will be added. Code Listing 22.1 shows an example of using a Set to create a
unique list of elements.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
290
8.
9. public class Lesson22_Listing1 {
10. public static void main(String[] args) {
11. List customers = new ArrayList();
12. customers.add("customer1");
13. customers.add("customer2");
14. customers.add("customer3");
15. customers.add("customer1");
16. Set uniqueCustomers = new HashSet(); //#A
17. uniqueCustomers.addAll(customers); //#B
18. System.out.println(customers.toString());
19. System.out.println(Arrays.toString(uniqueCustomers.toArray()));
20. }
21. }
In this example, I have started by creating a list of four customers, including one duplicate
customer. Then I created a HashSet and added the list of customers to that set. This allows
the code to automatically remove any duplicates. The output from this code snippet shows
the original list and then prints the elements in the HashSet:
[customer1, customer2, customer3, customer1]
[customer2, customer3, customer1]
As you can see, the second line of output only contains one element for customer1. It is also
noticeable that the HashSet does not retain the insertion order of the elements. The next
three sections take a closer look at each type of Set.
22.3.1 HashSet
We can create any of these set types with a variable declared as a Set reference type since it
is the super class for each of these subclasses. Listing 22.2 creates a Set reference variable,
numbers, that is instantiated as a HashSet. Next, the for loop adds the numbers 12 through
102. The output from this code might look like this: [16, 64, 1, 49, 81, 4, 36, 100, 9, 25].
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
291
15. System.out.println(Arrays.toString(numbers.toArray()));
16. }
17. }
Figure 22.3 shows how the set might look for this example:
Figure 22.3 shows an example of a HashSet containing the values from the numbers set in Listing 22.2
The HashSet makes searching for an element quick, line 14 searches the collection for a
specific value, in this case 100, which returns true.
22.3.2 LinkedHashSet
The difference between a LinkedHashSet and a HashSet is that it allows us to store the
elements in the order they are added to the set. The LinkedHashSet data structure in Java
works similar to the LinkedList from Lesson 21. It allows you to go forward and backward
through a set of elements. Here is a code snippet that uses a LinkedHashSet to store the
same values from the HashSet example: 12 through 102.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
292
Code Listing 22.3 sample code to create a set of values using a LinkedHashSet
1. package lesson22;
2.
3. import java.util.Arrays;
4. import java.util.LinkedHashSet;
5. import java.util.Set;
6.
7. public class Lesson22_Listing3 {
8.
9. public static void main(String[] args) {
10. Set numbers = new LinkedHashSet(); //#A
11. for (int i = 1; i <= 10; i++) {
12. numbers.add(i * i);
13.
14. System.out.println(Arrays.toString(numbers.toArray())); //#B
15. }
16. }
The linked list shown in figure 22.4 shows how the elements are inserted into the set based
on insertion order. Since the set is a linked set, it follows the same rules as the LinkedList,
creating a double linked set of elements.
Figure 22.4 This figure shows the LinkedHashSet created by the code in Listing 22.3
22.3.3 TreeSet
Code listing 22.4 uses a TreeSet to hold a list of animals at the zoo:
Code Listing 22.4 sample code to create a set of values in sorted order using a TreeSet
1. package lesson22;
2.
3. import java.util.Arrays;
4. import java.util.Set;
5. import java.util.TreeSet;
6.
7. public class Lesson22_Listing4 {
8. public static void main(String[] args){
9. Set animals = new TreeSet(); //#A
10. animals.add("Lion"); //#B
11. animals.add("Bear"); //#B
12. animals.add("Tiger"); //#B
13. System.out.println(Arrays.toString(animals.toArray()));
14. }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
293
15. }
Listing 22.4 creates a Set reference variable, animals, that is instantiated as a TreeSet. Three
animals are added to the set. Since the TreeSet stores the elements in sorted order, the
output is: [Bear, Lion, Tiger]. The TreeSet collection can be created using the Set interface,
the SortedSet interface and the class name TreeSet. Listing 22.5 is similar to the code listing
from 22.4, but this time there are two differences. On line 9 I have changed the set type from
Set to SortedSet and added an additional statement on line 13.
Code Listing 22.5 sample code to create a set of values in sorted order using a TreeSet
1. package lesson22;
2.
3. import java.util.Arrays;
4. import java.util.SortedSet;
5. import java.util.TreeSet;
6.
7. public class Lesson22_Listing5 {
8. public static void main(String[] args){
9. SortedSet animals = new TreeSet();
10. animals.add("Lion");
11. animals.add("Bear");
12. animals.add("Tiger");
13. animals.add("Bear"); //#A
14. System.out.println(Arrays.toString(animals.toArray()));
15. }
16. }
#A Add the element “Bear” twice, but the output shows that it is only stored once in the set
In Listing 22.5, since the animals set does not allow duplicates, the statement on line 13 to
add Bear to the set a second time is ignored and this code produces the exact same result:
[Bear, Lion, Tiger]. When adding a duplicate element, it does not throw an exception error,
instead it returns true if the element is added and false if the element already exists and was
not added a second time.
Code Listing 22.6 sample code for the quick check 22-3
1. package lesson22;
2.
3. import java.util.Arrays;
4. import java.util.Set;
5. import java.util.HashSet;
6. import java.util.LinkedHashSet;
7. import java.util.TreeSet;
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
294
8.
9. public class Lesson22_Listing6 {
10. public static void main(String[] args){
11. Set set1 = new HashSet();
12. Set set2 = new LinkedHashSet();
13. Set set3 = new TreeSet();
14. for(int i = 1; i <= 10; i++) {
15. set1.add(i*i);
16. set2.add(i*i);
17. set3.add(i*i);
18. }
19. set1.add(51);
20. set2.add(2);
21. set3.add(47);
22. }
23. }
System.out.println(Arrays.toString(set1.toArray()));
System.out.println(Arrays.toString(set2.toArray()));
System.out.println(Arrays.toString(set3.toArray()));
4. Your application is designed to process a series of invoices from various customers. A single customer
might have more than one invoice with a unique invoice number. You need to create a mailing list of
the customers contained in the list of invoices. Which type of Set collection should you use to create
the set of unique customer names in alphabetical order?
a. HashSet
b. LinkedHashSet
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
295
c. TreeSet
d. None of the above
In Table 22.2, I wanted to take a closer look at the retainAll method. This method is similar to
the intersection of two sets. So, only elements that occur in both sets are returned from this
method.
Method Description
boolean contains(Object o) returns true if this collection contains the specified element
boolean containsAll(Collection<?> c) returns true if all of the elements are in the collection
boolean equals(Object o) compares the specified object with the collection for equality
int hashCode() returns the hash code value for this collection
Iterator<E> iterator() returns an iterator that can be used to traverse all elements
boolean remove(Object o) returns true if element is found and removed from collection
boolean removeAll(Collection<?> c) returns true if all elements are found and removed
boolean retainAll(Collection<?> c) keeps only the elements in the specified collection (*see below)
Object[] toArray() returns an array that includes all elements from the collection
The methods listed in Table 22.2 are from the Collection Interface. In addition to these
methods, each of the interfaces that implement Collection also have additional methods. For
example, the SortedSet interface contains additional methods, for example: subset, headset
and tailSet, first, and last. You can find all the methods for each class in the Oracle JavaDocs:
https://docs.oracle.com/en/java/javase
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
296
Table 22.3 A subset of some unique methods for the SortedSet Interface
Method Description
SortedSet<E> subSet(E fromElement, E toElement) returns all elements from the first element (inclusive) up to the
toElement (not inclusive)
SortedSet<E> headSet(E toElement) returns all elements up to the toElement (not inclusive)
SortedSet<E> tailSet(E fromElement) returns all elements after to fromElement to the end (inclusive)
To demonstrate how to use these methods, I have created a code example, shown here in
Listing 22.7, that demonstrates how to use these additional methods for a SortedSet.
The output from code listing 22.7 is shown below in figure 22.5. Make sure you look closely at
the output, it might be different than what you expect.
Figure 22.5 Snapshot of the output from executing the code snippet in Listing 22.7
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
297
#A Use the first method from the SortedSet to print the first element from the set
#B Print the last element from the set
#C Print a subset of the rainbow elements from Indigo, not including Yellow
#D Print the front part of the set up to the element “Blue” but not including Blue
#E Print the last part of the set from Yellow to the end
At first glance the output looks incorrect but remember that a TreeSet adds the elements in
sorted order to the set, it does not maintain the insertion order. So, in this example, the first
element is not Red, instead it is the first color alphabetically which is Blue.
a. set2.add(set1) ;
b. set2.addAll(set1) ;
c. set2.contains(set1) ;
d. set1.addAll(set2);
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
298
a. true
b. false
c. 0
d. null pointer exception
a. set3.add("four");
b. set3.addAll("four");
c. set3.put("four");
d. null pointer exception
a. 3
b. 0
c. 4
d. null pointer exception
This lesson started by reviewing the decision tree to identify scenarios that are best suited by
a Set collection. All Set collections ignore duplicate elements. Each set type is unique, the
HashSet stores elements using a hash code and does not maintain insertion order. The
LinkedHashSet is similar to the HashSet, but it maintains the insertion order. Finally, the
TreeSet is unique since the elements are stored in sorted order and it provides some unique
methods based on the fact that the elements are sorted.
The next lesson continues the discussion of Collections and reviews the Queue Interface and
the classes that extend Queue.
22.5 Summary
In this lesson, you learned:
• How to identify situations that work best by using a Set to store the elements
• To create sets using the HashSet, LinkedHashSet, and TreeSet classes and add
elements to each
• How to apply methods available for the Set collection in a Java program
Try this:
You need to write a program that maintains the insertion order, but also automatically
eliminates any duplicates. Write a sample program that stores a list of items, including some
duplicates, and then print the set of elements.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
299
Answer Section:
Quick Check 22-1 Solution:
1. Which class is best suited to store a sorted list of elements with no duplicates:
a. HashSet
b. Set
c. TreeSet
d. LinkedHashSet
1. You want to store a collection of books (which can contain duplicates) and you want to have access to
print them out based on a position in the list, which is best suited for your needs?
a. ArrayList
b. HashMap
c. HashSet
d. TreeMap
Code Listing 22.5 sample code for the quick check 22-3
1. package lesson22;
2.
3. import java.util.Arrays;
4. import java.util.Set;
5. import java.util.HashSet;
6. import java.util.LinkedHashSet;
7. import java.util.TreeSet;
8.
9. public class Lesson22_Listing5 {
10. public static void main(String[] args){
11. Set set1 = new HashSet();
12. Set set2 = new LinkedHashSet();
13. Set set3 = new TreeSet();
14. for(int i = 1; i <= 10; i++) {
15. set1.add(i*i);
16. set2.add(i*i);
17. set3.add(i*i);
18. }
19. set1.add(51);
20. set2.add(51);
21. set3.add(51);
22. }
23. }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
300
4. Your application is designed to process a series of invoices from various customers. A single customer
might have more than one invoice with a unique invoice number. You need to create a mailing list of
the customers contained in the list of invoices. Which type of Set collection should you use to create
the set of unique customer names in alphabetical order?
a. HashSet
b. LinkedHashSet
c. TreeSet
d. None of the above
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
301
a. set2.add(set1) ;
b. set2.addAll(set1) ;
c. set2.contains(set1) ;
d. set2.containsAll(set1) ;
a. true
b. false
c. 0
d. null pointer exception
a. set3.add("four");
b. set3.addAll("four");
c. set3.put("four");
d. null pointer exception
a. 3
b. 0
c. 4
d. null pointer exception
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java
302
11. names.add("Liam");
12. names.add("Aurora");
13. names.add("Owen");
14. names.add("Samuel");
15. names.add("Lily");
16. names.add("Charlotte");
17. names.add("Jasper");
18. names.add("Aurora"); //B
19. names.add("Owen"); //B
20. System.out.println(Arrays.toString(names.toArray()));
21. }
22. }
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
https://forums.manning.com/forums/get-programming-with-java