Java SE 7 Programming Practice

Download as pdf or txt
Download as pdf or txt
You are on page 1of 214
At a glance
Powered by AI
The document discusses installing and configuring Java SE 7 and NetBeans to work together. It also provides practices and exercises for learning Java.

The document is a student guide that provides lessons and practices for learning Java SE 7.

The document covers topics like Java syntax, classes, databases, localization, and more based on the table of contents.

Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Java SE 7 Programming r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis Guide
e t his
x a nd us
Activity

a l e e to
t e ( ns
a
tr le li c e
I s
n d ra erab
x a n s f
e
Al n-tra
no

D67238GC20
Edition 2.0
November 2011
D74998
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Disclaimer

This document contains proprietary information and is protected by copyright and other intellectual property laws. You may copy and
print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way.
Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization
of Oracle.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

The information contained in this document is subject to change without notice. If you find any problems in the document, please
report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.

Restricted Rights Notice

If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United
States Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS


The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or disclose these training materials are restricted
by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.

Trademark Notice s a
) h a
owners.
c o m
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
e ฺ
ฺ i d
r a cle t Gu
Authors
@ o e n
t e tu d
Michael Williams, Tom McGinn, Matt Heimer
t r a S
Technical Contributors and Reviewers dra
ฺis this
n u s e
a
Lee Klement, Steve Watts, Brian Earl,xVasily Strelnikov
to Goetz,, Andy Smith, Nancy K.A.N, Chris
Lamb, Todd Lowry, Ionut Radu (, a leDarcy,seBrian
Joe Alan Bateman, David Holmes
t r a te licen
r a Is rusing:
This book wasdpublished a bleOracle Tutor
e x an nsfe
Al n-tra
no
Table of Contents
Practices for Lesson 1 .............................................................................................................................. 1-1
Practices for Lesson 1: Overview............................................................................................................. 1-3
Practice 1-1: Verifying Software Installation ............................................................................................. 1-4
Practice 1-2: Software Installation............................................................................................................ 1-6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Practice 1-3: Configuring NetBeans 7.0.1 to Utilize JDK 7 ........................................................................ 1-8


Practices for Lesson 2: Java Syntax and Class Review .......................................................................... 2-1
Practices for Lesson 2: Overview............................................................................................................. 2-3
Practice 2-1: Summary Level: Creating Java Classes............................................................................... 2-4
Practice 2-1: Detailed Level: Creating Java Classes ................................................................................. 2-6
Practices for Lesson 3: Encapsulation and Subclassing ........................................................................ 3-1
Practices for Lesson 3: Overview............................................................................................................. 3-3
Practice 3-1: Summary Level: Creating Subclasses.................................................................................. 3-4
Practice 3-1: Detailed Level: Creating Subclasses.................................................................................... 3-7
(Optional) Practice 3-2: Adding a Staff to a Manager ................................................................................ 3-12 s a
Practices for Lesson 4: Java Class Design .............................................................................................. ) h 4-1 a
c m
o ideฺ4-3
Practices for Lesson 4.............................................................................................................................

r a cle t Gu 4-4
Practice 4-1: Summary Level: Overriding Methods and Applying Polymorphism ........................................
Practice 4-1: Detailed Level: Overriding Methods and Applying Polymorphism
@ o n
..........................................
e 4-7

r a t e Stud
Practices for Lesson 5: Advanced Class Design ..................................................................................... 5-1
t is
ฺis..................................................................
Practices for Lesson 5: Overview............................................................................................................. 5-3
Practice 5-1: Summary Level: Applying the Abstract Keyword r a t h 5-4
Practice 5-1: Detailed Level: Applying the Abstract a n se
dKeywordu.................................................................... 5-8
e x
l Singleton t o
Practice 5-2: Summary Level: Applying
( athethe n s eDesign
Design Pattern ....................................................... 5-13

r e
t Enumerations
Practice 5-2: Detailed Level: Applying
aJava i ce ....................................................................................
Singleton Pattern ......................................................... 5-15
(Optional) Practice 5-3:s
I t
Using
l e l 5-17

n dra5-4:
(Optional) Practice
(Optional)aSolution f e rab Nested
Recognizing Classes ............................................................................... 5-19

l e xfor Lesson a n s
5-4: Recognizing Nested Classes ............................................................................... 5-20

A
Practices
n - t r 6: Inheritance with Java Interfaces ........................................................................ 6-1

nofor Lesson 6: Overview............................................................................................................. 6-3


Practices
Practice 6-1: Summary Level: Implementing an Interface ......................................................................... 6-4
Practice 6-1: Detailed Level: Implementing an Interface ........................................................................... 6-7
Practice 6-2: Summary Level: Applying the DAO Pattern .......................................................................... 6-12
Practice 6-2: Detailed Level: Applying the DAO Pattern ............................................................................ 6-14
(Optional) Practice 6-3: Implementing Composition .................................................................................. 6-19
Practices for Lesson 7: Generics and Collections ................................................................................... 7-1
Practices for Lesson 7: Overview............................................................................................................. 7-3
Practice 7-1: Summary Level: Counting Part Numbers by Using HashMaps.............................................. 7-4
Practice 7-1: Detailed Level: Counting Part Numbers by Using HashMaps ................................................ 7-6
Practice 7-2: Summary Level: Matching Parentheses by Using a Deque ................................................... 7-8
Practice 7-2: Detailed Level: Matching Parentheses by Using a Deque ..................................................... 7-9
Practice 7-3: Summary Level: Counting Inventory and Sorting by Using Comparators ............................... 7-11
Practice 7-3: Detailed Level: Counting Inventory and Sorting by Using Comparators ................................. 7-14

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Java SE 7 Programming Table of Contents


i
Practices for Lesson 8: String Processing............................................................................................... 8-1
Practices for Lesson 8: Overview............................................................................................................. 8-3
Practice 8-1: Summary Level: Parsing Text with split() ............................................................................. 8-4
Practice 8-1: Detailed Level: Parsing Text with split() ............................................................................... 8-6
Practice 8-2: Summary Level: Creating a Regular Expression Search Program......................................... 8-9
Practice 8-2: Detailed Level: Creating a Regular Expression Search Program ........................................... 8-10
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Practice 8-3: Summary Level: Transforming HTML by Using Regular Expressions .................................... 8-12
Practice 8-3: Detailed Level: Transforming HTML by Using Regular Expressions ...................................... 8-14
Practices for Lesson 9: Exceptions and Assertions ................................................................................ 9-1
Practices for Lesson 9: Overview............................................................................................................. 9-3
Practice 9-1: Summary Level: Catching Exceptions.................................................................................. 9-4
Practice 9-1: Detailed Level: Catching Exceptions .................................................................................... 9-7
Practice 9-2: Summary Level: Extending Exception.................................................................................. 9-10
Practice 9-2: Detailed Level: Extending Exception .................................................................................... 9-14
Practices for Lesson 10: Java I/O Fundamentals ..................................................................................... 10-1
Practices for Lesson 10: Overview ........................................................................................................... 10-3
s a
Practice 10-1: Summary Level: Writing a Simple Console I/O Application.................................................. 10-4
)h a
m
o ideฺ
Practice 10-1: Detailed Level: Writing a Simple Console I/O Application.................................................... 10-6
c

cle t Gu
Practice 10-2: Summary Level: Serializing and Deserializing a ShoppingCart ........................................... 10-9
r a
Practice 10-2: Detailed Level: Serializing and Deserializing a ShoppingCart.............................................. 10-12
o n
@ d e
Practices for Lesson 11: Java File I/O (NIO.2) ..........................................................................................
e u 11-1
a t S t
tr...............................................................
Practices for Lesson 11: Overview ........................................................................................................... 11-3
ฺ i s t h i s
Practice 11-1: Summary Level: Writing a File Merge Application
Practice 11-1: Detail Level: Writing a File Merge n d ra .....................................................................
Application s e
11-4
11-7
Practice 11-2: Summary Level: RecursiveeCopy x t o u
a....................................................................................... 11-11
( a
Practice 11-2: Detailed Level: Recursive
lCopy .........................................................................................
s e
a t e c e nPathMatcher to Recursively Delete ................................. 11-13
I
(Optional) Practice 11-3:s tr le liUsing PathMatcher to Recursively Delete ................................... 11-18
(Optional) Practice 11-3: Summary Level:
Detailed Level:
Using 11-16

Practices for n d
Lesson f e rab ......................................................................................................... 12-1
ra12: Threading
l e xafor Lesson
Practices
r a n s
12: Overview ........................................................................................................... 12-3
A 12-1:
Practice
o n -tSummary Level: Synchronizing Access to Shared Data...................................................... 12-4
n 12-1: Detailed Level: Synchronizing Access to Shared Data........................................................ 12-7
Practice
Practice 12-2: Summary Level: Implementing a Multithreaded Program .................................................... 12-11
Practice 12-2: Detailed Level: Implementing a Multithreaded Program ...................................................... 12-13
Practices for Lesson 13: Concurrency ..................................................................................................... 13-1
Practices for Lesson 13: Overview ........................................................................................................... 13-3
(Optional) Practice 13-1: Using the java.util.concurrent Package .............................................................. 13-4
(Optional) Practice 13-2: Using the Fork-Join Framework ......................................................................... 13-6
Practices for Lesson 14: Building Database Applications with JDBC ..................................................... 14-1
Practices for Lesson 14: Overview ........................................................................................................... 14-3
Practice 14-1: Summary Level: Working with the Derby Database and JDBC............................................ 14-4
Practice 14-1: Detailed Level: Working with the Derby Database and JDBC.............................................. 14-6
Practice 14-2: Summary Level: Using the Data Access Object Pattern...................................................... 14-8
Practice 14-2: Detailed Level: Using the Data Access Object Pattern........................................................ 14-11

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Java SE 7 Programming Table of Contents


ii
Practices for Lesson 15: Localization ...................................................................................................... 15-1
Practices for Lesson 15: Overview ........................................................................................................... 15-3
Practice 15-1: Summary Level: Creating a Localized Date Application ...................................................... 15-4
Practice 15-1: Detailed Level: Creating a Localized Date Application ........................................................ 15-6
Practice 15-2: Summary Level: Localizing a JDBC Application (Optional).................................................. 15-9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Java SE 7 Programming Table of Contents


iii
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G1u
Lesson
@ o e n
t e tu d
t
Chapter r a
1 S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1


Chapter 1 - Page 1
Practices for Lesson 1: Overview

Practices Overview
These practices cover configuring a development environment for Java SE 7. These practices
should not be performed unless directed to do so by your instructor.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1


Chapter 1 - Page 2
Practice 1-1: Verifying Software Installation

Overview
In this practice, you will verify the installation of the necessary software to perform Java 7
software development. If verification fails, you will proceed with the remaining practices.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
Your instructor has instructed you to perform these steps.

Summary
You have been given a computer system that will be used for Java SE 7 software development.
You must validate that the Java 7 SE Development Kit is installed, the NetBeans 7.0.1 IDE is
installed, and the NetBeans IDE is correctly configured to use JDK 7.

Tasks
1. Open a command or terminal window. s a
Note: If you are using Windows, you can open a command window by performing the)h a
following steps: c m
o ideฺ

a. Click the Start button.
r a cle t Gu
b. Click Run.
@ o e n
t e tu d
t r a
c. Type cmd in the Run dialog box and click the OK button. S
2. ฺis this
Execute the java -version command. This verifies that a JRE is installed; this does not
r a
verify that the JDK is installed.
a n d use
l e x to
a. Verify that the output of the java -version command matches the following
( a ns e
example output. For 64-bit machines, the output should be:
a t e c e
I
java version s tr "1.7.0"
l e li
d
Java(TM)
n f ab Environment (build 1.7.0-b147)
ra SEerRuntime
e a HotSpot(TM)
xJava n s 64-Bit Server VM (build 21.0-b17, mixed mode)
l
A For r a
t machines, the output should be:
-32-bit
o n
n java version "1.7.0"
Java(TM) SE Runtime Environment (build 1.7.0-b147)
Java HotSpot(TM) Client VM (build 21.0-b17, mixed mode, sharing)
b. If a different version number or an error message is displayed, you may have one of
the following possible problems:
 The JRE/JDK is not installed.
 The java command is not in your path.
 The wrong JRE/JDK version is installed.
 Multiple JREs/JDKs are installed.
Note: To exclude an incorrect PATH environment variable as the reason for an
incorrect or unrecognized Java version, you may attempt to locate the path to your JDK
and execute java -version by using a fully qualified path. For example:
"C:\Program Files\Java\jdk1.7.0\bin\java.exe" -version
3. Execute the javac -version command. This verifies that a JDK is installed.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1


Chapter 1 - Page 3
a. Verify that the output of the javac -version command matches the following
example output:
javac 1.7.0
b. If a different version number or an error message is displayed, you may have one of
the following possible problems:
 The JDK is not installed.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

 The javac command is not in your path.


 The wrong JDK version is installed.
 Multiple JDKs are installed.
Note: It is very common that the directory containing javac is not listed in your PATH
environment variable. You do not need to modify the PATH for most IDEs to function;
instead, locate the path to your JDK and execute javac -version by using a fully
qualified path to verify the presence and version of the JDK. For example:
"C:\Program Files\Java\jdk1.7.0\bin\javac.exe" -version
s a
4. Start the NetBeans IDE and verify the version number of the JDK used by the IDE.
)h a
c m
a. The installation of NetBeans places a menu in your Start menu. Locate the NetBeans
o ideฺ
IDE 7.0.1 shortcut within the Start menu and click it. ฺ
b. Within NetBeans, click the Help menu, and then click About. r a cle t Gu
@ o e n
t e tu d
c. The About dialog box displays both the NetBeans and JDK version numbers that are
being used. For 64-bit machines, you should see: t r a S
r a is (Build
ฺ7.0.1
e t his 201107282000)
nd 64-Bit
Product Version: NetBeans IDE
Java: 1.7.0; Java HotSpot(TM) x a t o us Server VM 21.0-b17
l e
For 32-bit machines, you
t e ( ashould
e n se
see:
Product Version:
I s tra leNetBeans
lic IDE 7.0.1 (Build 201107282000)
Java:ra
d 1.7.0; Java
r a b HotSpot(TM) Client VM 21.0-b17
x an Even
Note: s iffe
JDK7 was discovered in a previous step, you must verify that NetBeans
l e is r
usinga n
Java 1.7.0.
A n-t
d.no Click the Close button to close the About dialog box.
Note: NetBeans 7.0.1 was the first version of NetBeans to fully support the final
release of JDK 7.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1


Chapter 1 - Page 4
Practice 1-2: Software Installation

Overview
In this practice, you will install the software needed to perform Java 7 SE development.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Your instructor has instructed you to perform these steps.

Summary
You have been given a computer system that will be used for Java SE 7 software development.
You will use the information obtained in the previous practice to determine the software to be
installed, and then you will install the software.
A JDK and NetBeans cobundle is available that will reduce the number of files to download.
Downloading the JDK and NetBeans separately provides greater flexibility for selecting the JDK
to be used (32-bit or 64-bit) and reduces the required amount of data to download if either the
JDK or NetBeans is already installed. s a
For more information about Oracle JDK 7 supported operating systems, go to )h a
m
o ideฺ
http://www.oracle.com/technetwork/java/javase/config-417990.html. Java 7 support for
c

additional operating systems may be available from other channels.
r a cle t Gu
Tasks @ o e n
t e tu d
1. Obtain the required software. t r a S
a. If you require both the JDK and NetBeans,r a e hismethod is to download the “JDK
ฺisthe easiest
t
7 with NetBeans 7.0.1” cobundle.
x a nd us
1) Using a web browser, a l go to e t
e o
t e ( ns
http://www.oracle.com/technetwork/java/javase/downloads/index.html.
a
trJava SE li c e
2) LocateIthe
a s b l e Development Kit (JDK) Cobundles table.
3) Click
n r e ra button for “JDK 7 with NetBeans 7.0.1.”
d thefDownload
a
x4) You s
tran the software.
must accept the JDK 7 and NetBeans 7.0.1 Cobundle License Agreement to
Ale n-download
no5) Download the file for your operating system. As of this writing, Linux, Solaris, and
Windows downloads are available.
b. If you require just the JDK, download the Java SE 7 JDK.
1) Using a web browser, go to
http://www.oracle.com/technetwork/java/javase/downloads/index.html.
2) Locate the Java Platform, Standard Edition table.
3) Click the Download button for Java SE 7 JDK.
Note: Be sure to download the JDK and not the JRE.
4) You must accept the JDK 7 and NetBeans 7.0.1 Cobundle License Agreement to
download the software.
5) Download the file for your operating system. As of this writing, Linux, Solaris, and
Windows downloads are available.
c. If you require just the NetBeans IDE, download “NetBeans IDE 7.0.1 for Java SE.”
1) Using a web browser, go to http://download.netbeans.org/netbeans/7.0.1/final/.
2) Click the Download button for Java SE.
3) If the download does not start automatically, click the “download it here” link.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1


Chapter 1 - Page 5
2. Install the required software.
 Install the software downloaded in the previous step.
 The JDK includes optional demos and a database known as the JavaDB. Install all
optional JDK components if you are installing the JDK.
 If you downloaded the JDK and NetBeans separately (not the cobundle), complete
the installation of the JDK before installing NetBeans.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

 If you have multiple JDK versions installed, be sure to select the Java SE 7 JDK if
prompted while installing NetBeans.
 If NetBeans 7.0.1 was installed before JDK 7 or an older version of the JDK was
selected during NetBeans installation, perform practice 1-3 to reconfigure NetBeans
to use JDK 7.
3. Verify the software installation.
 Repeat practice 1-1 to verify software installation.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1


Chapter 1 - Page 6
Practice 1-3: Configuring NetBeans 7.0.1 to Utilize JDK 7

Overview
In this practice, you will configure NetBeans 7.0.1 to use a locally installed instance of JDK 7.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Your instructor has instructed you to perform these steps.

Summary
These steps are required only if both NetBeans 7.0.1 and JDK 7 are installed but NetBeans is
running with the wrong JDK. You can verify the JDK being used by NetBeans with the steps
outlined in practice 1-1, step 4. Failure to correct the NetBeans configuration to use JDK 7 will
result in an inability to create Java projects that use Java 7 language features.

Tasks
1. Configure NetBeans to be aware of the Java 7 Platform. s a
a. In the NetBeans IDE, select Tools, and then Java Platforms from the Main menu.)h a
c m
o ideฺ
b. Click the Add Platform button and specify the directory that contains your JDK 7

installation.
r a cle t Gu
o n
c. In the Platform Name step, verify that the default locations of the Platform Sources zip
@ e
file and API documentation are valid. t e tu d
t r a S
r a ฺis this
d. Click the Finish button to close the Add Java Platform dialog box.

a n d use
e. Ensure that JDK 1.7 is selected in the Platforms list and click Close.
2. e x to
Configure NetBeans to start with Java SE 7 JDK.
l
( a ns e
a. Open the directory containing the NetBeans configuration files, typically: C:\Program
a t e c e
I s tr le li
Files\NetBeans 7.0.1\etc\.

n d ra erab
b. Use a text editor to edit the netbeans.conf file.
c. Modify
x f
a thensnetbeans_jdkhome property to have a value of the JDK 7 installation
l e -t r
location,a for example:
A Files\Java\jdk1.7.0". netbeans_jdkhome="C:\Program
n o n
3. Restart NetBeans and verify the JDK being used by NetBeans with the steps outlined in
practice 1-1, step 4.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1


Chapter 1 - Page 7
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G2:u Java
Lesson
@ o e n
Syntax e
t and S
Class d
tu Review
t r a
r a ฺis 2 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 1
Practices for Lesson 2: Overview

Practices Overview
In these practices, you will use the NetBeans IDE and create a project, create packages, and a
Java main class, and then add classes and subclasses. You will also run your project from
within the IDE and learn how to pass command-line arguments to your main class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Note: There are two levels of practice for most of the practices in this course. Practices that are
marked “Detailed Level” provide more instructions and, as the name implies, at a more detailed
level. Practices that are marked “Summary Level” provide less detail, and likely will require
additional review of the student guide materials to complete. The end state of the “Detailed” and
“Summary” level practices is the same, so you can also use the solution end state as a tool to
guide your experience.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 2
Practice 2-1: Summary Level: Creating Java Classes

Overview
In this practice, using the NetBeans IDE, you will create an Employee class, create a class with
a main method to test the Employee class, compile and run your application, and print the
results to the command line output.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Tasks
1. Start the NetBeans IDE by using the icon from Desktop.
2. Create a new project EmployeePractice in the D:\labs\02-Review\practices
directory with an EmployeeTest main class in the com.example package.
3. Set the Source/Binary format to JDK 7.
a. Right-click the project and select Properties.
b. Select JDK 7 from the drop-down list for Source/Binary Format.
c. Click OK. s a
4. Create another package called com.example.domain. )h a
c m
o ideฺ
5. Add a Java Class called Employee in the com.example.domain package. ฺ
6. Code the Employee class. r a cle t Gu
@ o e n
t e tu d
a. Add the following data fields to the Employee class—use your judgment as to what
r a S
you want to call these fields in the class. Refer to the lesson materials for ideas on the
t
r a ฺis this
field names and the syntax if you are not sure. Use public as the access modifier.
n e
d usRecommended
Field use
e x a t o field type
Employee id
e ( al nseint
Employee name tra
t lice String
s
a I Security b e
lNumber
r
EmployeedSocial
n e r a String
a s f
A lex -trsalary
Employee an double

ona no-arg constructor for the Employee class.


7. Create
n
NetBeans can format your code at any time for you. Right-click anywhere in the class and
select Format, or press the Alt-Shift-F key combination.
8. Add accessor/mutator methods for each of the fields.
Note that NetBeans has a feature to create the getter methods for you. Click in your class
where you want the methods to go, then right-click and choose Insert Code (or press the
Alt-Insert keys). Choose getters from the Generate menu, and click the boxes next to the
fields for which you want getter and setter methods generated.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 3
9. Write code in the EmployeeTest class to test your Employee class.
a. Construct an instance of Employee.
b. Use the setter methods to assign the following values to the instance:
Field Value
Employee id 101
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Employee name Jane Smith


Employee Social Security Number 012-34-4567
Employee salary 120_345.27

c. In the body of the main method, use the System.out.println method to write the
value of the employee fields to the console output.
d. Resolve any missing import statements.
e. Save the EmployeeTest class.
s a
10. Run the EmployeePractice project. ) h a
11. (Optional) Add some additional employee instances to your test class. com e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 4
Practice 2-1: Detailed Level: Creating Java Classes

Overview
In this practice, using the NetBeans IDE, you will create an Employee class, create a class with
a main method to test the Employee class, compile and run your application, and print the
results to the command-line output.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Tasks
1. Start the NetBeans IDE by using the icon from Desktop.
2. Create a new Project called EmployeePractice in NetBeans with an EmployeeTest
class and a main method.
a. Click File > New Project.
b. Select Java from Categories, and Java Application from Projects.
c. Click Next.
d. On the New Application screen, enter the following values: s a
) h a
Window/Page Description Choices or Values
c o m e ฺ
Project Name: EmployeePractice ฺ
le Gu i d
r a c t
Project Location o
D:\labs\02-Review\practices
@ e n
Use Dedicated Folder for Storing Deselected
r a t e Stud
Libraries
r a ฺist this
Create Main Class
a n dSelecteduse
l e x Changeto the name to
( a e
ns com.example.EmployeeTest –
a t e c e
I s tr le li com.example is the package name.

d
Set as Main
n raProjecterab Selected
a s f
lexClick-tFinish.
Ae.You r an
n notice that NetBeans has saved you a great deal of typing by creating a class
nowill
called EmployeeTest, including the package name of com.example, and writing the
skeleton of the main method for you.
3. Set the Source/Binary format to JDK 7.
a. Right-click the project and select Properties.
b. Select JDK 7 from the drop-down list for Source/Binary Format.
c. Click OK.
4. Create another package called com.example.domain.
a. Right-click the current package com.example under Source Packages.
b. Select New > Java Package. The New Java Package dialog box highlights the new
subpackage name.
c. Enter com.example.domain in the Package Name field, and click Finish.
You will notice that the icon beside the package name is gray in the Project—this is
because the package has no classes in it yet.
5. Create a new Java Class called Employee in the com.example.domain package.
a. Right-click the com.example.domain package and select New > Java Class.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 5
b. In the Class Name field, enter Employee.
c. Click Finish to create the class.
Notice that NetBeans has generated a class with the name Employee in the package
com.example.domain.
6. Code the Employee class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

a. Add the following data fields to the Employee class.


Field use Access Recommended field Field name
type
Employee id public int empId
Employee name public String name
Employee Social public String ssn
Security Number
Employee salary public double
s a salary
b. Add a constructor to the Employee class: )h a
public Employee() { }
c m
o ideฺ

NetBeans can format your code at any time for you. Right-click anywhere
r a cle t inGthe u class and
select Format, or press the Alt-Shift-F key combination.
@ o e n
c. Create accesor/mutator (getter/setter) methods for e d
u fields.
t eachSoftthe
t r a
Note that NetBeans has a feature to create the
aฺisgetter is for you. Click in your class
tmethods
hchoose
n r
where you want the methods to go, thendright-click eand Insert Code (or press the
s Generate menu,
Alt-Insert keys). Select “Getter and aSetter” from
x gettertand
o u the and click the boxes
next to the fields for which you
( l e
want e all fields. Click Generate to insertYou
a to nselect setter methods generated. can also
e
t lice
click the class name (Employee) s the code.
t r a
s syntax
The built-in automated
a Isyntax b l e orchecker for NetBeans should have provided you with hints
when you have
n d r e ra errors code errors. Save your class.
f
xacoderain nthes EmployeeTest main class to test your Employee class.
7. Write
l e
Aa. Add -tan import statement to your class for the Employee object:
o n
n import com.example.domain.Employee;
b. In the main method of EmployeeTest, create an instance of your Employee class,
like this:
Employee emp = new Employee();
c. Using the employee object instance, add data to the object using the setter methods.
For example:
emp.setEmpId(101);
emp.setName("Jane Smith");
emp.setSsn ("012-34-5678");
emp.setSalary(120_345.27);
Note that after you type the "emp.", Netbeans provides you with suggested field names (in
green) and method names (in black) that can be accessed via the emp reference you typed.
You can use this feature to cut down on typing. After typing the dot following emp, use the
arrow keys or the mouse to select the appropriate method from the list. To narrow the list
down, continue typing some of the first letters of the method name. For example, typing

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 6
set will limit the list to the method names that begin with set. Double-click the method to
choose it.
d. In the body of the main method, use the System.out.println method to write
messages to the console output.
System.out.println ("Employee id: " + emp.getEmpId());
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

System.out.println ("Employee name: " + emp.getName());


System.out.println ("Employee Soc Sec #: " + emp.getSsn());
System.out.println ("Employee salary: " + emp.getSalary());
The System class is in the java.lang package, which is why you do not have to import it
(by default, you always get java.lang). You will learn more about how this multiple dot
notation works, but for now understand that this method takes a string argument and writes
that string to the console output.
e. Save the EmployeeTest class.
8. Examine the Project Properties.
a. Right-click the project and select Properties. s a
) h a
b. Expand Build, if necessary, and select Compiling. The option at the top, “Compile on
m
ฺ c o e ฺ
Save,” is selected by default. This means that as soon as you saved the Employee and
d
EmployeeTest classes, they were compiled. cle t Gu i
o r a n
e @ d e
c. Select Run. You will see that the Main Class is com.example.EmployeeTest. This

t r a t S tu
is the class the Java interpreter will execute. The next field is Arguments, which is used

r a ฺis this
for passing arguments to the main method. You will use arguments in a future lesson.

a n d use
d. Click Cancel to close the Project Properties.
9. Run the EmployeePractice project.
l e x to
( a ns e
a. To run your EmployeePractice project, right-click the project and select Run, or click
a t e c e
I s tr le li
the Run Main Project icon (the green triangle), or press F6.

n d ra erab
b. If your classes have no errors, your should see the following output in the Output
x awindow:
n s f
e
Al run: - tra
n
noEmployee id: 101
Employee name: Jane Smith
Employee Soc Sec #: 012-34-5678
Employee salary: 120345.27
BUILD SUCCESSFUL (total time: 1 second)
10. (Optional) Add some additional employee instances to your test class.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 7
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G3:u
Lesson
@ o e n
Encapsulation
t e d
tuand
t r a S
r a ฺis this
Subclassing
a n d use
l e x to 3
Chapter
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 1
Practices for Lesson 3: Overview

Practices Overview
In these practices, you will extend your existing Employee class to create new classes for
Engineers, Admins, Managers, and Directors.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 2
Practice 3-1: Summary Level: Creating Subclasses

Overview
In this practice, you will create subclasses of Employee, including Manager, Engineer, and
Administrative assistant (Admin). You will create a subclass of Manager called Director, and
create a test class with a main method to test your new classes.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
Use this Java class diagram to help guide this practice.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Tasks
1. Open the project EmployeePractice in the practices directory.
2. Apply encapsulation to the Employee class.
a. Make the fields of the Employee class private.
b. Replace the no-arg constructor in Employee with a constructor that takes empId,
name, ssn, and salary.
c. Remove all the setter methods except setName.
d. Add a method named raiseSalary with a parameter of type double called
increase to increment the salary.
e. Save Employee.java.

3. Create a subclass of Employee called Manager in the same package.


a. Add a private String field to store the department name in a field called deptName.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 3
b. Create a constructor that includes all the parameters needed for Employee and
deptName.
c. Add a getter method for deptName.
4. Create subclasses of Employee: Engineer and Admin in the com.example.domain
package. These do not need fields or methods at this time.
5. Create a subclass of Manager called Director in the com.example.domain package.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

a. Add a private field to store a double value budget.


b. Create a constructor for Director that includes the parameters needed for Manager and
the budget parameter.
c. Create a getter method for this field.
6. Save all the classes.
7. Test your subclasses by modifying the EmployeeTest class. Have your code do the
following:
a. Remove the code that creates an instance of the “Jane Smith” Employee.
s a
b. Create an instance of an Engineer with the following information:
)h a
Field Choices or Valuesom ฺ
ฺ c i d e
ID 101
r a cle t Gu
Name Jane Smith @ o e n
t e tu d
SSN 012-34-5678t r a S
r a ฺis this
Salary
a n d use
120_345.27
You will likely see an error beside l e xthe line that
to you added to create an Engineer. This is
because NetBeans cannot a e
(resolve Engineer
ns using the existing import statements in the
a t e c e
class. The quick way
Right-click in theI s tr leselect
to
class and
fix li Fix Imports, or press the
import statements is to allow NetBeans to fill them in for you.
Ctrl + Shift + I key combination.
r a r a b
NetBeans
x a ndwill automatically
s f eerror add the import statement for Engineer in the appropriate place
in the class andn the will disappear.
Ac.le Create
t r a
- an instance of a Manager with the following information:
non Field Choices or Values
ID 207
Name Barbara Johnson
SSN 054-12-2367
Salary 109_501.36
Department US Marketing
d. Use the setDeptName method on the manager instance to set the department field to
“US Marketing.”
e. Create an instance of an Admin with the following information:
Field Choices or Values
ID 304
Name Bill Monroe

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 4
Field Choices or Values
SSN 108-23-6509
Salary 75_002.34
f. Create an instance of a Director:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Field Choices or Values


ID 12
Name Susan Wheeler
SSN 099-45-2340
Salary 120_567.36
Department Global Marketing
Budget 1_000_000.00
s a
g. Use the setDeptName method to set the department name field to “Global Marketing.”
)h a
h. Use the setBudget method of Director to set the budget to 1,000,000.
c m
o ideฺ

i. Save EmployeeTest and correct any syntax errors.
r a cle t Gu
8. Add a printEmployee method to EmployeeTest to print o n Employee
out a formatted
object (its data fields). The printEmployee methodte @ take
should u d
an
e
Employee object as a
r a S t
parameter.
9. (Optional) Use the raiseSalary and setName r a ฺistmethods
t hison some of your objects to make
sure that those methods work. xan
d us e
a l e e to work.
10. Save the EmployeeTest class
t e ( and test your
ns print output using the NumberFormat class.
11. (Optional) Improve the a look of li c
the esalary
a. Use the a I str code
following l e
b get an instance of a static java.text.NumberFormat
to
n d r e r a
x
class
a that you
s f can use to format the salary to look like a standard US dollar currency:

- t r an
AInletheNumberFormat.getCurrencyInstance().format((double)emp.getSalary()));
nonlesson on abstract classes, you will see how to use an abstract factory, such as
NumberFormat.getCurrencyInstance().
12. (Optional) Add additional business logic (data validation) to your Employee class.
a. Prevent a negative value for the raiseSalary method.
b. Prevent a null or empty value for the setName method.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 5
Practice 3-1: Detailed Level: Creating Subclasses

Overview
In this practice, you will create subclasses of Employee, including Manager, Engineer, and
Administrative assistant (Admin). You will create a subclass of Manager called Director, and
create a test class with a main method to test your new classes
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
Use this Java class diagram to help guide this practice.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Tasks
1. Open the project EmployeePractice in the practices directory.
a. Select File > Open Project
b. Browse to D:\labs\03-Encapsulation\practices.
c. Select EmployeePractice.
d. Click Open Project.
2. Apply encapsulation to the Employee class.
a. Open the Employee class in the editor.
b. Make the fields of the Employee class private.

c. Replace the no-arg constructor in Employee with a constructor that takes empId,
name, ssn, and salary.
public Employee(int empId, String name, String ssn, double
salary) {
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 6
this.empId = empId;
this.name = name;
this.ssn = ssn;
this.salary = salary;
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

d. Remove all the setter methods except setName.


e. Add a method named raiseSalary with a parameter of type double named
increase to increment the salary
public void raiseSalary(double increase) {
salary += increase;
}
f. Save Employee.java
3. Create a subclass of Employee called Manager.
a. Right-click the package com.example.domain and select New > Java Class. s a
)h a
b. Enter the class name Manager and click Finish. m
ฺ c o ideฺ
c. Modify the class to subclass Employee.
Note that the class declaration now has an error mark on it from r a cle t GRecall
Netbeans.
u that
@ owill needetonadd a constructor
constructors are not inherited from the parent class, so you
a
that sets the value of the fields inherited from thetrparent
e udeasiest way to do this is
t class.StThe
r a e his the super keyword.
ฺis tusing
to write a constructor that calls the parent constructor
d. Add a private String field to storen
a d department
the us name in a field called deptName.
e. Add a constructor that takes l e x t o ssn, salary, and a deptName of type
( a empId,
s e name,
n should call the Employee constructor with the
String. The Manager
super keyword, t r a tethenconstructor
and l i c
set
ethe value of deptName.
I s l e
d
public
n raManager(int
f e r ab empId, String name, String ssn, double
e a
xsalary, n s
String deptName) {
l r a
A n-tsuper (empId, name, ssn, salary);
no this.deptName = deptName;
}
f. Add a getter method for deptName.
g. Save the Manager class.
4. Create two subclasses of Employee: Engineer and Admin in the
com.example.domain package. These do not need fields or methods at this time.
a. Because Engineers and Admins are Employees, add a constructor for each of these
classes that will construct the class as an instance of an Employee.
Hint: Use the super keyword as you did in the Manager class.
b. Save the classes.
5. Create a subclass of Manager called Director in the com.example.domain package.
a. Add a private field to store a double value budget.
b. Add the appropriate constructors for Director. Use the super keyword to construct a
Manager instance and set the value of budget.
c. Create a getter method for budget.
6. Save the class.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 7
7. Test your subclasses by modifying the EmployeeTest class. Have your code do the
following:
a. Remove the code that creates an instance of the “Jane Smith” Employee.
b. Create an instance of an Engineer with the following information:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Field Choices or Values


ID 101
Name Jane Smith
SSN 012-34-5678
Salary 120_345.27
You will likely see an error beside the line that you added to create an Engineer. This is
because NetBeans cannot resolve Engineer using the existing import statements in the
class. The quick way to fix import statements is to allow NetBeans to fill them in for you.
s a
) h a
Right-click in the class and select Fix Imports, or press the Ctrl + Shift + I key combination.
NetBeans will automatically add the import statement for Engineer in the appropriate place
in the class and the error will disappear. c o m e ฺ
ฺ i d
r a cle t Gu
c. Create an instance of a Manager with the following information:
@ o or Values
e n
Field Choices
e d
ID 207 istr
at s Stu
r a ฺ
e t hi
Name
x a ndBarbarauJohnson
s
SSN e t o
al nse054-12-2367
e (
Salary
s t r at lice 109_501.36
Departmentra I
a b le US Marketing
d r
fe of an Admin with the following information:
an anninstance
d. xCreate
e s
Al n-tra Field Choices or Values
n o
ID 304
Name Bill Monroe
SSN 108-23-6509
Salary 75_002.34

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 8
e. Create an instance of a Director:
Field Choices or Values
ID 12
Name Susan Wheeler
SSN 099-45-2340
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Salary 120_567.36
Department Global Marketing
Budget 1_000_000.00
f. Save EmployeeTest and correct any syntax errors.
8. Add a printEmployee method to EmployeeTest.
a. Adding System.out.println methods after each of the instances you created is
going to create a lot of redundant code. Instead, you will use a method that takes an
s a
Employee object as the parameter:
)h a
public static void printEmployee (Employee emp) {
c m
o ideฺ

System.out.println(); // Print a blank line as a
r a cle t Gu
separator
// Print out the data in this Employee object
@ o" + emp.getEmpId());
e n
System.out.println ("Employee id:
t e u d
System.out.println ("Employee name: t r a S" t+ emp.getName());
a ฺisSoc Secth#:is " + emp.getSsn());
System.out.println ("Employee
r
nd salary: e
System.out.println ("Employee
x a t o us " + emp.getSalary());
}
( e
al nse
r a e
Note that all the object tinstances e
i cthat you are creating are Employee objects, so
s
regardless of which t subclass
I cannot l e l
you create, the printEmployee method will work. However,
the Employee
d r a class r a b know about the specialization of its subclasses. You will see
n
a work around
howxto f e
s this in the next lesson.
l e t r a n
9. AUse the-printEmployee method to print out information about your classes. For example:
o n
n printEmployee (eng);
printEmployee(man);
printEmployee(adm);
printEmployee(dir);
10. (Optional) Use the raiseSalary and setName methods on some of your objects to make
sure those methods work. For example:
mgr.setName ("Barbara Johnson-Smythe");
mgr.raiseSalary(10_000.00);
printEmployee(mgr);
11. Save the EmployeeTest class and test your work.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 9
12. (Optional) Improve the look of the salary print output using the NumberFormat class.
a. Use the following code to get an instance of a static java.text.NumberFormat
class that you can use to format the salary to look like a standard U.S. dollar currency.
Replace the emp.getSalary() with the following:
NumberFormat.getCurrencyInstance().format((double)emp.getSalary())
In the lesson on abstract classes, you will see how to use an abstract factory, such as
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

NumberFormat.getCurrencyInstance().
13. (Optional) Add additional business logic (data validation) to your Employee class.
a. Prevent a negative value for the raiseSalary method.
b. Prevent a null or empty value for the setName method.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 10
(Optional) Practice 3-2: Adding a Staff to a Manager

Overview
In this practice you modify the Manager class to add an array of Employee objects (a staff) to
the manager class, and create methods to add and remove employees from the Manager.
Finally, add a method to Manager to print the staff names and IDs.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
Start with the completed project from Practice 3-1 (Summary or Detailed) or the solution from
the solutions\practice1 directory.

Tasks
1. Add fields to the Manager class to keep the employee objects.
a. Declare a private field called staff that is declared as an array of Employee objects .
b. You will need to keep track of the number of employees in staff, so create a private
s a
) h a
integer field employeeCount to keep a count of the number of employees. Initialize
the employee count with 0. m
ฺ c o d e ฺ
i
c. In the constructor, initialize the staff array with a maximum of 20 employees.
cle t Gu
2. r a
Add a method called findEmployee. This method scans the current staff Employee array
o n
@ d e
to see whether there is a match between the any member of staff and the Employee
e
passed in. t r a t S tu
a ฺis this
a. Return -1 if there is no match, and the index number of the Employee if there is a
r
match.
a n d use
3. l e x to
Add a method called addEmployee. This method adds the Employee passed in as a
( a ns e
a e
parameter to the end of the array.
t c e
s tr le li
a. This method should return a boolean value and take an Employee object as a
I
n d ra erab
parameter. The method should return true if the employee was successfully added and
x a n s f
false if the employee already exists as a member of staff.
e
Al n-tra
b. Call the findEmployee method to determine whether the Employee is a member of
no staff already. Return false if there is match.
c. Add the employee object to the staff array. (Hint: Use the employeeCount as the
index of the array element to assign the employee parameter to.)
d. Increment the employeeCount and return true.
4. Add a method called removeEmployee. This method is a bit more complicated. When you
remove an element from the array, you must shift the other elements of the array so there
are no empty elements. The easiest way to do this is to create a new array and assign a
copy of each of the staff elements to it except for the match. This effectively removes the
match from the array.
a. Declare a local boolean variable initialized to false to return as the status for the
method.
b. Declare a temporary array of Employee objects to copy the revised staff array to.
c. Declare an integer counter of the number of employees copied to the temporary array.
d. Use a for loop to go through the staff array and attempt to match the employee ID of
each element of the staff array with the employee ID of the Employee passed into the
method as a parameter.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 11
e. If the employee ID’s do not match, copy the employee reference from the staff array to
the temporary array from step b and increment the count of employees in the
temporary array.
f. If there is a match, “skip” this employee by continuing to the next element in the staff
array, and set the local boolean variable from step a to true.
g. If there was a match (the local boolean is true), replace the current staff array with the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

temporary array, and the count of employees with the temporary counter from step c.
h. Return the local boolean variable.
5. Add a method called printStaffDetails. This method prints the name of the manager
and then each of the elements of staff in turn.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 12
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G4:u Java
Lesson
@ o e n
Class e
Design
t tu d
t r a S
r a ฺis 4 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 1
Practices for Lesson 4

Practices Overview
In these practices, you will override methods, including the toString method in the Object
class. You will also create a method in a class that uses the instanceof operator to determine
which object was passed to the method.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 2
Practice 4-1: Summary Level: Overriding Methods and Applying
Polymorphism

Overview
In this practice, you will override the toString method of the Object class in the Employee
class and in the Manager class. You will create an EmployeeStockPlan class with a
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

grantStock method that uses the instanceof operator to determine how much stock to
grant based on the employee type.

Assumptions

Tasks
1. Open the EmployeePractice project in the practices directory.
2. Edit the Employee class to override the toString() method from the Object class.
Object’s toString method returns a String.
s a
h a
a. Add a return statement that returns a string that includes the employee ID, name,
)
c o m
Social Security number, and a salary as a formatted string, with each line separated
e ฺ
with a newline character ("\n"). ฺ i d
b. To format the double salary, use the following: r a cle t Gu
@ o e n
t e
NumberFormat.getCurrencyInstance().format(getSalary())
tu d
c. Fix any missing import statements. t r a S
d. Save the class. r a ฺis this
a n d use
3.
l e x
Override the toString() method in the Manager class to include the deptName field
to
a e
value. Separate this string from the Employee string with a newline character.
( ns
a t e c e
Note the Green circle icon with the “o” in the center beside the method signature in the
I s tr le li
Manager class. This indicates that NetBeans is aware that this method overrides the
d ra erab
method from the parent class, Employee. Hold the cursor over the icon to read what this
n
x a s f
icon represents:
n
e
Al n-tra
no

Click the icon, and NetBeans will open the Employee class and position the view to the
toString() method.
4. (Optional) Override the toString() method in the Director class as well, to display all
the fields of a Director and the available budget.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 3
5. Create a new class called EmployeeStockPlan in the package
com.example.business. This class will include a single method, grantStock, which
takes an Employee object as a parameter and returns an integer number of stock options
based on the employee type:
Employee Type Number of Stock Options
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Director 1000
Manager 100
All other Employees 10
a. Add a grantStock method that takes an Employee object reference as a parameter
and returns an integer
b. In the method body, determine what employee type was passed in using the
instanceof keyword and return the appropriate number of stock options based on
that type.
c. Resolve any missing import statements. s a
d. Save the EmployeeStockPlan class. )h a
6. Modify the EmployeeTest class. Replace the four print statements in the c m
o ideฺ

r a cle t Gu
printEmployee method with a single print statement that uses the toString method
that you created.
@ o e n
7. t e
Overload the printEmployee method to take a second parameter, tu d
t r a S
r a ฺis this
EmployeeStockPlan, and print out the number of stock options that this employee will
receive.
a n d use
x to
a. Above the printEmployee method calls in the main method, create an instance of
l e
( a ns e
the EmployeeStockPlan and pass that instance to each of the printEmployee
methods. a t e c e
I s tr le li
b. The new printEmployee method should call the first printEmployee method and
n d ra erab
the number of stocks granted to this employee:
x a n s f
e - t a
Al System.out.println("Stock
r
printEmployee (emp);

non Options: " + esp.grantStock(emp));


8. Save the EmployeeTest class and run the application. You should see output for each
employee that includes the number of Stock Options, such as:
Employee id: 101
Employee name: Jane Smith
Employee Soc Sec #: 012-34-5678
Employee salary: $120,345.27
Stock Options: 10

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 4
9. It would be nice to know what type of employee each employee is. Add the following to your
original printEmployee method above the print statement that prints the employee data
fields:
System.out.println("Employee type: " +
emp.getClass().getSimpleName());
This will print out the simple name of the class (Manager, Engineer, etc). The output of
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

the first employee record should now look like this:


Employee type: Engineer
Employee id: 101
Employee name: Jane Smith
Employee Soc Sec #: 012-34-5678
Employee salary: $120,345.27
Stock Options: 10

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 5
Practice 4-1: Detailed Level: Overriding Methods and Applying
Polymorphism

Overview
In this practice, you will override the toString method of the Object class in the Employee
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

class and in the Manager class. You will create an EmployeeStockPlan class with a
grantStock method that uses the instanceof operator to determine how much stock to
grant based on the employee type.

Assumptions

Tasks
1. Open the EmployeePractice project in the practices directory.
a. Select File > Open Project.
b. Browse to D:\labs\04-Class_Design\practices. s a
c. Select EmployeePractice and click Open Project. )h a
2. Edit the Employee class to override the toString() method from the c m
o idclass.
e ฺ
ฺ Object
Object's toString method returns a String.
r a cle t Gu
a. Add the toString method to the Employee class withothe following e n signature:
t e @ tu d
public String toString() {
t r a S
b. Add a return statement that returns a astring is the employee information:
ฺis thatthincludes
ID, name, Social Security number,
r e
ndand a formatted
s salary like this:
x a o u
return "Employee ID:
( a le s"e+t getEmpId() + "\n" +
"Employee
t r a te Name:
l i c en " + getName() + "\n" +
r a Is bleSSN: " + getSsn() + "\n" +
"Employee

n d "Employee
f e ra Salary: " +
a
x ran s
NumberFormat.getCurrencyInstance().format(getSalary());
Ac.le Save
n -t the Employee class.
o
n the toString method in the Manager class to include the deptName field value.
3. Override
a. Open the Manager class.
b. Add a toString method with the same signature as the Employee toString
method:
public String toString() {
The toString method in the Manager class overrides the toString method inherited
from the Employee class.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 6
c. Call the parent class method by using the super keyword and add the department
name:
return super.toString() + "\nDepartment: " + getDeptName();
Note the Green circle icon with the “o” in the center beside the method signature in the
Manager class. This indicates that NetBeans is aware that this method overrides the
method from the parent class, Employee. Hold the cursor over the icon to read what this
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

icon represents:

Click the icon, and NetBeans will open the Employee class and position the view to the
toString() method.
d. Save the Manager class. s a
4. (Optional) Override the toString method in the Director class as well, to display
a
) h all the
fields of a director and the available budget.
c m
o ideฺ
5. Create a new class called EmployeeStockPlan in the packagecle
ฺ u
com.example.business. This class will include a single method, o r a n t G which
e @ d e
grantStock,
takes an Employee object as a parameter and returns
based on the employee type: t r a t an
S tu
integer number of stock options

r a ฺis this
Employee Type
n d usNumber e of Stock Options
e x a to
Director
( a l s e 1000
Manager
t r a te licen 100
All other
a s
I Employees
b le 10
d r r a
an thensnew
a. Create
x fepackage and class in one step by right-clicking Source Package, and
e
Al then - ra New > Java Class.
tselecting
b. o n
n Enter EmployeeStockPlan as the Class Name and com.example.business as
the Package and click Finish.
c. In the new class, add fields to the class to define the stock levels, like this:
private final int employeeShares = 10;
private final int managerShares = 100;
private final int directorShares = 1000;
d. Add a grantStock method that takes an Employee object reference as a parameter
and returns an integer:
public int grantStock(Employee emp) {

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 7
e. In the method body, determine what employee type was passed in using the
instanceof keyword and return the appropriate number of stock options based on
that type. Your code might look like this:
// Stock is granted based on the employee type
if (emp instanceof Director) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

return directorShares;
} else {
if (emp instanceof Manager) {
return managerShares;
} else {
return employeeShares;
}
}
f. Resolve any missing import statements.
s a
g. Save the EmployeeStockPlan class.
)h a
6. Modify the EmployeeTest class. Replace the four print statements in the
c m
o ideฺ

that you created. r a cle t Gu
printEmployee method with a single print statement that uses the toString method

@ o e n
a. Replace these lines: t e tu d
t r a S
System.out.println("Employee id:
r a ฺis this + emp.getEmpId());
"
System.out.println("Employee
n d name:u s e " + emp.getName());
e x a toSoc Sec #: " + emp.getSsn());
( a l
System.out.println("Employee
e
a t e
System.out.println("Employee
c e ns salary: " +

I s tr le li
NumberFormat.getCurrencyInstance().format((double)
raline that
emp.getSalary()));
d b
rauses
b. With
x a n one
s f e the toString() method:
e tra n
Al System.out.println(emp);
n -
no the printEmployee method to take a second parameter,
7. Overload
EmployeeStockPlan, and print out the number of stock options that this employee will
receive.
a. Create another printEmployee method that takes an instance of the
EmployeeStockPlan class:
public static void printEmployee(Employee emp, EmployeeStockPlan
esp) {
b. This method first calls the original printEmployee method:
printEmployee(emp);
c. Add a print statement to print out the number of stock options that the employee is
entitled to:
System.out.println("Stock Options: " +
esp.grantStock(emp));
d. Above the printEmployee method calls in the main method, create an instance of
the EmployeeStockPlan and pass that instance to each of the printEmployee
methods:

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 8
EmployeeStockPlan esp = new EmployeeStockPlan();
printEmployee(eng, esp);
... modify the remaining printEmployee invocations
e. Resolve any missing import statements.
8. Save the EmployeeTest class and run the application. You should see output for each
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

employee that includes the number of Stock Options, such as:


Employee id: 101
Employee name: Jane Smith
Employee Soc Sec #: 012-34-5678
Employee salary: $120,345.27
Stock Options: 10
9. It would be nice to know what type of employee each employee is. Add the following to your
original printEmployee method above the print statement that prints the employee data
fields:
s a
System.out.println("Employee type: " +
)h a
emp.getClass().getSimpleName());
c m e ฺ
o Theioutput
This will print out the simple name of the class (Manager, Engineer, ฺ
le Gu
etc). d of
a c
the first employee record should now look like this:
@ or ent
Employee type: Engineer
r a t e Stud
t
aฺis e this
Employee id: 101
Employee name: Jane d r
Smith
x
Employee Soc Sec #: 012-34-5678
e an to us
Employee salary: (al $120,345.27 se
t e e n
Stock Options:
I s tra le lic10
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G5:u
Lesson
@ o e n
Advanced e
t Class d
tu Design
t r a S
r a ฺis 5 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 1
Practices for Lesson 5: Overview

Practices Overview
In these practices, you will use the abstract, final, and static Java keywords. You will also learn
to recognize nested classes.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 2
Practice 5-1: Summary Level: Applying the Abstract Keyword

Overview
In this practice, you will take an existing application and refactor the code to use the abstract
keyword.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the abstract class section of this lesson.

Summary
You have been given a project that implements the logic for a bank. The banking software
supports only the creation of time deposit accounts. Time deposit accounts allow withdraw only
after a maturity date. Time deposit accounts are also known as term deposit, certificate of
deposit (CD), or fixed deposit accounts. You will enhance the software to support checking
accounts.
A checking account and a time deposit account have some similarities and some differences. s a
)h a
Your class design should reflect this. Additional types of accounts might be added in the future.
c m
o ideฺ

Tasks
1. Open the AbstractBanking project as the main project. ora
cle t Gu
@ d e n
a. Select File > Open Project.
r a t e S tu
t
ฺis this
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
r a
c. Select AbstractBanking and select
a n d u“Open
the se as Main Project” check box.
d. Click the Open Project button. l e x to
(
2. Expand the project directories.
a ns e
a t e c e
3. Run the project. s
I tr should
You
l e li a report of all customers and their accounts.
see
d a rab
4. Review therTimeDepositAccount class.
n f e
a thenTimeDepositAccount.java
a. xOpen s file (under the com.example package).
l e r a
-t the fields and method implementations of TimeDepositAccount that are
Ab. Identify
o n
n related to time or are in some other way specific to TimeDepositAccount. Add a
code comment if desired.
c. Identify the fields and method implementations of TimeDepositAccount that could
be used by any type of account. Add a code comment if desired.
5. Create a new Java class, Account, in the com.example package.
6. Code the Account class.
a. This class should be declared as abstract.
b. Move any fields and method implementations from TimeDepositAccount that could
be used by any type of account to the Account class.
Note: The fields and methods should be removed from TimeDepositAccount.
c. Add abstract methods to the Account class for any methods in
TimeDepositAccount that are time related but have a method signature that would
make sense in any type of account.
Hint: Would all accounts have a description?
d. Add an Account class constructor that has a double balance parameter.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 3
e. The Account class should have a protected access level balance field that is
initialized by the Account constructor.
7. Modify the TimeDepositAccount class.
a. TimeDepositAccount should be a subclass of Account.
b. Modify the TimeDepositAccount constructor to call the parent class constructor with
the balance value.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

c. Make sure that you are overriding the abstract withdraw and getDescription
methods inherited from the Account class.
Note: It is a good practice to add @Override to any method that should be overriding
a parent class method.
8. Modify the Customer and CustomerReport classes to use Account references.
a. Open the Customer.java file (under the com.example package).
b. Change all TimeDepositAccount references to Account type references.
c. Open the CustomerReport.java file (under the com.example package).
s a
d. Change all TimeDepositAccount references to Account type references.
) h a
9. Run the project. You should see a report of all customers and their accounts.
c o m e ฺ
ฺ i d
10. Create a new Java class, CheckingAccount, in the com.example package.
a. CheckingAccount should be a subclass of Account. r a cle t Gu
@ o e n
b. Add an overDraftLimit field to the CheckingAccount class.t e tu d
t r a S
private final double overDraftLimit;
r a ฺis this
c. Add a CheckingAccount constructor
a n d thatuhas setwo parameters.
 double balance: Passle x value totothe parent class constructor.
this
 double overDraftLimit:
t e ( a
e n se this value in the overDraftLimit field.
Store
I s tra le licconstructor that has one parameter. This constructor
d. Add a CheckingAccount
shouldrset
n d f e r ab
a the overDraftLimit field to zero.
 adouble s
l e x ranbalance: Pass this value to the parent class constructor.
A n-t
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 4
e. Override the abstract getDescription method inherited from the Account class.
@Override
public String getDescription() {
return "Checking Account";
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Note: It is a good practice to add @Override to any method that should be overriding
a parent class method.
f. Override the abstract withdraw method inherited from the Account class.
 The withdraw method should allow an account balance to go negative up to the
amount specified in the overDraftLimit field.
 The withdraw method should return false if the withdraw cannot be performed,
and true if it can.
11. Modify the AbstractBankingMain class to create checking accounts for the customers.
// Create several customers and their accounts
s a
bank.addCustomer("Jane", "Simms");
) h a
customer = bank.getCustomer(0);
c o m e ฺ
ฺ i d
customer.addAccount(new TimeDepositAccount(500.00,
cal.getTime())); r a cle t Gu
@ o e n
e
customer.addAccount(new CheckingAccount(200.00, 400.00));
t tu d
t r a S
r a ฺis this
bank.addCustomer("Owen", "Bryant");
a n d use
customer = bank.getCustomer(1);
l e x CheckingAccount(200.00));
to
customer.addAccount(new ( a ns e
a t e c e
I s tr le li "Soley");
rab
ra = ebank.getCustomer(2);
bank.addCustomer("Tim",
n d
customer
a f
l e a s
xcustomer.addAccount(new
n
t r
A cal.getTime()));
n -
TimeDepositAccount(1500.00,

nocustomer.addAccount(new CheckingAccount(200.00));

bank.addCustomer("Maria", "Soley");
customer = bank.getCustomer(3);
// Maria and Tim have a shared checking account
customer.addAccount(bank.getCustomer(2).getAccount(1));
customer.addAccount(new TimeDepositAccount(150.00,
cal.getTime()));
Note: Both Customer and CustomerReport can utilize CheckingAccount
instances, because you previously modified them to use Account type references.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 5
12. Run the project. You should see a report of all customers and their accounts. Note that the
date displayed should be one hundred and eighty days in the future.
CUSTOMERS REPORT
================
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Customer: Simms, Jane


Time Deposit Account Sat Feb 04 11:14:54 CST 2012: current
balance is 500.0
Checking Account: current balance is 200.0

Customer: Bryant, Owen


Checking Account: current balance is 200.0

Customer: Soley, Tim


s a
Time Deposit Account Sat Feb 04 11:14:54 CST 2012: current
balance is 1500.0 )h a
c m
o ideฺ
Checking Account: current balance is 200.0 ฺ
r a cle t Gu
@ o e n
Customer: Soley, Maria
e
t is 200.0 tu d
Checking Account: current balance
t r a S
Time Deposit Account SataFeb
r e his
ฺis 04 11:14:54
t CST 2012: current
balance is 150.0 d
an to us
e x
e ( al nse
s t r at lice
r a I
a b le
x a nd sfer
n
Ale n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 6
Practice 5-1: Detailed Level: Applying the Abstract Keyword

Overview
In this practice, you will take an existing application and refactor the code to use the abstract
keyword.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the abstract class section of this lesson.

Summary
You have been given a project that implements the logic for a bank. The banking software
supports only the creation of time deposit accounts. Time deposit accounts allow withdraw only
after a maturity date. Time deposit accounts are also known as term deposit, certificate of
deposit (CD), or fixed deposit accounts. You will enhance the software to support checking
accounts.
A checking account and a time deposit account have some similarities and some differences.s a
) h a
Your class design should reflect this. Additional types of accounts might be added in the future.
c o m e ฺ
ฺ i d
Tasks
r a cle t Gu
1. Open the AbstractBanking project as the main project. o n
e @ d e
a. Select File > Open Project.
t r a t S tu
r a ฺis this
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
c. Select AbstractBanking and select
a n se as Main Project” check box.
d theu“Open
l
d. Click the Open Project button. e x to
( a ns e
a t e
2. Expand the project directories.
c e
3. Run the project.Is tr should
You
l e li a report of all customers and their accounts.
see

n d ra erabCUSTOMERS REPORT
x a n s f
e
Al n-tra
================

noCustomer: Simms, Jane


Time Deposit Account Fri Mar 09 12:04:28 CST 2012: current
balance is 500.0

Customer: Bryant, Owen

Customer: Soley, Tim


Time Deposit Account Fri Mar 09 12:04:28 CST 2012: current
balance is 1500.0

Customer: Soley, Maria


Time Deposit Account Fri Mar 09 12:04:28 CST 2012: current
balance is 150.0

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 7
4. Review the TimeDepositAccount class.
a. Open the TimeDepositAccount.java file (under the com.example package).
b. Identify the fields and method implementations of TimeDepositAccount that are
related to time or are in some other way specific to TimeDepositAccount. Add a
code comment to the maturityDate field and the withdraw and getDescription
methods. For example:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

// time deposit account specific code


private final Date maturityDate;
c. Identify the fields and method implementations of TimeDepositAccount that could
be used by any type of account. Add a code comment to the balance field and the
getBalance, deposit, and toString methods. For example:
// generic account code
private double balance;
5. Create a new Java class, Account, in the com.example package. a
a s
6. Code the Account class.
m )h
a. This class should be declared as abstract.
ฺ c o ideฺ
public abstract class Account
r a cle t Gu
b. Move the balance field and the getBalance, deposit,
@ o and toString
e n methods
from TimeDepositAccount to the Accounta t e
class. t u d
i
Note: The fields and methods should beฺremoveds tr from i s S
h
ra toethet Account class.
TimeDepositAccount.
c. Add an abstract getDescription n dmethod s
u
l e xagetDescription();
t o
(a method seto the Account class.
public abstract String
d. Add an abstract a t e e n
I s
withdraw
e lic withdraw(double amount);
tr lboolean
ra eclass rabshould have a protected access level balance field. If you have
public abstract
e. The n d
a moved f
l e
Account
xalready a n s this field from the TimeDepositAccount, just change the access
A level.n -t r
o
n protected double balance;
f. Add an Account class constructor that has a double balance parameter.
public Account(double balance) {
this.balance = balance;
}
7. Modify the TimeDepositAccount class.
a. TimeDepositAccount should be a subclass of Account.
public class TimeDepositAccount extends Account

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 8
b. Modify the TimeDepositAccount constructor to call the parent class constructor with
the balance value.
super(balance);
c. Make sure that you are overriding the abstract withdraw and getDescription
methods inherited from the Account class, by using the @Override annotation.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

@Override
public String getDescription() {
return "Time Deposit Account " + maturityDate;
}
Note: It is a good practice to add @Override to any method that should be overriding
a parent class method.
8. Modify the Customer and CustomerReport classes to use Account references.
a. Open the Customer.java file (under the com.example package).
b. Change all TimeDepositAccount references to Account type references. s a
c. Open the CustomerReport.java file (under the com.example package). )h a
c
d. Change all TimeDepositAccount references to Account type ฺreferences.
m
o ideฺ
e Gu
claccounts.
o a
9. Run the project. You should see a report of all customers andrtheir
n t
@
10. Create a new Java class, CheckingAccount, in the com.example epackage.
a
a. CheckingAccount should be a subclass oftrAccount.
te Stud
a ฺis
extends th
is
public class CheckingAccount r
nd us e Account
b. Add an overDraftLimit field
e x ato the CheckingAccount
to class.
a l e
( overDraftLimit;
private final double
a t e c e ns
I s tr le li constructor.
c. Add a CheckingAccount

n d
public
f e rab
raCheckingAccount(double balance, double overDraftLimit) {
a
x ran s
Ale n-tthis.overDraftLimit
super(balance);
= overDraftLimit;
o
n}
d. Add a CheckingAccount constructor that has one parameter.
public CheckingAccount(double balance) {
this(balance, 0);
}
e. Override the abstract getDescription method inherited from the Account class.
@Override
public String getDescription() {
return "Checking Account";
}
Note: It is a good practice to add @Override to any method that should be overriding
a parent class method.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 9
f. Override the abstract withdraw method inherited from the Account class. The
withdraw method should allow an account balance to go negative up to the amount
specified in the overDraftLimit field.
@Override
public boolean withdraw(double amount) {
if(amount <= balance + overDraftLimit) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

balance -= amount;
return true;
} else {
return false;
}
}
11. Modify the AbstractBankingMain class to create checking accounts for the customers.
// Create several customers and their accounts
s a
bank.addCustomer("Jane", "Simms");
) h a
customer = bank.getCustomer(0);
c o m e ฺ
ฺ i d
customer.addAccount(new TimeDepositAccount(500.00,
r a cle t Gu
cal.getTime()));
@ o e n
t e
customer.addAccount(new CheckingAccount(200.00, 400.00));
tu d
t r a S
r a ฺis this
bank.addCustomer("Owen", "Bryant");
a n d use
customer = bank.getCustomer(1);
l e x to
customer.addAccount(new ( a ns e
CheckingAccount(200.00));
a t e c e
I s tr le li "Soley");
rab
ra = ebank.getCustomer(2);
bank.addCustomer("Tim",
a n d f
l e
customer
a n s
xcustomer.addAccount(new
n - t r
A cal.getTime())); TimeDepositAccount(1500.00,

nocustomer.addAccount(new CheckingAccount(200.00));

bank.addCustomer("Maria", "Soley");
customer = bank.getCustomer(3);
// Maria and Tim have a shared checking account
customer.addAccount(bank.getCustomer(2).getAccount(1));
customer.addAccount(new TimeDepositAccount(150.00,
cal.getTime()));
Note: Both Customer and CustomerReport can utilize CheckingAccount
instances, because you previously modified them to use Account type references.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 10
12. Run the project. You should see a report of all customers and their accounts. Note that the
date displayed should be one hundred and eighty days in the future.
CUSTOMERS REPORT
================
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Customer: Simms, Jane


Time Deposit Account Sat Feb 04 11:14:54 CST 2012: current
balance is 500.0
Checking Account: current balance is 200.0

Customer: Bryant, Owen


Checking Account: current balance is 200.0

Customer: Soley, Tim


s a
Time Deposit Account Sat Feb 04 11:14:54 CST 2012: current
balance is 1500.0 )h a
c m
o ideฺ
Checking Account: current balance is 200.0 ฺ
r a cle t Gu
@ o e n
Customer: Soley, Maria
e
t is 200.0 tu d
Checking Account: current balance
t r a S
Time Deposit Account SataFeb
r e his
ฺis 04 11:14:54
t CST 2012: current
balance is 150.0 d
an to us
e x
e ( al nse
s t r at lice
r a I
a b le
x a nd sfer
n
Ale n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 11
Practice 5-2: Summary Level: Applying the Singleton Design Pattern

Overview
In this practice, you will take an existing application and refactor the code to implement the
Singleton design pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the static and final keyword sections of this lesson.

Summary
You have been given a project that implements the logic for a bank. The application currently
allows the creation of an unlimited number of Bank instances.
Bank bank = new Bank();
Bank bank2 = new Bank();
Bank bank3 = new Bank(); s a
a
) hper Java
Using the static and final keywords you will limit the number of Bank instances to one
virtual machine (JVM). c m
o ideฺ

Tasks r a cle t Gu
@ o e n
1. Open the SingletonBanking project as the main project. t e tu d
t r a S
a. Select File > Open Project.
r a ฺis this
a n d use
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
c. Select SingletonBankingx tothe “Open as Main Project” check box.
and select
a l e
d. Click the Open Project(button. s e
2. Expand the projecttr a te licen
directories.
a
3. Run the project.
r IsYou should
b lesee a report of all customers and their accounts.
a
nd sfer CUSTOMERS REPORT
x a n
Ale n-tra ================
no
Customer: Simms, Jane
Time Deposit Account Fri Mar 09 12:04:28 CST 2012: current
balance is 500.0

Customer: Bryant, Owen

Customer: Soley, Tim


Time Deposit Account Fri Mar 09 12:04:28 CST 2012: current
balance is 1500.0

Customer: Soley, Maria


Time Deposit Account Fri Mar 09 12:04:28 CST 2012: current
balance is 150.0

4. Modify the Bank class to implement the Singleton design pattern.


a. Open the Bank.java file (under the com.example package).
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 12
b. Change the constructor’s access level to private.
c. Add a new field named instance. The field should be:
 private
 Marked static
 Marked final
 Type of Bank
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

 Initialized to a new Bank instance


d. Create a static method named getInstance that returns the value stored in the
instance field.
5. Modify the SingletonBankingMain class to use the Bank singleton.
a. Open the SingletonBankingMain.java file (under the com.example package).
b. Replace any calls to the Bank constructor with calls to the previously created
getInstance method.
c. In the main method, create a second local Bank reference named bank2 and initialize
it using the getInstance method. s a
)h a
d. Use reference equality checking to determine whether bank and bank2 reference the
same object. c m
o ideฺ

if(bank == bank2) {
r a cle t Gu
System.out.println("bank and bank2@ o the esame
n object");
t e are
tu d
} t r a S
s on the first Bank.
e. Try initializing only the second Bank butr a is the
ฺrunning t hireport
nd us e
initializeCustomers(bank2);
e x a to
( a l e
a t e c e ns
I s tr report
// run the customer
l e li = new CustomerReport();
report

n d ra erab
CustomerReport

x a s f
report.setBank(bank);
n
e
Al n-tra
report.generateReport();

nothe project. You should see a report of all customers and their accounts.
6. Run

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 13
Practice 5-2: Detailed Level: Applying the Singleton Design Pattern

Overview
In this practice, you will take an existing application and refactor the code to implement the
Singleton design pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the static and final keyword sections of this lesson.

Summary
You have been given a project that implements the logic for a bank. The application currently
allows the creation of an unlimited number of Bank instances.
Bank bank = new Bank();
Bank bank2 = new Bank();
Bank bank3 = new Bank();
s a
Using the static and final keywords you will limit the number of Bank instances to one a
) hper Java
Virtual Machine (JVM).
c m
o ideฺ

Tasks r a cle t Gu
@ o e n
1. Open the SingletonBanking project as the main project.
t e tu d
a. Select File > Open Project. t r a S
r a ฺis this
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
a d use
nselect
c. Select SingletonBankingx and othe “Open as Main Project” check box.
l
a nse
d. Click the Open Project(button.
e t
2. Expand the projecttr a t e i ce
s
IYou should l
directories.
lesee a report of all customers and their accounts.
3. Run the project.r a a b
4. Modify
x a er to implement the Singleton design pattern.
nthedBanksclass
f
Aa.le Open - t r anBank.java file (under the com.example package).
the
b.no
n
Change the constructor’s access level to private.
private Bank() {
customers = new Customer[10];
numberOfCustomers = 0;
}
c. Add a new field named instance. The field should be:
 private
 Marked static
 Marked final
 Type of Bank
 Initialized to a new Bank instance
private static final Bank instance = new Bank();
d. Create a static method named getInstance that returns the value stored in the
instance field.
public static Bank getInstance() {
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 14
return instance;
}
5. Modify the SingletonBankingMain class to use the Bank singleton.
a. Open the SingletonBankingMain.java file (under the com.example package).
b. Replace any calls to the Bank constructor with calls to the previously created
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

getInstance method.
Bank bank = Bank.getInstance();
c. In the main method, create a second local Bank reference named bank2 and initialize
it using the getInstance method.
Bank bank2 = Bank.getInstance();
d. Use reference equality checking to determine whether bank and bank2 reference the
same object.
if(bank == bank2) {
s a
}
System.out.println("bank and bank2 are the same object");
) h a
c o m e ฺ

e. Initialize only the second Bank, but run the report on the first Bank. i d
initializeCustomers(bank2); r a cle t Gu
@ o e n
t e tu d
t r a S
ฺis this
// run the customer report
CustomerReport report = newra
report.setBank(bank); xan
d use
CustomerReport();

a l e e to
report.generateReport();
t e ( ns of all customers and their accounts.
6. Run the project. You a
tr le li
should see caereport
I s
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 15
(Optional) Practice 5-3: Using Java Enumerations

Overview
In this practice, you will take an existing application and refactor the code to use an enum.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have reviewed the enum section of this lesson.

Summary
You have been given a project that implements the logic for a bank. The application currently
allows the creation of TimeDepositAccount instances with any maturity date.
//180 day term
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 180);
new TimeDepositAccount(500.00, cal.getTime()) s a
By creating a new Java enum you will modify the application to only allow for the creation
a
) h of
TimeDepositAccount instances with a maturity date that is 90 or 180 in the c m
ofuture.ideฺ

Tasks r a cle t Gu
o en
1. Open the EnumBanking project as the main project.te@ tud
a. Select File > Open Project. i s t ra is S
d r aฺ e th
b. Browse to D:\labs\05-Advanced_Class_Design\practices. s
c. Select EnumBanking andle xanthe “Open
select t o uas Main Project” check box.
( a n s e
d. Click the Open Project
t r a te button.
l i c e
2. Expand the project
r a Is directories.
b lesee a report of all customers and their accounts.
3. Run the project.
na dnew JavaYou
f r a
should
eenum,
x
4. Create
e a n s DepositLength, in the com.example package.
A l
5. Code n t r a
- DepositLength enum.
the
n o
a. Declare a days field along with a corresponding constructor and getter method.
private int days;

private DepositLength(int days) {


this.days = days;
}

public int getDays() {


return days;
}
b. Create two DepositLength instances, THREE_MONTHS and SIX_MONTHS that call
the DepositLength constructor with values of 90 and 180 respectively.
6. Modify the TimeDepositAccount class to only accept DepositLength instances for the
constructor’s maturity date parameter.
a. Open the TimeDepositAccount.java file (under the com.example package).
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 16
b. Modify the existing constructor to receive an enum as the second parameter.
public TimeDepositAccount(double balance, DepositLength
duration) {
super(balance);
Calendar cal = Calendar.getInstance();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

cal.add(Calendar.DAY_OF_YEAR, duration.getDays());
this.maturityDate = cal.getTime();
}
7. Modify the EnumBankingMain class to create TimeDepositAccount instances using the
two DepositLength instances available.
a. Open the EnumBankingMain.java file (under the com.example package).
b. Within the initializeCustomers method, remove the code to create calendars.
c. Within the initializeCustomers method, modify the creation of all
TimeDepositAccount instances to use the DepositLength enum.
s a
customer.addAccount(new TimeDepositAccount(500.00,
)h a
DepositLength.SIX_MONTHS));
c m
o ideฺ
Note: Try using both the SIX_MONTHS and THREE_MONTHS c

le You
values. ucan also use
a static import to reduce the length of the statement. ora n t G
e @ u d e
r a t
8. Run the project. You should see a report of all customers and
S their
t accounts. It is now

maturity date. r a ฺista TimeDepositAccount


impossible to compile a line of code that creates
t h is with an invalid

a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 17
(Optional) Practice 5-4: Recognizing Nested Classes

Overview
In this practice, you will take an existing application and attempt to recognize the declaration
and use of various types of nested classes.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the nested class section of this lesson.

Summary
You have been given a small project that contains only two .java files. Although there are only
two .java files, there may be multiple Java classes being created.
Attempt to determine the number of classes being created.

Tasks
1. Open the NestedClasses project as the main project. s a
) h a
a. Select File > Open Project. m
ฺ c o d e ฺ
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
cle t Gu i
r a
c. Select NestedClasses and select the “Open as Main Project” check box.
o n
d. Click the Open Project button. e @ d e
t r a t S tu
2.
3.
Expand the project directories.
r a ฺis this
Run the project. You should see the output in the output window.
a n d use
4.
l e x
Count the number of classes created in the OuterClass.java file.
to
( a ns e
a. Open the OuterClass.java file (under the com.example package).
a t e c e
I s tr le li
b. Determine the total number of classes created in this file.

n d ra erab
c. Determine the total number of top-level classes created in this file.

x a n s f
d. Determine the total number of nested classes created in this file.
e
Al n-tra
e. Determine the total number of inner classes.
no
f. Determine the total number of member classes.
g. Determine the total number of local classes.
h. Determine the total number of anonymous classes.
i. Determine the total number of static nested classes.
Hint: Using the Files tab in NetBeans, you can see how many .class files are created by
looking in the build\classes folder for a project.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 18
(Optional) Solution 5-4: Recognizing Nested Classes

Overview
In this solution, you will take an existing application and review the number and types of nested
classes created within a single .java file.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the nested class section of this lesson.

Summary
You have been given a small project that contains only two .java files. Although there are only
two .java files, there may be multiple Java classes being created.
Review the number of classes being created.

Tasks
1. Open the NestedClasses project as the main project. s a
) h a
a. Select File > Open Project. m
ฺ c o d e ฺ
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
cle t Gu i
r a
c. Select NestedClasses and select the “Open as Main Project” check box.
o n
d. Click the Open Project button. e @ d e
t r a t S tu
2.
3.
Expand the project directories.
r a ฺis this
Run the project. You should see the output in the output window.
a n d use
4.
l e x
Open the OuterClass.java file (under the com.example package).
to
( a ns e
 Within the OuterClass.java file there are:
a t e c e
 10 classes
I s tr le li
n d ra erab
 1 top-level class

x a n s f
 9 nested classes
e
Al n-tra  8 inner classes
no  3 member classes
 2 local classes
 3 anonymous classes
 1 static nested class

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 19
 Classes are declared on the following lines within the OuterClasss.java file:
 line 3: top-level class
 line 10: local inner class
 line 22: anonymous local inner class
 line 32: anonymous inner class
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

 line 40: anonymous inner class


 line 48: member inner class
 line 62: static nested class
 line 72: member inner class
 line 74: member inner class
 line 77: local inner class
Hint: You can show line number in NetBeans by going to the View menu and enabling
Show Line Numbers.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 20
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G6:u
Lesson
@ o e n
Inheritance t e with d
tu Java
t r a S
r a ฺis this
Interfaces
a n d use
l e x to 6
Chapter
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 1
Practices for Lesson 6: Overview

Practices Overview
In these practices, you will use Java interfaces and apply design patterns.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 2
Practice 6-1: Summary Level: Implementing an Interface

Overview
In this practice, you will create an interface and implement that interface.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have reviewed the interface section of this lesson.

Summary
You have been given a project that contains an abstract class named Animal. You create a
hierarchy of animals that is rooted in the Animal class. Several of the animal classes
implement an interface named Pet, which you will create.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Tasks
1. Open the Pet project as the main project.
a. Select File > Open Project.
b. Browse to D:\labs\06-Interfaces\practices.
c. Select Pet and select the “Open as Main Project” check box.
d. Click the Open Project button.
2. Expand the project directories.
3. Run the project. You should see text displayed in the output window.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 3
4. Review the Animal and Spider classes.
a. Open the Animal.java file (under the com.example package).
b. Review the abstract Animal class. You will extend this class.
c. Open the Spider.java file (under the com.example package).
d. The Spider class is an example of extending the Animal class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

5. Create a new Java interface: Pet in the com.example package.


6. Code the Pet interface. This interface should include three method signatures:
 public String getName();
 public void setName(String name);
 public void play();
7. Create a new Java class: Fish in the com.example package.
8. Code the Fish class.
a. This class should:
 Extend the Animal class s a
 Implement the Pet interface ) h a
b. Complete this class by creating: c o m e ฺ
ฺ i d
 A String field called name
r a cle t Gu
 Getter and setter methods for the name field @ o e n
t e tu d
t r a
 A no-argument constructor that passes a value of 0 to the parent constructor
S
r a ฺis this
 A play() method that prints out "Just keep swimming."

a n d use
 An eat() method that prints out "Fish eat pond scum."
e x to
 A walk() method that overrides the Animal class walk method. It should first call
l
( a ns e
the super class walk method, and then print "Fish, of course, can't walk;
a t e c e
they swim."
I s tr le li
9. Create a new Java class: Cat in the com.example package.
n d ra erab
x n s f
10. Code the Cat class.
a
e
Al n-tra
a. This class should:

no
 Extend the Animal class
 Implement the Pet interface
b. Complete this class by creating:
 A String field called name
 Getter and setter methods for the name field
 A constructor that receives a name String and passes a value of 4 to the parent
constructor
 A no-argument constructor that passes a value of "Fluffy" to the other constructor
in this class
 A play() method that prints out name + " likes to play with string."
 An eat() method that prints out "Cats like to eat spiders and fish."

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 4
11. Modify the PetMain class.
a. Open the PetMain.java file (under the com.example package).
b. Review the main method. You should see the following lines of code:
Animal a;
//test a spider with a spider reference
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Spider s = new Spider();


s.eat();
s.walk();
//test a spider with an animal reference
a = new Spider();
a.eat();
a.walk();
c.Add additional lines of code to test the Fish and Cat classes that you created.
 Try using every constructor s a
) h a
 Experiment with using every reference type possible and determine which methods
o m
can be called with each type of reference. Use a Pet reference while testing the
c e ฺ
ฺ i d
Fish and Cat classes.
r a cle t Gu
d. Implement and test the playWithAnimal(Animal a) method.
@ o e n
t e tu d
 Determine whether the argument implements the Pet interface. If so, cast the
t r a S
r a ฺis this
reference to a Pet and invoke the play method. If not, print a message of "Danger!
Wild Animal".
a n d use
 Call the playWithAnimal(Animal a) method from within main, passing in each
l e x to
type of animal.
( a ns e
t e e
12. Run the project. You should see text displayed in the output window.
a c
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 5
Practice 6-1: Detailed Level: Implementing an Interface

Overview
In this practice, you will create an interface and implement that interface.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have reviewed the interface section of this lesson.

Summary
You have been given a project that contains an abstract class named Animal. You create a
hierarchy of animals that is rooted in the Animal class. Several of the animal classes
implement an interface named Pet, which you will create.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Tasks
1. Open the Pet project as the main project.
a. Select File > Open Project.
b. Browse to D:\labs\06-Interfaces\practices.
c. Select Pet and select the "Open as Main Project" check box.
d. Click the Open Project button.
2. Expand the project directories.
3. Run the project. You should see text displayed in the output window.

4. Review the Animal and Spider classes.


a. Open the Animal.java file (under the com.example package).
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 6
b. Review the abstract Animal class. You will extend this class.
c. Open the Spider.java file (under the com.example package).
d. The Spider class is an example of extending the Animal class.
5. Create a new Java interface: Pet in the com.example package.
6. Code the Pet interface. This interface should include three method signatures:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

public String getName();


public void setName(String name);
public void play();
7. Create a new Java class: Fish in the com.example package.
8. Code the Fish class.
a. This class should extend the Animal class and implement the Pet interface.
public class Fish extends Animal implements Pet
b. Complete this class by creating: a
 A String field called name. h a s
m )
private String name;
ฺ c o d e ฺ
 Getter and setter methods for the name field. cle t Gu i
o r a n
@Override
e @ d e
public String getName() {
t r a t S tu
return name;
r a ฺis this
}
a n d use
l e x to
( a ns e
@Override
a t e c e
public void
I s l e li
trsetName(String name) {

n d ra era=b name;
this.name
x}a n s f
e tra
Al  nA -no-argument constructor that passes a value of 0 to the parent constructor.
nopublic Fish() {
super(0);
}
 A play() method that prints out "Just keep swimming."
@Override
public void play() {
System.out.println("Just keep swimming.");
}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 7
 An eat() method that prints out "Fish eat pond scum."
@Override
public void eat() {
System.out.println("Fish eat pond scum.");
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

 A walk() method that overrides the Animal class walk method. It should first call
the super class walk method, and then print " Fish, of course, can't walk;
they swim."
@Override
public void walk() {
super.walk();
System.out.println("Fish, of course, can't walk; they
swim.");
}
s a
9. Create a new Java class: Cat in the com.example package.
)h a
10. Code the Cat class.
c m
o ideฺ

e interface.
a. This class should extend the Animal class and implement the
r a clPet t G u
public class Cat extends Animal implements
@ o Pet en
b. Complete this class by creating: r a t e S t ud
 A String field called name.
r a ฺist this
 Getter and setter methods forathe n u se
dname field.
 A constructor that receivesl e xa name String
to and passes a value of 4 to the parent
( a ns e
constructor.
a t e c e
I s tr le name)
public Cat(String li {
n d ra erab
super(4);
x a this.name
n s f = name;
e
Al }n-tra
no A no-argument constructor that passes a value of "Fluffy" to the other constructor
in this class.
public Cat() {
this("Fluffy");
}
 A play() method that prints out name + " likes to play with string."
@Override
public void play() {
System.out.println(name + " likes to play with string.");
}
 An eat() method that prints out "Cats like to eat spiders and fish."

11. Modify the PetMain class.


a. Open the PetMain.java file (under the com.example package).

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 8
b. Review the main method. You should see the following lines of code:
Animal a;
//test a spider with a spider reference
Spider s = new Spider();
s.eat();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s.walk();
//test a spider with an animal reference
a = new Spider();
a.eat();
a.walk();
c. Add additional lines of code to test the Fish and Cat classes that you created.
 Try using every constructor
 Experiment with using every reference type possible and determine which methods
can be called with each type of reference. Use a Pet reference while testing the
s a
Fish and Cat classes.
) h a
Pet p;
c o m e ฺ
ฺ i d
r a cle t Gu
Cat c = new Cat("Tom");
@ o e n
c.eat(); t e tu d
t r a S
c.walk();
r a ฺis this
c.play();
a n d use
a = new Cat();
l e x t o
a e
a.eat();
a.walk(); tra
te ( licens
r a Is ble
a n d fera Whiskers");
p = new Cat();

l e a n s
p.setName("Mr.
xp.play();
A n-t r
no
Fish f = new Fish();
f.setName("Guppy");
f.eat();
f.walk();
f.play();
a = new Fish();
a.eat();
a.walk();

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 9
d. Implement and test the playWithAnimal(Animal a) method.
 Determine whether the argument implements the Pet interface. If so, cast the
reference to a Pet and invoke the play method. If not, print a message of "Danger!
Wild Animal".
public static void playWithAnimal(Animal a) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

if(a instanceof Pet) {


Pet p = (Pet)a;
p.play();
} else {
System.out.println("Danger! Wild Animal");
}
}
 Call the playWithAnimal(Animal a) method at the end of the main method,
passing in each type of animal. a
playWithAnimal(s); h a s
m )
playWithAnimal(c);
ฺ c o d e ฺ
playWithAnimal(f);
cle t Gu i
r a
12. Run the project. You should see text displayed in the outputowindow. n
t e @ tude
s a
tr is S
r ฺ i
a e th
d
an to us
e x
e ( al nse
s t r at lice
r a I
a b le
x a nd sfer
n
Ale n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 10
Practice 6-2: Summary Level: Applying the DAO Pattern

Overview
In this practice, you will take an existing application and refactor the code to implement the data
access object (DAO) design pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the DAO sections of this lesson.

Summary
You have been given a project that implements the logic for a human resources application. The
application allows for creating, retrieving, updating, deleting, and listing Employee objects.
Employee objects are currently stored in-memory using an array. You must move any code
related to the persistence of Employee objects out of the Employee class. In later practices,
you will supply alternative persistence implementations. In the future, this application should
require no modification when substituting the persistence implementation. s a
) h a
Tasks
c o m e ฺ
ฺ i d
1. Open the EmployeeMemoryDAO project as the main project.
r a cle t Gu
a. Select File > Open Project.
@ o e n
b. Browse to D:\labs\06-Interfaces\practices. t e tu d
t r a S
c. Select EmployeeMemoryDAO and selectฺithe
r a s "Open
e t hiass Main Project" check box.
d. Click the Open Project button. nd
2. Expand the project directories.lex
a to us
t e
3. Run the project. You should e se Test all the menu choices.
(asee a menu.
n
[C]reate Is
ra e |lic[U]pdate | [D]elete | [L]ist | [Q]uit:
| t[R]ead
r a a b l
x
Note:
a er dates, they should be in the form of: Nov 26, 1976
ndWhensfentering
A le Employee
- t r anIDs should be in the range of 0 through 9.
on the Employee class.
4. Review
n
a. Open the Employee.java file (under the com.example.model package).
b. Find the array used to store employees.
private static Employee[] employeeArray = new Employee[10];
Note: The employee’s id is used as the array index.
c. Locate any methods that utilize the employeeArray field. These methods are used to
persist employee objects.
5. Create a new com.example.dao package.
6. Create an EmployeeDAO interface in the com.example.dao package.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 11
7. Complete the EmployeeDAO interface with the following method signatures.
public void add(Employee emp);
public void update(Employee emp);
public void delete(int id);
public Employee findById(int id);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

public Employee[] getAllEmployees();


8. Create an EmployeeDAOMemoryImpl class in the com.example.dao package.
9. Complete the EmployeeDAOMemoryImpl class.
a. Move the employeeArray and any related methods from the Employee class to the
EmployeeDAOMemoryImpl class.
b. Implement the EmployeeDAO interface. Modify the methods that you moved in the
previous step to become the methods required by the EmployeeDAO interface.
Hint: In this DAO, the add and update methods will function the same.
10. Update the EmployeeTestInteractive class.
a. The EmployeeTestInteractive class no longer compiles, review the errors. s a
) h a
b. Create an EmployeeDAO instance in the main method. Use the EmployeeDAO m
interface as the reference type. ฺ c o d e ฺ
cle t Gu i
c. Modify any lines containing errors to use the EmployeeDAO instance.
o r a n
11. Run the project. You should see a menu. Test all the menu choices.
e @ d e
r a t S tu
Note: While functional, the EmployeeTestInteractive class is still tied to a specific
t
r a ฺis this
type of DAO because it references the EmployeeDAO implementing class by name.

a n d use
EmployeeDAO dao = new EmployeeDAOMemoryImpl();
l e xthis tighttocoupling from the
( classnsbyecreating a DAO factory.
In the following steps, you remove
t e a
EmployeeTestInteractive
s t r a l i ce interface.
r a I no-argument
12. Modify the EmployeDAOMemoryImpl
a b le
 Add a d
n protected,
f e r constructor.
a s
A lex an
13. Create
t r a n
EmployeeDAOFactory class in the com.example.dao package.

n o n- the EmployeeDAOFactory class.


14. Complete
 Add a method that returns an EmployeeDAO.
public EmployeeDAO createEmployeeDAO() {
return new EmployeeDAOMemoryImpl();
}
15. Update the EmployeeTestInteractive class to use the EmployeeDAOFactory class.
a. Obtain an EmployeeDAOFactory instance in the main method.
b. Obtain an EmployeeDAO instance using the factory created in the previous step.
16. Run the project. You should see a menu. Test all the menu choices.
In the future, you will be able to change the persistence mechanism to use a database
without changing the reference types or method calls used in the
EmployeeTestInteractive class.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 12
Practice 6-2: Detailed Level: Applying the DAO Pattern

Overview
In this practice, you will take an existing application and refactor the code to implement the data
access object (DAO) design pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the DAO sections of this lesson.

Summary
You have been given a project that implements the logic for a human resources application. The
application allows for creating, retrieving, updating, deleting, and listing Employee objects.
Employee objects are currently stored in-memory using an array. You must move any code
related to the persistence of Employee objects out of the Employee class. In later practices,
you will supply alternative persistence implementations. In the future, this application should
require no modification when substituting the persistence implementation. s a
) h a
Tasks
c o m e ฺ
ฺ i d
1. Open the EmployeeMemoryDAO project as the main project.
r a cle t Gu
a. Select File > Open Project.
@ o e n
b. Browse to D:\labs\06-Interfaces\practices. t e tu d
t r a S
c. Select EmployeeMemoryDAO and selectฺithe
r a s "Open
e t hiass Main Project" check box.
d. Click the Open Project button. nd
2. Expand the project directories.lex
a to us
t e
3. Run the project. You should e se Test all the menu choices.
(asee a menu.
n
[C]reate Is
ra e |lic[U]pdate | [D]elete | [L]ist | [Q]uit:
| t[R]ead
r a a b l
x
Note:
a er dates, they should be in the form of: Nov 26, 1976
ndWhensfentering
A le Employee
- t r anIDs should be in the range of 0 through 9.
on the Employee class.
4. Review
n
a. Open the Employee.java file (under the com.example.model package).
b. Find the array used to store employees. You will relocate this field in a subsequent
step.
private static Employee[] employeeArray = new Employee[10];
Note: The employee’s id is used as the array index.
c. Locate the save, delete, findById, and getAllEmployees methods that utilize
the employeeArray field. These methods are used to persist employee objects. You
will relocate these methods in a subsequent step.
5. Create a new com.example.dao package.
6. Create an EmployeeDAO interface in the com.example.dao package.
7. Complete the EmployeeDAO interface with the following method signatures. Add import
statements as needed.
public void add(Employee emp);
public void update(Employee emp);
public void delete(int id);
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 13
public Employee findById(int id);
public Employee[] getAllEmployees();
8. Create an EmployeeDAOMemoryImpl class in the com.example.dao package.
9. Complete the EmployeeDAOMemoryImpl class.
a. Move the employeeArray and any related methods from the Employee class to the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

EmployeeDAOMemoryImpl class:

s a
)h a
c m
o ideฺ

r a cle t Gu
@ o e n
b. Implement the EmployeeDAO interface. Modifyathe e
t methods d
tuthat you moved in the
t r S
previous step to become the methods required
r a ฺis this
by the EmployeeDAO interface.
 The save method becomes the add
n d methodu s eand is modified to have an Employee
parameter.
e x a to
 The save method is ( a l
duplicated s e
a t e c e n to become the update method and is modified to
I s tr le li
have an Employee parameter.
 The delete
d r a methodr a b is modified to have an id parameter.
x n findById
 aThe
n s fe method is no longer static.
e
Al  nThe
- a
trgetAllEmployees method is no longer static.
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 14
public class EmployeeDAOMemoryImpl implements EmployeeDAO {
private static Employee[] employeeArray = new Employee[10];

public void add(Employee emp) {


employeeArray[emp.getId()] = emp;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

public void update(Employee emp) {


employeeArray[emp.getId()] = emp;
}

public void delete(int id) {


employeeArray[id] = null;
}
s a
) h a
public Employee findById(int id) {
c o m e ฺ
ฺ i d
return employeeArray[id];
r a cle t Gu
}
@ o e n
t e tu d
t r a S
r a is this
ฺnew
public Employee[] getAllEmployees() {
List<Employee> emps
a n d useArrayList<>();
=
for (Employee
l e xe : employeeArray)
to {
a
if (e( != null) e
ns {
a t e c e
I s e li
tr lemps.add(e);
n d ra erab }

x a n}s f
e
Al n-tra return emps.toArray(new Employee[0]);
no }
}
10. Update the EmployeeTestInteractive class.
a. The EmployeeTestInteractive class no longer compiles, review the errors.
b. Create an EmployeeDAO instance in the main method. Use the EmployeeDAO
interface as the reference type. Replace the line:
//TODO create dao
With:
EmployeeDAO dao = new EmployeeDAOMemoryImpl();

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 15
c. Modify any lines containing errors to use the EmployeeDAO instance. For example:
case 'C':
emp = inputEmployee(in);
dao.add(emp);
System.out.println("Successfully added Employee Record: " +
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

emp.getId());
System.out.println("\n\nCreated " + emp);
break;
Note: You can also remove the now unnecessary finding of employee object that is
present when deleting an employee.
// Find this Employee record
emp = null;
emp = Employee.findById(id);
if (emp == null) {
s a
System.out.println("\n\nEmployee " + id + " not found");
)h a
break;
c m
o ideฺ

}
r a cle t Gu
11. Run the project. You should see a menu. Test all the menu o choices. en
t e @ t uisdstill tied to a specific
Note: While functional, the EmployeeTestInteractive
r a class
S
type of DAO because it references the EmployeeDAO
r a ฺist thimplementing
is class by name.
nd us
EmployeeDAO dao = new EmployeeDAOMemoryImpl(); e
e x a tocoupling from the
In the following steps, you remove
a l this tight
e
( classnsby creating a DAO factory.
EmployeeTestInteractive
r a t e i ce interface.
s t
12. Modify the EmployeDAOMemoryImpl l
a. Add d r
a protected, ble
a I rano-argument constructor.
a n s f e
xEmployeeDAOMemoryImpl()
n
Ale }n-tra
{

no an EmployeeDAOFactory class in the com.example.dao package.


13. Create
14. Complete the EmployeeDAOFactory class.
 Add a method that returns an EmployeeDAO.
public class EmployeeDAOFactory {

public EmployeeDAO createEmployeeDAO() {


return new EmployeeDAOMemoryImpl();
}
}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 16
15. Update the EmployeeTestInteractive class to use the EmployeeDAOFactory class.
a. Obtain an EmployeeDAOFactory instance in the main method. Replace the line:
//TODO create factory
With:
EmployeeDAOFactory factory = new EmployeeDAOFactory();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

b. Obtain an EmployeeDAO instance using the factory created in the previous step.
Replace the line:
EmployeeDAO dao = new EmployeeDAOMemoryImpl();
With:
EmployeeDAO dao = factory.createEmployeeDAO();
c. Fix any imports.
16. Run the project. You should see a menu. Test all the menu choices.
In the future, you will be able to change the persistence mechanism to use a database
s a
without changing the reference types or method calls used in the
) h a
EmployeeTestInteractive class. Notice that none of the *MemoryImpl classes are
m
used by name from within the EmployeeTestInteractive class. ฺ c o d e ฺ
cle t Gu i
o r a n
e @ d e
t r a t S tu
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 17
(Optional) Practice 6-3: Implementing Composition

Overview
In this practice, you will take an existing application and refactor it to make use of composition.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have reviewed the interface and composition sections of this lesson.

Summary
You have been given a small project that represents a hierarchy of animals that is rooted in the
Animal class. Several of the animal classes implement an interface named Pet. This project is
a completed implementation of the “Implementing an Interface” practice.
There are some potential problems with the design of the existing project. If you wanted to
restrict a pet’s name to less than 20 characters how many classes would you have to modify?
Would this problem become worse with the addition of new animals?
If some types of animals, such as Fish, cannot walk, should they have a walk method? s a
)h a
Tasks c m
o ideฺ

1. Open the PetComposition project as the main project.
r a cle t Gu
a. Select File > Open Project.
@ o e n
t e tu d
b. Browse to D:\labs\06-Interfaces\practices.
t r a S
c. Select PetComposition and select the a s asthMain
ฺi"Open is Project" check box.
r
d us e
d. Click the Open Project button. an
2. Expand the project directories. l e x to
a
( see output e
ns in the output window.
3. Run the project. Youa t e
should
c e
I s
4. Centralize all “name” l e li
tr functionality.
d
All petsncan
a named,
rbe b you may want to give names to objects that cannot play. For
rabut
xa you f e
s name a volleyball “Wilson.” Your design should reflect this.
instance,
l e r a n
could
Aa. Create
o n -t a Nameable interface (under the com.example package).
b.n Complete the Nameable interface with setName and getName method signatures.
public interface Nameable {

public void setName(String name);

public String getName();

}
c. Create a NameableImpl class (under the com.example package).
d. Complete the NameableImpl class. It should:
 Implement the Nameable interface
 Contain a private String field called name
 Only accept names less than 20 characters in length
 Print "Name too long" if a name is too long
e. Modify the Pet interface.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 18
 Extend the Nameable interface.
 Remove the getName and setName method signatures (they are inherited now).
f. Modify the Fish and Cat classes to use composition.
 Delete the name field.
 Delete the existing getName and setName methods.
 Add a new Nameable field.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

private Nameable nameable = new NameableImpl();


 Add getName and setName methods that delegate to the Nameable field.
Hint: Position the cursor within the curly braces for the class. Open the Source
menu, select Insert Code, select Delegate Method, select the Nameable check
box, and click the Generate button.
 Replace any use of the old name field with calls to the getName and setName
methods.
5. Centralize all walking functionality.
Only some animal can walk. Remove the walk method from the Animal class and use s a
interfaces and composition to facilitate walking. )h a
a. Create an Ambulatory interface (under the com.example package). c m
o ideฺ

b. Complete the Ambulatory interface with the walk method
r a cle t Gu
signature.
@ o e n
public interface Ambulatory {
t e tu d
t r a S
public void walk();
r a ฺis this
a n d use
}
l e x t o
c. Create an AmbulatoryImpl ( a e
ns (under the com.example package).
class
a t e
r e li
d. Complete the tAmbulatoryImpl c e class. It should:
I s b l
n draa private
 Implement
 aContain
the Ambulatory
f e raint field
interface
called
e x n s legs
trafielda single argument constructor that receives an int value to be stored in the
Al  nContain
-
no Contain a walk method
legs

public void walk() {


System.out.println("This animal walks on " + legs + "
legs.");
}
e. Delete the walk method from the Fish class.
f. Modify the Spider and Cat classes to use composition.
 Add a new Ambulatory field.
private Ambulatory ambulatory;
 Add a walk method that delegates to the Ambulatory field.
Hint: Position the cursor within the curly braces for the class. Open the Source
menu, select Insert Code, select Delegate Method, select the Ambulatory check
box, and click the Generate button.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 19
g. Initialize the ambulatory field within the Spider and Cat constructors. For example:
public Spider() {
ambulatory = new AmbulatoryImpl(8);
}
6. Modify the PetMain class to test the walk method. The walk method can only be called
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

on Spider, Cat, or Ambulatory references.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 20
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G7:u
Lesson
@ o e n
Generics e
t and d
tuCollections
t r a S
r a ฺis 7 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 1
Practices for Lesson 7: Overview

Practices Overview
In these practices, use generics and collections to practice the concepts covered in the lecture.
For each practice, a NetBeans project is provided for you. Complete the project as indicated in
the instructions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 2
Practice 7-1: Summary Level: Counting Part Numbers by Using
HashMaps

Overview
In this practice, use the HashMap collection to count a list of part numbers.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the collections section of this lesson.

Summary
You have been asked to create a simple program to count a list of part numbers that are of an
arbitrary length. Given the following mapping of part numbers to descriptions, count the number
of each part. Produce a report that shows the count of each part sorted by the part’s product
description. The part-number-to-description mapping is as follows:
Part Number
s Description a
1S01 Blue Polo Shirt ) h a
c o m e ฺ
1S02 Black Polo Shirt ฺ
le Gu i d
1H01 Red Ball Cap rac t
@ o e n
1M02 Duke Mug
r a t e Stud
r a ฺist this
Once complete, your report should look like
a n dthis: use
=== Product Report l=== e x to
a e
(Shirt ns Count: 6
Name: Black Polo
r a t e i ce Count: 7
Name: Blue
I s tPolo
le l
Shirt
Name:ra
d Duke Mug r a b Count: 3
n
a Red
xName: f e
s Ball Cap
l e r a n Count: 5
A n-t
no
Tasks
Open the Generics-Practice01 project and make the following changes.
1. For the ProductCounter class, add two private map fields. The first map counts part
numbers. The order of the keys does not matter. The second map stores the mapping of
product description to part number. The keys should be sorted alphabetically by description
for the second map.
2. Create a one argument constructor that accepts a Map as a parameter. The map that stores
the description-to-part-number mapping should be passed in here.
3. Create a processList() method to process a list of String part numbers. Use a HashMap
to store the current count based on the part number.
public void processList(String[] list){ }

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 3
4. Create a printReport() method to print out the results.
public void printReport(){ }
5. Add code to the main method to print out the results.
6. Run the ProductCounter.java class to ensure that your program produces the desired
output.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 4
Practice 7-1: Detailed Level: Counting Part Numbers by Using
HashMaps

Overview
In this practice, use the HashMap collection to count a list of part numbers.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the collections section of this lesson.

Summary
You have been asked to create a simple program to count a list of part numbers that are of an
arbitrary length. Given the following mapping of part numbers to descriptions, count the number
of each part. Produce a report that shows the count of each part sorted by the part’s product
description. The part number to description mapping is as follows:
Part Number
s Description a
1S01 Blue Polo Shirt ) h a
c o m e ฺ
1S02 Black Polo Shirt ฺ
le Gu i d
1H01 Red Ball Cap rac t
@ o e n
1M02 Duke Mug
r a t e Stud
r a ฺist this
Once complete, your report should look like
a n dthis: use
=== Product Report l=== e x to
a e
(Shirt ns Count: 6
Name: Black Polo
r a t e i ce Count: 7
Name: Blue
I s tPolo
le l
Shirt
Name:ra
d Duke Mug r a b Count: 3
n
a Red
xName: f e
s Ball Cap
l e r a n Count: 5
A n-t
no
Tasks
Open the Generics-Practice01 project and make the following changes.
1. For the ProductCounter class, add two private map fields. The first map counts part
numbers. The order of the keys does not matter. The second map stores the mapping of
product description to part number. The keys should be sorted alphabetically by description
for the second map.
private Map<String, Long> productCountMap = new HashMap<>();
private Map<String, String> productNames = new TreeMap<>();

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 5
2. Create a one argument constructor that accepts a Map as a parameter.
public ProductCounter(Map productNames){
this.productNames = productNames;
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

3. Create a processList() method to process a list of String part numbers. Use a


HashMap to store the current count based on the part number.
public void processList(String[] list){
long curVal = 0;
for(String itemNumber:list){
if (productCountMap.containsKey(itemNumber)){
curVal = productCountMap.get(itemNumber);
curVal++; s a
productCountMap.put(itemNumber, new ) h a
Long(curVal));
c o m e ฺ
ฺ i d
} else {
r a cle t Gu
o
productCountMap.put(itemNumber,new Long(1));
@ e n
t e tu d
}
t r a S
}
r a ฺis this
}
a n d use
l e x to
( a ns e
a t e c e
s tr lemethod
4. Create a printReport()
I li to print out the results.
n d ra evoid
public
f rab printReport(){
l e xa ranSystem.out.println("===
s Product Report ===");
A n-t for (String key:productNames.keySet()){
no System.out.print("Name: " + key);
System.out.println("\t\tCount: " +
productCountMap.get(productNames.get(key)));
}
}

5. Add the following code to the main method to print out the results.
ProductCounter pc1 = new ProductCounter (productNames);
pc1.processList(parts);
pc1.printReport();

6. Run the ProductCounter.java class to ensure that your program produces the desired
output.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 6
Practice 7-2: Summary Level: Matching Parentheses by Using a
Deque

Overview
In this practice, you use the Deque object to match parentheses in a programming statement.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the collections section of this lesson.

Summary
Use the Deque data structure as a stack to match parentheses in a programming statement.
You will be given several sample lines containing logical statements. Test the lines to ensure
that the parentheses match, return true if they do, false if they do not.

For example, the output from the program might look like the following.
s a
Line 0 is valid
)h a
Line 1 is invalid
c m
o ideฺ

Line 2 is invalid
r a cle t Gu
Line 3 is valid
@ o e n
t e tu d
t r a S
Tasks r a ฺis this
a n d use
Open the Generics-Practice02 project
l e x andtomake the following changes.
1. Modify the processLine()
t e (amethodnsineParenMatcher.java to read a line in and convert
the string into a character
s t r a array.
l i ce
2. Loop throughathe
r a le “(“ onto the stack. When a “)” is encountered, pop a “(“ from
I array. bPush
the stack.
x a s f er should return false.
ndTwo conditions
Aa.le Ifdonyou
- an to call a pop operation and the stack is empty, the number of parentheses
trneed
not match, return false.
n o
b. If after completing the loop a “(“ is left on the stack return false. The number of
parentheses does not match.
3. Run the ParanMatcher.java class to ensure that your program produces the desired
output.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 7
Practice 7-2: Detailed Level: Matching Parentheses by Using a Deque

Overview
In this practice, you use the Deque object to match parentheses in a programming statement.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have reviewed the collections section of this lesson.

Summary
Use the Deque data structure as a stack to match parentheses in a programming statement.
You will be given several sample lines containing logical statements. Test the lines to ensure
that the parentheses match, return true if they do, false if they do not.

For example, the output from the program might look like the following.
Line 0 is valid
s a
Line 1 is invalid
)h a
Line 2 is invalid
c m
o ideฺ

Line 3 is valid
r a cle t Gu
@ o e n
t e tu d
Tasks t r a S
Open the Generics-Practice02 project d r
and e his changes.
ฺis the tfollowing
amake
1. Modify the processLine() method x t o us
anin ParenMatcher.java to read a line in and convert
( a l e
the string into an array of characters. e
Clear the stack and convert the line to a character
array. t e e n s
I s tra le lic
ra curLinerab = line.toCharArray();
stack.clear();
n d f e
l e xa rans
A n-t
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 8
2. In the same method, loop through the array. Push “(” onto the stack. When a “)” is
encountered, pop a “(” from the stack. If “(” is left on the stack, or you attempt to perform a
pop operation on an empty stack, the parentheses do not match, return false. Otherwise,
return true. To do this, add the following code to the processLine method (replace the
return true; statement).
for (char c:curLine){
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

switch (c){
case '(':stack.push(c);break;
case ')':{
if (stack.size() > 0){
stack.pop();
} else {
return false;
}
s a
break;
)h a
}
c m
o ideฺ

cle t Gu
}
}
o r a n
e @ d e
if (stack.size()> 0){
t r a t S tu
ฺis this
return false; // Missing match invalid expression
} else { r a
d use
x a
return true; // n
a l e e to
}
t e ( nsto ensure that your program produces the desired
a
tr le li
3. Run the ParanMatcher.java c e
class
output. I s
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 9
Practice 7-3: Summary Level: Counting Inventory and Sorting by
Using Comparators

Overview
In this practice, you process shirt-related transactions for a Duke’s Choice store. Compute the
inventory level for a number of shirts. Then print out the shirt data sorted by description and by
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

inventory count.

Assumptions
You have reviewed all the content in this lesson.

Summary
Any Duke’s Choice stores carry a number of products including shirts. In this practice, process
the shirt-related transactions and calculate the inventory levels. After the levels have been
calculated, print a report sorted by description and a report sorted by inventory count. You will
s
create two classes that implement the Comperator interface to allow sorting shirts by count and a
by description. ) h a
For example, the output from the program might look like the following. c o m e ฺ
ฺ i d
=== Inventory Report - Description ===
r a cle t Gu
Shirt ID: P002
@ o e n
t e tu d
Description: Black Polo Shirt
t r a S
Color: Black
r a ฺis this
Size: M
a n d use
Inventory: 15 l e x to
( a ns e
a t e c e
Shirt ID:sP001
I tr le li
d ra eraBlue
Description: b Polo Shirt
a n
xColor: s f
l e r a n
Blue
A Size:
o n -t L
n Inventory: 24
Shirt ID: P003
Description: Maroon Polo Shirt
Color: Maroon
Size: XL
Inventory: 20

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 10
Shirt ID: P004
Description: Tan Polo Shirt
Color: Tan
Size: S
Inventory: 19
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

=== Inventory Report - Count ===


Shirt ID: P002
Description: Black Polo Shirt
Color: Black
Size: M
Inventory: 15

Shirt ID: P004


s a
Description: Tan Polo Shirt
) h a
Color: Tan
c o m e ฺ
ฺ i d
Size: S
r a cle t Gu
Inventory: 19
@ o e n
t e tu d
t r a S
Shirt ID: P003
r a ฺis this
Description: Maroon Polo Shirt
a n d use
Color: Maroon
l e x to
Size: XL ( a ns e
Inventory: t20 a t e
r e li c e
a I s b l
r
nd ID:sfP001er a
x a
Shirt

- t an
Ale Description:
r Blue Polo Shirt
n
noColor: Blue
Size: L
Inventory: 24

Tasks
Open the Generics-Practice03 project and make the following changes.
1. Review the Shirt class and InventoryCount interface to see how the Shirt class has
changed to support inventory features.
2. Review the DukeTransaction class to see how transactions are defined for this program.
3. Update the SortShirtByCount Comparator class to sort shirts by count.
4. Update the SortShirtByDesc Comparator class to sort shirts by description.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 11
5. Update the TestItemCounter class to process the shirts and transactions and produce
the desired report.
 Loop through the transactions and update the appropriate shirt object contained in the
polos map.
 Each Shirt class implements the InventoryCount interface. Use those methods and
the count field to increment and decrement the inventory levels.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

 Print the list of shirts by description.


 Print the list of shirts by count
6. Run the TestItemCounter.java class to ensure that your program produces the desired
output.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 12
Practice 7-3: Detailed Level: Counting Inventory and Sorting by Using
Comparators

Overview
In this practice, you process shirt-related transactions for a Duke’s Choice store. Compute the
inventory level for a number of shirts. Then print out the shirt data sorted by description and by
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

inventory count.

Assumptions
You have reviewed all the content in this lesson.

Summary
Any Duke’s Choice stores carry a number of products including shirts. In this practice, process
the shirt-related transactions and calculate the inventory levels. Once the levels have been
calculated print a report sorted by description and a report sorted by inventory count. You will
s
create two classes that implement the Comperator interface to allow sorting shirts by count and a
by description. ) h a
For example, the output from the program might look like the following. c o m e ฺ
ฺ i d
=== Inventory Report - Description ===
r a cle t Gu
Shirt ID: P002
@ o e n
t e tu d
Description: Black Polo Shirt
t r a S
Color: Black
r a ฺis this
Size: M
a n d use
Inventory: 15 l e x to
( a ns e
a t e c e
Shirt ID:sP001
I tr le li
d ra eraBlue
Description: b Polo Shirt
a n
xColor: s f
l e r a n
Blue
A Size:
o n -t L
n Inventory: 24
Shirt ID: P003
Description: Maroon Polo Shirt
Color: Maroon
Size: XL
Inventory: 20

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 13
Shirt ID: P004
Description: Tan Polo Shirt
Color: Tan
Size: S
Inventory: 19
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

=== Inventory Report - Count ===


Shirt ID: P002
Description: Black Polo Shirt
Color: Black
Size: M
Inventory: 15

Shirt ID: P004


s a
Description: Tan Polo Shirt
) h a
Color: Tan
c o m e ฺ
ฺ i d
Size: S
r a cle t Gu
Inventory: 19
@ o e n
t e tu d
t r a S
Shirt ID: P003
r a ฺis this
Description: Maroon Polo Shirt
a n d use
Color: Maroon
l e x to
Size: XL ( a ns e
Inventory: t20 a t e
r e li c e
a I s b l
r
nd ID:sfP001er a
x a
Shirt

- t an
Ale Description:
r Blue Polo Shirt
n
noColor: Blue
Size: L
Inventory: 24

Tasks
Open the Generics-Practice03 project and make the following changes.
1. Review the Shirt class and InventoryCount interface to see how the Shirt class has
changed to support inventory features.
2. Review the DukeTransaction class to see how transactions are defined for this program.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 14
3. Update the SortShirtByCount Comparator class to sort shirts by count.
public class SortShirtByCount implements Comparator<Shirt>{
public int compare(Shirt s1, Shirt s2){
Long c1 = new Long(s1.getCount());
Long c2 = new Long(s2.getCount());
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

return c1.compareTo(c2);
}
}

4. Update the SortShirtByDesc Comparator class to sort shirts by description.


public class SortShirtByDesc implements Comparator<Shirt>{
public int compare(Shirt s1, Shirt s2){
return
s a
s1.getDescription().compareTo(s2.getDescription());
)h a
}
c m
o ideฺ

}
r a cle t Gu
@ o e n
e u
5. Update the TestItemCounter class to process thetshirts andttransactions d and produce
t r a S
the desired report.
r a is this
ฺthe
nd count
 Loop through the transactions and update
u e
sappropriate shirt object contained in the
polos Map. This will produce x anainventory for each product.
a l e e to
// Count the shirts
t e ( ns
a
tr le li
for (DukeTransaction c e
transaction:transactions){
I s
n d ra erab
if (polos.containsKey(transaction.getProductID())){

x a n s f
currentShirt = polos.get(transaction.getProductID());
e
Al n-t}raelse {
no } System.out.println("Error: Invalid part number");
switch (transaction.getTransactionType()) {
case "Purchase":currentShirt.
addItems(transaction.getCount()); break;

case "Sale":currentShirt.
removeItems(transaction.getCount()); break;

default: System.out.println("Error: Invalid Transaction


Type"); continue;
}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 15
 Print the list of shirts by description.
// Convert to List
List<Shirt> poloList = new ArrayList<>(polos.values());

// Init Comparators
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Comparator sortDescription = new SortShirtByDesc();


Comparator sortCount = new SortShirtByCount();

// Print Results - Sort by Description


Collections.sort(poloList, sortDescription);
System.out.println("=== Inventory Report - Description ===");

for(Shirt shirt:poloList){
System.out.println(shirt.toString());
s a
}
)h a
c m
o ideฺ

r a cle t Gu
 Print the list of shirts by count.
@ o e n
// Print Results - Sort by Count at e tu d
t r S
Collections.sort(poloList, sortCount);
r a ฺis this
System.out.println("=== n
a d useReport - Count ===");
Inventory
l e x to
( a ns e
t e
for(Shirt shirt:poloList){
a c e
I s tr le li
System.out.println(shirt.toString());
} dra
n f e rab
6. Run
e a TestItemCounter.java
xthe n s class to ensure that your program produces the desired
l
Aoutput.n-t r a
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 16
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
)h a
c m
o ideฺ

Practices for r a cle t G8:u String
Lesson
@ o e n
Processing t e tu d
t r a S
r a ฺis 8 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 1
Practices for Lesson 8: Overview

Practices Overview
In these practices, you use regular expressions and String.split() to manipulate strings in
Java. For each practice, a NetBeans project is provided for you. Complete the project as
indicated in the instructions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 2
Practice 8-1: Summary Level: Parsing Text with split()

Overview
In this practice, parse comma-delimited text and convert the data into Shirt objects.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have participated in the lecture for this lesson.

Summary
You have been given some comma-delimited shirt data. Parse the data, store it in shirt objects,
and print the results. The output from the program should look like the following.

=== Shirt List ===


Shirt ID: S001
Description: Black Polo Shirt
s a
Color: Black ) h a
Size: XL
c o m e ฺ
ฺ i d
r a cle t Gu
Shirt ID: S002
@ o e n
t e tu d
Description: Black Polo Shirt
t r a S
Color: Black
r a ฺis this
Size: L
a n d use
l e x to
Shirt ID: S003 e (
a ns e
a t c e
li Shirt
tr Bluele Polo
I s
Description:
d
Color:
n raBlueerab
e x a XLnsf
Size:
Al n-tra
noShirt ID: S004
Description: Blue Polo Shirt
Color: Blue
Size: M

Shirt ID: S005


Description: Tan Polo Shirt
Color: Tan
Size: XL

Shirt ID: S006


Description: Black T-Shirt
Color: Black
Size: XL

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 3
Shirt ID: S007
Description: White T-Shirt
Color: White
Size: XL
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Shirt ID: S008


Description: White T-Shirt
Color: White
Size: L

Shirt ID: S009


Description: Green T-Shirt
Color: Green
Size: S
s a
) h a
Shirt ID: S010
c o m e ฺ
ฺ i d
Description: Orange T-Shirt
r a cle t Gu
Color: Orange
@ o e n
Size: S t e tu d
t r a S
r a ฺis this
Shirt ID: S011
a n d use
Description: Maroon Polo
l e x to
Shirt
Color: Maroon ( a ns e
a t e c e
Size: S
I s tr le li
n d ra erab
Tasks x a n s f
e
Al n-tra
Open the StringsPractice01 project and make the following changes.
n o
1. Edit the main method of the StringSplitTest.java file.
2. Parse each line of the shirts array.
3. Convert the shirt data into a List of Shirt objects.
4. Print out the list of shirts.
5. Run the StringSplitTest.java file and verify that your output is similar to that shown
in the “Summary” section of this practice.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 4
Practice 8-1: Detailed Level: Parsing Text with split()

Overview
In this practice, parse comma-delimited text and convert the data into Shirt objects.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have participated in the lecture for this lesson.

Summary
You have been given some comma-delimited shirt data. Parse the data, store it in shirt objects,
and print the results. The output from the program should look like the following.

=== Shirt List ===


Shirt ID: S001
Description: Black Polo Shirt
s a
Color: Black ) h a
Size: XL
c o m e ฺ
ฺ i d
r a cle t Gu
Shirt ID: S002
@ o e n
t e tu d
Description: Black Polo Shirt
t r a S
Color: Black
r a ฺis this
Size: L
a n d use
l e x to
Shirt ID: S003 e (
a ns e
a t c e
li Shirt
tr Bluele Polo
I s
Description:
d
Color:
n raBlueerab
e x a XLnsf
Size:
Al n-tra
noShirt ID: S004
Description: Blue Polo Shirt
Color: Blue
Size: M

Shirt ID: S005


Description: Tan Polo Shirt
Color: Tan
Size: XL

Shirt ID: S006


Description: Black T-Shirt
Color: Black
Size: XL

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 5
Shirt ID: S007
Description: White T-Shirt
Color: White
Size: XL
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Shirt ID: S008


Description: White T-Shirt
Color: White
Size: L

Shirt ID: S009


Description: Green T-Shirt
Color: Green
Size: S
s a
) h a
Shirt ID: S010
c o m e ฺ
ฺ i d
Description: Orange T-Shirt
r a cle t Gu
Color: Orange
@ o e n
Size: S t e tu d
t r a S
r a ฺis this
Shirt ID: S011
a n d use
Description: Maroon Polo
l e x to
Shirt
Color: Maroon ( a ns e
a t e c e
Size: S
I s tr le li
n d ra erab
Tasks x a n s f
e
Al n-tra
Open the StringsPractice01 project and make the following changes.
n o
1. Edit the main method of the StringSplitTest.java file.
2. Parse each line of the shirts array. Create a Shirt object for each line and add the
Shirt to a List. A for loop to perform these steps could be as follows:
for(String curLine:shirts){
String[] e = curLine.split(",");
shirtList.add(new Shirt(e[0], e[1], e[2], e[3]));
}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 6
3. Print out the list of shirts. A loop to do this could be like the following:
System.out.println("=== Shirt List ===");
for (Shirt shirt:shirtList){
System.out.println(shirt.toString());
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

4. Run the StringSplitTest.java file and verify that your output is similar to that shown
in the “Summary” section of this practice.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 7
Practice 8-2: Summary Level: Creating a Regular Expression Search
Program

Overview
In this practice, create a program that searches a text file by using regular expressions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have participated in the lecture for this lesson.

Summary
Create a simple application that will loop through a text file (gettys.html) and search for text
by using regular expressions. If the desired text is found on a line, print out the line number and
the line text. For example, if you performed a search for “<h4>” the output would be:
9 <h4>Abraham Lincoln</h4>
10 <h4>Thursday, November 19, 1863</h4>
s a
)h a
c m
o ideฺ
Tasks ฺ
le Gu
Open the StringsPractice02 project and make the followingochanges. rac nPleaset note that the
code to read a file has been supplied for you. @
e Stud e
r a t
Note: The gettys.html file is located in the rootis
the project open, click the Files tab. Double-click r a ฺtheoftfile h is folder.
the project
totopen
To examine the file, with
it and examine its contents.
1. Edit the FindText.java file. xan
d use
a l e e to
2. Create a Pattern and a Matcher
t e ( s
field.
nsupplied
3. Generate a Matcher a
tr le li
based on c e
the Pattern object.
4. Search each
I s
aline for rthe bpattern supplied.
d r a
5. Print a
x nline number
the
n s fe and the line that has matching text.
e tra
l the-FindText.java
6. ARun file and search for these patterns.
n
o lines that contain: <h4>
 nAll
 All the lines that contain the word “to” (For example, line 17 should not be selected.)
 All the lines that contain ‘class=”line”’
 All the lines that contain a pair of brackets “{ }”
 Lines that begin with “<p” or “<d”
 Lines that only contain HTML closing tags (for example, “</div>”)
7. (Optional) Modify the program to accept the file name and regular expression pattern on the
command line.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 8
Practice 8-2: Detailed Level: Creating a Regular Expression Search
Program

Overview
In this practice, create a program that searches a text file by using regular expressions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have participated in the lecture for this lesson.

Summary
Create a simple application that will loop through a text file and search for text by using regular
expressions. If the desired text is found on a line, print out the line number and the line text. For
example, if you performed a search for “<h4>” the output would be:
9 <h4>Abraham Lincoln</h4>
10 <h4>Thursday, November 19, 1863</h4>
s a
)h a
c m
o ideฺ
Tasks ฺ
le Gu
Open the StringsPractice02 project and make the followingochanges. rac nPleaset note that the
code to read a file has been supplied for you. @
e Stud e
r a t
Note: The gettys.html file is located in the root s
r a
the project open, click the Files tab. Double-click
ioftfile
ฺthe the project
h is folder.
totopen
To examine the file, with
it and examine its contents.
1. Edit the FindText.java file. xan
d use
2. Create fields for a Pattern(a lea Matcher
and e toobject.
privatetra
te pattern;
Patternlic ens
r a Is Matcher
b le m;
private
nd sfer a
x a n loop, create and initialize your pattern object.
le -the
3. AOutside t r asearch
non pattern = Pattern.compile("<h4>");
4. Inside the search loop, generate a Matcher based on the supplied Pattern object.
m = pattern.matcher(line);

5. Inside the search loop, search each line for the pattern supplied. Print the line number and
the line that has matching text.
if (m.find()) {
System.out.println(" " + c + " "+ line);
}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 9
6. Run the FindText.java file and search for these patterns.
 All the lines that contain: <h4>
pattern = Pattern.compile("<h4>");
 All the lines that contain the word “to” (For example, line 17 should not be selected.)
pattern = Pattern.compile("\\bto\\b");
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

 All the lines that start with 4 spaces


pattern = Pattern.compile("^\\s{4}");
 Lines that begin with “<p” or “<d”
pattern = Pattern.compile("^<[p|d]");
 Lines that only contain HTML closing tags (for example, “</div>”)
pattern = Pattern.compile("^</.*?>$");
7. (Optional) Modify the program to accept the file name and regular expression pattern on the
command line.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 10
Practice 8-3: Summary Level: Transforming HTML by Using Regular
Expressions
Overview
In this practice, use regular expressions to transform <p> tags into <span> tags.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have participated in the lecture for this lesson.
Summary
You have decided that you want to change the formatting of the gettys.html file. Instead of
using <p> tags, <span> tags should be used. In addition, you think that the value for class
should be “sentence” instead of “line.” Use regular expressions to find the lines that you want to
change. Then use regular expressions to transform the tags and the attributes as described.
The transformed lines should be output to the console. The output should look like the following:
13 <span class="sentence">Four score and seven years ago our
s a
fathers brought forth on this continent a new nation, conceived
) h a
in liberty, and dedicated to the proposition that all men are
c o m e ฺ
ฺ i d
cle t Gu
created equal.</span>
r a
14 <span class="sentence">Now we are engaged in a great civil
o n
@
war, testing whether that nation, or any nation, so conceived
e d e
and so dedicated, can long endure.</span>
t r a t S tu
r a ฺis this
15 <span class="sentence">We are met on a great battle-field of
that war.</span>
a n d use
e x to
16 <span class="sentence">We have come to dedicate a portion of
l
( a ns e
that field, as a final resting place for those who here gave
a t e c e
I s tr le li
their lives that that nation might live.</span>

ra erab
17 <span class="sentence">It is altogether fitting and proper

a n d
that we should do this.</span>
f
e x n s
21 <span class="sentence">But, in a larger sense, we can not
Al n-tradedicate, we can not consecrate, we can not hallow this
no ground.</span>

One approach to the problem could be to break the algorithm into three steps.
1. Break the line into three parts: the start tag, the content, and the end tag.
2. Replace the current tags with a new tag.
3. Replace the attribute value with a new attribute value.
Then return the newly formatted line.
The method signatures to replace the tag and attributes might look like this:
public String replaceTag(String tag, String targetTag,
String replaceTag){ }
public String replaceAttribute(String tag, String attribute,
String value){

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 11
Tasks
Open the StringsPractice03 project and make the following changes. Please note that the
code to read a file has been supplied for you.
1. Edit the SearchReplace.java file.
2. Create a Pattern object to match the entire line.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

3. As you loop through the file, do the following:


 Create a Matcher to match the current line.
 Execute the find() method to find a match.
 If there is a match, replace the start and end tags.
 Replace the attribute
4. Create a method that will replace the contents of any tag.
5. Create a method that will replace a tag’s attribute.
6. Run the SearchReplace.java file and produce the output shown in the “Summary”
section of this practice.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 12
Practice 8-3: Detailed Level: Transforming HTML by Using Regular
Expressions
Overview
In this practice, use regular expressions to transform <p> tags into <span> tags.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have participated in the lecture for this lesson.
Summary
You have decided that you want to change the formatting of the gettys.html file. Instead of
using <p> tags, <span> tags should be used. In addition, you think that the value for class
should be “sentence” instead of “line.” Use regular expressions to find the lines that you want to
change. Then use regular expressions to transform the tags and the attributes as described.
The transformed lines should be output to the console. The output should look like the following:
13 <span class="sentence">Four score and seven years ago our
s a
fathers brought forth on this continent a new nation, conceived
) h a
in liberty, and dedicated to the proposition that all men are
c o m e ฺ
created equal.</span> ฺ i d
r a cle t Gu
14 <span class="sentence">Now we are engaged in a great civil
o
war, testing whether that nation, or any nation, so conceived
@ e n
t e tu d
and so dedicated, can long endure.</span>
t r a S
r a ฺis this
15 <span class="sentence">We are met on a great battle-field of
that war.</span>
a n d use
x to
16 <span class="sentence">We have come to dedicate a portion of
l e
( a ns e
that field, as a final resting place for those who here gave
a t e c e
their lives that that nation might live.</span>
I s tr le li
17 <span class="sentence">It is altogether fitting and proper
d ra erab
that we should do this.</span>
n
x a n s f
21 <span class="sentence">But, in a larger sense, we can not
e
Al n-tradedicate, we can not consecrate, we can not hallow this
no ground.</span>

One approach to the problem could be to break the algorithm into three steps.
1. Break the line into three parts: the start tag, the content, and the end tag.
2. Replace the current tags with a new tag.
3. Replace the attribute value with a new attribute value.
Then return the newly formatted line.
The method signatures to replace the tag and attributes might look like this:
public String replaceTag(String tag, String targetTag,
String replaceTag){ }
public String replaceAttribute(String tag, String attribute,
String value){

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 13
Tasks
Open the StringsPractice03 project and make the following changes. Please note that the
code to read a file has been supplied for you.
1. Edit the SearchReplace.java file.
2. Create a Pattern object to match the entire line.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Pattern pattern1 = Pattern.compile("(<" + targetTag +


".*?>)(.*?)(</" + targetTag + ".*?>)");

3. As you loop through the file, do the following:


 Create a Matcher to match the current line.

Matcher m = pattern1.matcher(line);
s a
 Execute the find() method to find a match. If there is a match, replace the
a
h and
) start
end tags. Replace the attribute c m
o ideฺ

r a cle t Gu
if (m.find()) {
@ o e n
t e u d
ttargetTag,
String newStart = replaceTag(m.group(1),
t r a S
replaceTag);
r a ฺis this
n d use
newStart = replaceAttribute(newStart,
a
attribute, value);
l e x to
String newEnd = replaceTag(m.group(3), targetTag, replaceTag);
( a ns e
a t e i c e
s tr le= lnewStart
String newLine
I + m.group(2) + newEnd;

d ra erab
System.out.printf("%3d
n
%s\n", c, newLine);
x}a rans f
l e
A n-t
no a method that will replace the contents of any tag.
4. Create

public String replaceTag(String tag, String targetTag, String


replaceTag){
Pattern p = Pattern.compile(targetTag); // targetTag is
regex
Matcher m = p.matcher(tag); // tag is text to replace
if (m.find()){
return m.replaceFirst(replaceTag); // swap target with
replace
}
return targetTag;
}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 14
5. Create a method that will replace a tag’s attribute.

public String replaceAttribute(String tag, String attribute,


String value){
Pattern p = Pattern.compile(attribute + "=" + "\".*?\"");
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Matcher m = p.matcher(tag); // tag is text to replace


if (m.find()){
return m.replaceFirst(attribute + "=" + "\"" + value +
"\"");
}
return tag;
}
6. Run the SearchReplace.java file and produce the output shown in the “Summary”
section of this practice. a
h a s
m )
ฺ c o d e ฺ
cle t Gu i
o r a n
e @ d e
t r a t S tu
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 15
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G9:u
Lesson
@ o e n
Exceptions t e and d
tu Assertions
t r a S
r a ฺis 9 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 1
Practices for Lesson 9: Overview

Practices Overview
In these practices, you will use try-catch statements, extend the Exception class, and use
the throw and throws keywords.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 2
Practice 9-1: Summary Level: Catching Exceptions

Overview
In this practice, you will create a new project and catch checked and unchecked exceptions.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have reviewed the exception handling section of this lesson.

Summary
You will create a project that reads from a file. The file-reading code will be provided to you.
Your task is to add the appropriate exception-handling code.

Tasks
1. Create a new ExceptionPractice project as the main project.
a. Select File > New Project. a
b. Select Java under Categories and Java Application under Projects. Click the Next a s
button. m )h
c. Enter the following information in the “Name and Location” dialog box: ฺ c o ideฺ
 Project Name: ExceptionPractice r a cle t Gu
@ o e n
 Project Location: D:\labs\09-Exceptions\practices.
t e tu d
t r a S
 (checked) Set as Main Project r a ฺis this
 (checked) Create Main Class: com.example.ExceptionMain

a n d use
d. Click the Finish button.
l e x to
2. ( a ns
Add the following line to the main method. e
a t e c e
s tr le li
System.out.println("Reading
I from file:" + args[0]);
ra eraargument
Note: A command-line
d b will be used to specify the file that will be read. Currently
a n
no arguments
x f
s be supplied, do not correct this oversight yet.
will
l e t r a n
3. ARun the-project. You should see an error message similar to:
o n
n Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at com.example.ExceptionMain.main(ExceptionMain.java:7)
Java Result: 1
4. Surround the println line of code you added with a try-catch statement.
 The catch clause should:
 Accept a parameter of type ArrayIndexOutOfBoundsException
 Print the message: "No file specified, quitting!"
 Exit the application with an exit status of 1 by using the appropriate static method
within the System class
Note: Because the compiler did not force you to handle or declare the
ArrayIndexOutOfBoundsException, it is an unchecked exception. Typically, you
should not need to use a try-catch block to deal with an unchecked exception.
Checking the length of the args array is an alternate way to ensure that a
command-line argument was supplied.
5. Run the project. You should see an error message similar to:
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 3
No file specified, quitting!
Java Result: 1
6. Add a command-line argument to the project.
a. Right-click the ExceptionPractice project and select Properties.
b. In the Project Properties dialog box, select the Run category.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

c. In the Arguments field, enter a value of:


D:\labs\resources\DeclarationOfIndependence.txt
d. Click the OK button.
7. Run the project. You should see a message similar to:
Reading from
file:D:\labs\resources\DeclarationOfIndependence.txt
Warning: Running the project is not the same as running the file. The command-line
argument will only be passed to the main method if you run the project.
8. Add the following lines of code to the main method below your previously added lines: a
a s
BufferedReader b =
m )h
new BufferedReader(new FileReader(args[0]));
ฺ c o ideฺ
String s = null;
r a cle t Gu
while((s = b.readLine()) != null) {
@ o e n
System.out.println(s); t e tu d
t r a S
}
r a ฺis this
9. Run the Fix Imports wizard by right-clicking
n d thein
u e
ssource-code window.
10. You should now see compiler errors e a
x in some
toof the lines that you just added. These lines
a l
( exceptions.e
potentially generate checked
cursor above the line a t e
with c
errors, e nsshould
you
By manually building the project or holding your
see a message similar to:
I s tr le li
r a toexception
unreported
d r a bthrownFileNotFoundException; must be caught or
e x an nsfe
declared be
11. Modify the
- a properties to support the try-with-resources statement.
Aa.l Right-click
trproject
no n the ExceptionPractice project and select Properties.
b. In the Project Properties dialog box, select the Sources category.
c. In the Source/Binary Format drop-down list, select JDK 7.
d. Click the OK button.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 4
12. Surround the file IO code provided in step 8 with a try-with-resources statement.
 The line that creates and initializes the BufferedReader should be an automatically
closed resource.
 Add a catch clause for a FileNotFoundException. Within the catch clause:
 Print "File not found:" + args[0]
 Exit the application.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

 Add a catch clause for an IOException. Within the catch clause:


 Print " Error reading file:" along with the message available in the
IOException object
 Exit the application.
13. Run the project. You should see the content of the
D:\labs\resources\DeclarationOfIndependence.txt file displayed in the output
window.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 5
Practice 9-1: Detailed Level: Catching Exceptions

Overview
In this practice, you will create a new project and catch checked and unchecked exceptions.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have reviewed the exception handling section of this lesson.

Summary
You will create a project that reads from a file. The file-reading code will be provided to you.
Your task is to add the appropriate exception-handling code.

Tasks
1. Create a new ExceptionPractice project as the main project.
a. Select File > New Project. a
b. Select Java under Categories and Java Application under Projects. Click the Next a s
button. m )h
c. Enter the following information in the “Name and Location” dialog box: ฺ c o ideฺ
 Project Name: ExceptionPractice r a cle t Gu
@ o e n
 Project Location: D:\labs\09-Exceptions\practices.
t e tu d
t r a S
 (checked) Set as Main Project r a ฺis this
 (checked) Create Main Class: com.example.ExceptionMain

a n d use
d. Click the Finish button.
l e x t o
2. ( a ns
Add the following line to the main method. e
a t e c e
s tr le li
System.out.println("Reading
I from file:" + args[0]);
ra eraargument
Note: A command-line
d b will be used to specify the file that will be read. Currently
a n
no arguments
x f
s be supplied; do not correct this oversight yet.
will
l e t r a n
3. ARun the-project. You should see an error message similar to:
o n
n Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at com.example.ExceptionMain.main(ExceptionMain.java:7)
Java Result: 1

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 6
4. Surround the println line of code you added with a try-catch statement.
 The catch clause should:
 Accept a parameter of type ArrayIndexOutOfBoundsException
 Print the message: "No file specified, quitting!"
 Exit the application with an exit status of 1 by using the System.exit(1) method
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

try {
System.out.println("Reading from file:" + args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No file specified, quitting!");
System.exit(1);
}
Note: Since the compiler did not force you to handle or declare the
ArrayIndexOutOfBoundsException it is an unchecked exception. Typically you
should not need to use a try-catch block to deal with an unchecked exception.
s a
Checking the length of the args array is an alternate way to ensure that a command
) h a
line argument was supplied.
c o m e ฺ
ฺ i d
5. Run the project. You should see an error message similar to:
r a cle t Gu
No file specified, quitting!
@ o e n
e d
rat is Stu
Java Result: 1
6. Add a command-line argument to the project.ฺist
a. Right-click the ExceptionPractice d r aproject and
e thclick Properties.
x n selectuthes Run category.
abox,
b. In the Project Properties dialog
a l e e to
c. In the Arguments field,
t e (enter a nvalue
s of:
a
tr le li c e
D:\labs\resources\DeclarationOfIndependence.txt
d. Click theaOK I sbutton.
7. Run the n d r You
project. f e ab see a message similar to:
rshould
e a
xReading n s
l -t r a
A file:D:\labs\resources\DeclarationOfIndependence.txt
from
n o n
Warning: Running the project is not the same as running the file. The command-line
argument will only be passed to the main method if you run the project.
8. Add the following lines of code to the main method below your previously added lines:
BufferedReader b =
new BufferedReader(new FileReader(args[0]));
String s = null;
while((s = b.readLine()) != null) {
System.out.println(s);
}
9. Run the Fix Imports wizard by right-clicking in the source-code window.
10. You should now see compiler errors in some of the lines that you just added. These lines
potentially generate checked exceptions. By manually building the project or holding your
cursor above the line with errors, you should see a message similar to:
unreported exception FileNotFoundException; must be caught or
declared to be thrown
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 7
11. Modify the project properties to support the try-with-resources statement.
a. Right-click the ExceptionPractice project and select Properties.
b. In the Project Properties dialog box, select the Sources category.
c. In the Source/Binary Format drop-down list, select JDK 7.
d. Click the OK button.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

12. Surround the file IO code provided in step 8 with a try-with-resources statement.
 The line that creates and initializes the BufferedReader should be an automatically
closed resource.
 Add a catch clause for a FileNotFoundException. Within the catch clause:
 Print "File not found:" + args[0]
 Exit the application.
 Add a catch clause for an IOException. Within the catch clause:
 Print " Error reading file:" along with the message available in the
IOException object
s a
 Exit the application.
)h a
try (BufferedReader b =
c m
o {ideฺ

new BufferedReader(new FileReader(args[0]));)
r a cle t Gu
String s = null;
@ o e n
e d
while((s = b.readLine()) != null)
System.out.println(s); str
at s Stu
{

r a ฺi
e t hi
}
x a nd e)us{
} catch(FileNotFoundException
a l e e tonot found:" + args[0]);
(
System.out.println("File
t e ns
a
tr le li
System.exit(1); c e
I s
a rab e) {
r
} catch(IOException
d
x n fe
an System.out.println("Error
s reading file:" + e.getMessage());
e ra
Al }n-tSystem.exit(1);
no
13. Run the project. You should see the content of the
D:\labs\resources\DeclarationOfIndependence.txt file displayed in the output
window.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 8
Practice 9-2: Summary Level: Extending Exception

Overview
In this practice, you will take an existing application and refactor the code to make use of a
custom exception class and a custom auto-closeable resource.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the exception handling section of this lesson.

Summary
You have been given a project that implements the logic for a human resources application. The
application allows for creating, retrieving, updating, deleting, and listing of Employee objects.
This is the same project that you completed in the “Applying the DAO Pattern” practice.
Currently the only exceptions generated by the DAO implementation
(EmployeeDAOMemoryImpl) are unchecked exceptions such as
s a
ArrayIndexOutOfBoundsException.
Future DAO implementations should not require any rewriting of the application logic ) h a
(EmployeeTestInteractive). However, some DAO implementations will generate checked
c o m e ฺ
ฺ i d
r a cle t Gu
exceptions that must be dealt with. By creating a custom checked exception class that will be
used to wrap any DAO generated exceptions, all DAO implementations can appear to generate
@ o e n
t e tu d
the same type of exception. This will completely eliminate the need to change any application
r a S
logic when you create database enabled DAO implementations in later practices.
t
r a ฺis this
Tasks
a n d use
1. Open the DAOException project l e xas the main
to project.
( a ns e
a e
a. Select File > OpentProject.
c e
s tr le li
b. Browse to D:\labs\09-Exceptions\practices.
I
c. Select d a rab and select the "Open as Main Project" check box.
rDAOException
n
a the nOpen
d.exClick s feProject button.
l
2. AExpand
n - traproject directories.
the
3. Runnothe project. You should see a menu. Test all the menu choices.
[C]reate | [R]ead | [U]pdate | [D]elete | [L]ist | [Q]uit:
4. Create a DAOException class in the com.example.dao package.
5. Complete the DAOException class. The DAOException class should:
 Extend the Exception class
 Contain four constructors with parameters matching those of the four constructors
present in the Exception class. For each constructor, use super() to invoke the
parent class constructor with matching parameters.
6. Modify the EmployeeDAO interface.
 All methods should declare that a DAOException may be thrown during execution.
 Extend the AutoCloseable interface.
7. Modify the add method within the EmployeeDAOMemoryImpl class to:
 Declare that a DAOException may be produced during execution of this method.
 Use an if statement to validate that an existing employee will not be overwritten by the
add. If one would, generate a DAOException and deliver it to the caller of the method.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 9
The DAOException should contain a message String indicating what went wrong and
why.
 Use a try-catch block to catch the ArrayIndexOutOfBoundsException
unchecked exception that could possibly be generated.
 Within the catch block that you just created, generate a DAOException and deliver it to
the caller of the method. The DAOException should contain a message String
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

indicating what went wrong and why.


Note: Checking the length of the employeeArray could be used to determine whether the
DAOException should be thrown. However, the use of a try-catch block will be typical
of the structure used when creating a database-enabled DAO.
8. Modify the update method within the EmployeeDAOMemoryImpl class to:
 Declare that a DAOException may be produced during execution of this method.
 Use an if statement to validate that an existing employee is being updated. If one would
not be, generate a DAOException and deliver it to the caller of the method. The
DAOException should contain a message String indicating what went wrong and why.
 Use a try-catch block to catch the ArrayIndexOutOfBoundsException s a
unchecked exception that could possibly be generated. ) h a
c o m e ฺ
 Within the catch block that you just created, generate a DAOException and deliver it to
ฺ i d
r a cle t Gu
the caller of the method. The DAOException should contain a message String
indicating what went wrong and why.
@ o e n
t e tu
9. Modify the delete method within the EmployeeDAOMemoryImpl class to:d
t r a S
r a ฺis this
 Declare that a DAOException may be produced during execution of this method.

a n d use
 Use an if statement to validate that an existing employee is being deleted. If one would
x to
not be, generate a DAOException and deliver it to the caller of the method. The
l e
( a e
DAOException should contain a message String indicating what went wrong and why.
ns
a t e c e
I s tr le li
 Use a try-catch block to catch the ArrayIndexOutOfBoundsException
unchecked exception that could possibly be generated.
n d ra erab
 Within the catch block that you just created, generate a DAOException and deliver it to
x a n s f
the caller of the method. The DAOException should contain a message String
e
Al n-tra
indicating what went wrong and why.
no
10. Modify the findById method within the EmployeeDAOMemoryImpl class to:
 Declare that a DAOException may be produced during execution of this method.
 Use a try-catch block to catch the ArrayIndexOutOfBoundsException
unchecked exception that could possibly be generated.
 Within the catch block that you just created, generate a DAOException and deliver it to
the caller of the method. The DAOException should contain a message String
indicating what went wrong and why.
11. Add a close method within the EmployeeDAOMemoryImpl class to implement the
AutoCloseable interface.
@Override
public void close() {
System.out.println("No database connection to close just
yet");
}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 10
Note: The EmployeeDAOMemoryImpl class implements EmployeeDAO which extends
AutoCloseable and, therefore, EmployeeDAOMemoryImpl class must provide a close
method.
12. Modify the EmployeeTestInteractive class to handle the DAOException objects that
are thrown by the EmployeeDAO.
a. Import the com.example.dao.DAOException class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

b. Modify the executeMenu method to declare that it throws an additional exception of


type DAOException.
c. Remove the throws statement from the main method.
public static void main(String[] args) throws Exception
d. Modify the main method to use a try-with-resources statement.
 Surround the do-while loop with a try block.
 Convert the EmployeeDAO and BufferedReader references into auto-closed
resources. a
a s
 Add a catch clause for an IOException to the end of the try block to handle both
m )h
I/O errors thrown from the executeMenu method and when auto-closing the
ฺ c o ideฺ
cle t Gu
BufferedReader.
catch (IOException e) {
o r a n
e @ u d e
a t
System.out.println("Error " + e.getClass().getName()
tr is S t +
" , quitting.");
ฺ i s
a "e+ the.getMessage());
System.out.println("Message:
d r
}
e x an to us
(
 Add a second catch clause
e al fornanseException to the end of the try block to handle
r at lithe
errors when tauto-closing
s ceEmployeeDAO.
catchra
I
(Exceptiona b lee) {
x a s er
ndSystem.out.println("Error
f closing resource " +
e ra n
Al n-tSystem.out.println("Message:
e.getClass().getName());

no} " + e.getMessage());

Note: At this point the application will compile and run, but DAOException instances
generated will cause the application to terminate. For example, if you create an
employee with an ID of 100, the application will break out of the do-while loop and
pass to this catch clause.
e. Add a nested try-catch block in the main method that handles exceptions of type
DAOException that may be thrown by the executeMenu method.
try {
timeToQuit = executeMenu(in, dao);
} catch (DAOException e) {
System.out.println("Error " + e.getClass().getName());
System.out.println("Message: " + e.getMessage());
}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 11
13. Run the project. You should see a menu. Test all the menu choices.
[C]reate | [R]ead | [U]pdate | [D]elete | [L]ist | [Q]uit:
Attempt to delete an employee that does not exist. You should see a message similar to:
Error com.example.dao.DAOException
Message: Error deleting employee in DAO, no such employee 1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 12
Practice 9-2: Detailed Level: Extending Exception

Overview
In this practice, you will take an existing application and refactor the code to make use of a
custom exception class and a custom auto-closeable resource.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the exception handling section of this lesson.

Summary
You have been given a project that implements the logic for a human resources application. The
application allows for creating, retrieving, updating, deleting, and listing of Employee objects.
This is the same project that you completed in the “Applying the DAO Pattern” practice.
Currently the only exceptions generated by the DAO implementation
(EmployeeDAOMemoryImpl) are unchecked exceptions such as a
ArrayIndexOutOfBoundsException.
h a s
Future DAO implementations should not require any rewriting of the application logic m )
ฺ c
(EmployeeTestInteractive). However, some DAO implementations will generate checked o d e ฺ
cle t Gu i
exceptions that must be dealt with. By creating a custom-checked exception class that will be
o r a n
used to wrap any DAO generated exceptions, all DAO implementations can appear to generate
e @ d e
t r a t S tu
the same type of exception. This will completely eliminate the need to change any application
logic when you create database enabled DAO implementations in later practices.
r a ฺis this
Tasks a n d use
1. Open the DAOException project l e xas the main
to project.
( a ns e
a. Select File > Open a t e
Project.
c e
I s tr le li
b. Browse to D:\labs\09-Exceptions\practices.
d a rab and select the "Open as Main Project" check box.
rDAOException
c. Select
x n
a the nOpen s fe
A l
d. e Click
- t r a Project button.
on the project directories.
2. Expand
n
3. Run the project. You should see a menu. Test all the menu choices.
[C]reate | [R]ead | [U]pdate | [D]elete | [L]ist | [Q]uit:
4. Create a DAOException class in the com.example.dao package.
5. Complete the DAOException class. The DAOException class should:
 Extend the Exception class.
 Contain four constructors with parameters matching those of the four constructors
present in the Exception class. For each constructor, use super() to invoke the
parent class constructor with matching parameters.
public class DAOException extends Exception {

public DAOException() {
super();
}

public DAOException(String message) {


Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 13
super(message);
}

public DAOException(Throwable cause) {


super(cause);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

public DAOException(String message, Throwable cause) {


super(message, cause);
}
}
6. Modify all the methods in the EmployeeDAO interface.
 All methods should declare that a DAOException may be thrown during execution.
 Extend the AutoCloseable interface. a
public interface EmployeeDAO extends AutoCloseable { ) h
as
ฺ c om ideฺ
public void add(Employee emp) throws DAOException;
r a cle t Gu
@ o e n
e
t throws d
tuDAOException;
public void update(Employee emp)
t r a S
r a ฺis this
public void delete(int
a n se DAOException;
did) uthrows
l e x to
a e
( findById(int
ns
a t
public Employee
r e i c e id) throws DAOException;
t
Is ble l
r a ra
dpublicfeEmployee[]
x a n s
getAllEmployees() throws DAOException;
n
Ale }n-tra
no the add method within the EmployeeDAOMemoryImpl class to:
7. Modify
 Declare that a DAOException may be produced during execution of this method.
 Use an if statement to validate that an existing employee will not be overwritten by the
add. If one would, generate a DAOException and deliver it to the caller of the method.
The DAOException should contain a message String indicating what went wrong and
why.
 Use a try-catch block to catch the ArrayIndexOutOfBoundsException
unchecked exception that could possibly be generated.
 Within the catch block that you just created, generate a DAOException and deliver it to
the caller of the method. The DAOException should contain a message String
indicating what went wrong and why.
public void add(Employee emp) throws DAOException {
if(employeeArray[emp.getId()] != null) {
throw new DAOException("Error adding employee in DAO,
employee id already exists " + emp.getId());
}
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 14
try {
employeeArray[emp.getId()] = emp;
} catch (ArrayIndexOutOfBoundsException e) {
throw new DAOException("Error adding employee in DAO, id
must be less than " + employeeArray.length);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

}
}
Note: Checking the length of the employeeArray could be used to determine whether the
DAOException should be thrown however the use of a try-catch block will be typical of
the structure used when create a database enabled DAO.
8. Modify the update method within the EmployeeDAOMemoryImpl class to:
 Declare that a DAOException may be produced during execution of this method.
 Use an if statement to validate that an existing employee is being updated. If one would
not be, generate a DAOException and deliver it to the caller of the method. The
s a
DAOException should contain a message String indicating what went wrong and why.
 Use a try-catch block to catch the ArrayIndexOutOfBoundsException )h a
unchecked exception that could possibly be generated.
c m
o ideฺ

r a cle t Gu
 Within the catch block that you just created, generate a DAOException and deliver it to

@ o
the caller of the method. The DAOException should contain a message String
e n
indicating what went wrong and why.
t e tu d
t r a S
public void update(Employee emp)
r a ฺ is this
throws DAOException {

a n d use== null) {
if(employeeArray[emp.getId()]
ex e to
throw new DAOException("Error
no such employee ("al+ emp.getId());
updating employee in DAO,

a t e c e ns
}
I s tr le li
rab
ra employeeArray[emp.getId()]
try {

a n d f e = emp;
x s
n (ArrayIndexOutOfBoundsException e) {
Ale n-t}racatch
noid must throw new DAOException("Error updating employee in DAO,
be less than " + employeeArray.length);
}
}
9. Modify the delete method within the EmployeeDAOMemoryImpl class to:
 Declare that a DAOException may be produced during execution of this method.
 Use an if statement to validate that an existing employee is being deleted. If one would
not be, generate a DAOException and deliver it to the caller of the method. The
DAOException should contain a message String indicating what went wrong and why.
 Use a try-catch block to catch the ArrayIndexOutOfBoundsException
unchecked exception that could possibly be generated.
 Within the catch block that you just created, generate a DAOException and deliver it to
the caller of the method. The DAOException should contain a message String
indicating what went wrong and why.
public void delete(int id) throws DAOException {
if(employeeArray[id] == null) {

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 15
throw new DAOException("Error deleting employee in DAO,
no such employee " + id);
}
try {
employeeArray[id] = null;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

} catch (ArrayIndexOutOfBoundsException e) {
throw new DAOException("Error deleting employee in DAO,
id must be less than " + employeeArray.length);
}
}
10. Modify the findById method within the EmployeeDAOMemoryImpl class to:
 Declare that a DAOException may be produced during execution of this method.
 Use a try-catch block to catch the ArrayIndexOutOfBoundsException
unchecked exception that could possibly be generated.
s a
a
 Within the catch block that you just created, generate a DAOException and deliver it to
)h
the caller of the method. The DAOException should contain a message String
indicating what went wrong and why. c m
o ideฺ

public Employee findById(int id) throws DAOException
r a cle t G{u
@ o e n
try {
return employeeArray[id];rat
e tu d
t S
r a ฺis this e) {
} catch (ArrayIndexOutOfBoundsException
a n d use finding employee in DAO",
throw new DAOException("Error
e); l e x to
( a ns e
}
a t e c e
}
I s tr le li
d
11. Add a closeramethod b the EmployeeDAOMemoryImpl class to implement the
rawithin
n f e
xa rans interface.
l e
AutoCloseable
-t
A @Override
o n
n public void close() {
System.out.println("No database connection to close just
yet");
}
Note: The EmployeeDAOMemoryImpl class implements EmployeeDAO which extends
AutoCloseable and, therefore, EmployeeDAOMemoryImpl class must provide a close
method.
12. Modify the EmployeeTestInteractive class to handle the DAOException objects that
are thrown by the EmployeeDAO.
a. Import the com.example.dao.DAOException class.
import com.example.dao.DAOException;
b. Modify the executeMenu method to declare that it throws an additional exception of
type DAOException.
public static boolean executeMenu(BufferedReader in, EmployeeDAO
dao) throws IOException, DAOException {

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 16
c. Remove the throws statement from the main method.
public static void main(String[] args) throws Exception
d. Modify the main method to use a try-with-resources statement.
 Surround the do-while loop with a try block.
 Convert the EmployeeDAO and BufferedReader references into auto-closed
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

resources.
 Add a catch clause for an IOException to the end of the try block to handle both
I/O errors thrown from the executeMenu method and when auto-closing the
BufferedReader.
 Add a second catch clause for an Exception to the end of the try block to handle
errors when auto-closing the EmployeeDAO.
try (EmployeeDAO dao = factory.createEmployeeDAO();
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in))) {
s a
do { )h a
timeToQuit = executeMenu(in, dao);
c m
o ideฺ

} while (!timeToQuit);
r a cle t Gu
} catch (IOException e) {
@ o e n
t e tu d
t r a
System.out.println("Error " + e.getClass().getName() +
S
" , quitting.");
r a ฺis this
n d use
System.out.println("Message: " + e.getMessage());
a
} catch (Exception e) { l e x to
( a ns e
t e e
System.out.println("Error closing resource " +
a c
I s tr le li
e.getClass().getName());

n d ra erab
System.out.println("Message: " + e.getMessage());
x a }
n s f
e
Al Note:- trAta this point, the application will compile and run, but DAOException instances
n
nogenerated will cause the application to terminate. For example, if you create an
employee with an ID of 100, the application will break out of the do-while loop and
pass to this catch clause.
e. Add a nested try-catch block in the main method that handles exceptions of type
DAOException that may be thrown by the executeMenu method.
try {
timeToQuit = executeMenu(in, dao);
} catch (DAOException e) {
System.out.println("Error " + e.getClass().getName());
System.out.println("Message: " + e.getMessage());
}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 17
13. Run the project. You should see a menu. Test all the menu choices.
[C]reate | [R]ead | [U]pdate | [D]elete | [L]ist | [Q]uit:
Attempt to delete an employee that does not exist. You should see a message similar to:
Error com.example.dao.DAOException
Message: Error deleting employee in DAO, no such employee 1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 18
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
)h a
c m
o ideฺ

Practices for r a cle t G10:
Lesson
u
Java
@ o e n
r a t e Stud
I/O Fundamentals
r a ฺist 10 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 1
Practices for Lesson 10: Overview

Practices Overview
In these practices, you will use some of the java.io classes to read from the console, open and
read files, and serialize and deserialize objects to and from the file system.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 2
Practice 10-1: Summary Level: Writing a Simple Console I/O
Application

Overview
In this practice, you will write a simple console-based application that reads from and writes to
the system console. In NetBeans, the console is opened as a window in the IDE.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Tasks
1. Open the project FileScanner in the following directory:
D:\labs\10-IO_Fundamentals\practices\
2. Open the file FileScanInteractive.
Notice that the class has a method called countTokens already written for you. This
method takes a String file and String search as parameters. The method will open the
file name passed in and use an instance of a Scanner to look for the search token. For
each token encountered, the method increments the integer field instanceCount. When
s a
h a
the file is exhausted, it returns the value of instanceCount. Note that the class rethrows
)
c o m
any IOException encountered, so you will need to be sure to use this method inside a
e ฺ
try-catch block. ฺ i d
3. r a cle t Gu
Code the main method to check the number of arguments passed. The application expects
@ o e n
at least one argument (a string representing the file to open). If the number of arguments is
t e tu d
t r a
less than one, exit the application with an error code (-1). S
r a ฺis this
a. The main method is passed an array of Strings. Use the length attribute to determine
n d use
whether the array contains less than one argument.
a
l e x to
b. Print a message if there is less than one argument, and use System.exit to return
( a ns e
an error code. (-1 typically is used to indicate an error.)
a t e c e
4. tr le li
Save the first argument passed into the application as a String.
I s
5. ra erab
Create an instance of the FileScanInteractive class. You will need this instance to
n d
a s f
call the countTokens method.
x n
6. Al
e - tra
Open the system console for input using a buffered reader.
no n
a. Use a try-with-resources to open a BufferedReader chained to the system console
input. (Recall that System.in is an input stream connected to the system console.)
b. Be sure to add a catch statement to the try block. Any exception returned will be an
IOException type.
c. In a while loop, read from the system console into a string until the string “q” is entered
on the console by itself.
Note: You can use equalsIgnoreCase to allow your users to enter an upper- or
lowercase “Q.”. Also the trim() method is a good choice to remove any whitespace
characters from the input.
d. If the string read from the console is not the terminate character, call the
countTokens method, passing in the file name and the search string.
e. Print a string indicating how many times the search token appeared in the file.
f. Add any missing import statements.
7. Save the FileScanInteractive class.
8. If you have no compilation errors, you can test your application by using a file from the
resources directory.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 3
a. Right-click the project and select Properties.
b. Click Run.
c. Enter the name of a file to open in the Arguments text box (for example,
D:\labs\resources\DeclarationOfIndependence.txt).
d. Click OK
e. Run the application and try searching for some words like when, rights, and free.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Your output should look something like this:


Searching through the file:
D:\labs\resources\DeclarationOfIndependence.txt
Enter the search string or q to exit: when
The word "when" appears 3 times in the file.
Enter the search string or q to exit: rights
The word "rights" appears 3 times in the file.
Enter the search string or q to exit: free
s a
The word "free" appears 4 times in the file.
) h a
Enter the search string or q to exit: q
c o m e ฺ
ฺ i d
cle t Gu
BUILD SUCCESSFUL (total time: 16 seconds)

o r a n
e @ d e
t r a t S tu
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 4
Practice 10-1: Detailed Level: Writing a Simple Console I/O
Application

Overview
In this practice, you will write a simple console-based application that reads from and writes to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

the system console. In NetBeans, the console is opened as a window in the IDE.

Tasks
1. Open the project FileScanner in the following directory:
D:\labs\10-IO_Fundamentals\practices\
a. Select File > Open Project.
b. Browse to D:\labs\10-IO_Fundamentals\practices.
c. Select FileScanner and select the “Open as Main Project” check box.
d. Click the Open Project button.
s a
2. Open the file FileScanInteractive. a
) hThis
Notice that the class has a method called countTokens already written form you. ฺ the
method takes a String file and String search as parameters. Theemethod ฺ c o willidopen
e
file name passed in and use an instance of a Scanner to lookra
l
forcthe searchG utoken. For
each token encountered, the method increments the integer e t
ofield instanceCount.
n When
t e @ t u d
the file is exhausted, it returns the value of instanceCount.
any IOException encountered, so you will ฺneed i s trtoa be sure
i s StoNote
use
that the class rethrows
this method inside a
r a e t h
try-catch block.
x nd ofuarguments
anumber s
3. Code the main method to checkethe
a l e t o passed. The application expects
at least one argument (a string
t e ( n s
representing the file to open). If the number of arguments is
less than one, exit the
t raapplicationl e
ic with an error code (-1).
a. The main I s
athemethod l e
isbpassed an array of Strings. Use the length attribute to determine
d
whether
n r r a
e contains less than one argument.
array
x a s f
n if there is less than one argument, and use System.exit to return
Ab.le Print- taa
r message

non
an error code. (-1 typically is used to indicate an error.) For example:
if (args.length < 1) {
System.out.println("Usage: java FileScanInteractive <file to
search>");
System.exit(-1);
}
4. Save the first argument passed into the application as a String.
String file = args[0];
5. Create an instance of the FileScanInteractive class. You will need this instance to
call the countTokens method.
FileScanInteractive scan = new FileScanInteractive ();

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 5
6. Open the system console for input using a buffered reader.
a. Use a try-with-resources to open a BufferedReader chained to the system console
input. (Recall that System.in is an input stream connected to the system console.)
b. Be sure to add a catch statement to the try block. Any exception returned will be an
IOException type. For example:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

try (BufferedReader in =
new BufferedReader(new InputStreamReader(System.in))) {

} catch (IOException e) { // Catch any IO exceptions.


System.out.println("Exception: " + e);
System.exit(-1);
}
c. In the try block that you created, add a while loop. The while loop should run until a
a
break statement. Inside the while loop, read from the system console into a string until
s
the string “q” is entered on the console by itself.
)h a
Note: You can use equalsIgnoreCase to allow your users to enter an upper- or
m
ฺ c o ideฺ
lowercase “Q.” Also the trim() method is a good choice to remove any whitespace
characters from the input.
r a cle t Gu
d. o e n
If the string read from the console is not the terminate character, call the
@
t e tu d
t r a
countTokens method, passing in the file name and the search string.
S
e. ฺis this
Print a string indicating how many times the search token appeared in the file.
r a
f. n d use
Your code inside the try block should look something like this:
a
l e x to
String search = ""; a
( ("Searching
ns e
a
System.out.println
r t e i c e through the file: " + file);
I s
while (true) t { le l
r a
d fer a b
a n System.out.print("Enter
x search s
the search string or q to exit: ");

Ale n-tif ran(search.equalsIgnoreCase("q"))


= in.readLine().trim();
break;
no int count = scan.countTokens(file, search);
System.out.println("The word \"" + search + "\" appears "
+ count + " times in the file.");
}
g. Add any missing import statements.
7. Save the FileScanInteractive class.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 6
8. If you have no compilation errors, you can test your application by using a file from the
resources directory.
a. Right-click the project and select Properties.
b. Click Run.
c. Enter the name of a file to open in the Arguments text box (for example,
D:\labs\resources\DeclarationOfIndependence.txt).
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

d. Click OK
e. Run the application and try searching for some words like when, rights, and free.
Your output should look something like this:
Searching through the file:
D:\labs\resources\DeclarationOfIndependence.txt
Enter the search string or q to exit: when
The word "when" appears 3 times in the file.
Enter the search string or q to exit: rights
s a
The word "rights" appears 3 times in the file.
Enter the search string or q to exit: free ) h a
c o m e ฺ
The word "free" appears 4 times in the file. ฺ i d
Enter the search string or q to exit: q
r a cle t Gu
@ o e n
BUILD SUCCESSFUL (total time: 16 seconds)
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 7
Practice 10-2: Summary Level: Serializing and Deserializing a
ShoppingCart

Overview
In this practice, you use the java.io.ObjectOutputStream class to write a Java object to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

the file system (serialize), and then use the same stream to read the file back into an object
reference. You will also customize the serialization and deserialization of the ShoppingCart
object.

Tasks
1. Open the SerializeShoppingCart project in the
D:\labs\10-IO_Fundamentals\practices directory.
2. Expand the com.example.test package. Notice there are two Java main classes in this
package, SerializeTest and DeserializeTest. You will be writing the code in these
main classes to serialize and deserialize ShoppingCart objects.
s a
3. Open the SerializeTest class. You will write the methods in this class to write
a
) hseveral
ShoppingCart objects to the file system.
c m
o ideฺ
a. Read through the code. You will note that the class prompts c

lethe cartGIDuand
constructs an instance of ShoppingCart with the cart o afor
IDrin t
the constructor.
n
@
e Stud e
b. The code then adds three Item objects to the ShoppingCart.
r a t
c. The code then prints out the number of items
r a ฺ ist in the
t is and the total cost of the items
hcart,
n d us
in the cart. Look through the ShoppingCart e
and Item classes in the
com.example.domain package
e x a for details
t o on how these classes work.
d. You will be writing the (
l
a to open
code sean ObjectOutputStream and write the
t e e n
ShoppingCart
I s traas a lserialized
e lic object on the file system.
4. Create the try
d r b a FileOutputStream chained to an
ablock toraopen
x a n
ObjectOutputStream.
s f e The file name is already constructed for you.
Aa.b.le Open r
Your code
- t anwill go where the comment line is at the bottom of the file.
n on a FileOutputStream with the cartFile string in a try-with-resources block.
c. Pass the file output stream instance to an ObjectOutputStream to write the
serialized object instance to the file.
d. Write the cart object to the object output stream instance by using the writeObject
method.
e. Be sure to catch any IOException and exit with an error as necessary.
f. Add a success message before the method ends:
System.out.println ("Successfully serialized shopping cart with
ID: " + cart.getCartId());
g. Save the file.
5. Open the DeserializeTest class. The main method in this class reads from the console
for the ID of the customer shopping cart to deserialize.
6. Your code will go where the comment line is at the bottom of the file.
a. Open a FileOutputStream with the cartFile string in a try-with-resources block.
b. Pass the file output stream instance to an ObjectOutputStream to write the
serialized object instance to the file.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 8
c. Read the cart object from the object output stream using the readObject method.
Be sure to cast the result to the appropriate object type.
d. You will need to catch both ClassNotFoundException and IOException, so use a
multi-catch expression.
e. Finally, print out the results of the cart (all of its contents) and the cart total cost
using the following code:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

System.out.println ("Shopping Cart contains: ");


List<Item> cartContents = cart.getItems();
for (Item item : cartContents) {
System.out.println (item);
}
System.out.println ("Shopping cart total: " +
NumberFormat.getCurrencyInstance().format(cart.getCartTotal()));
f. Save the file.
s a
7. a
Open the ShoppingCart class. You will customize the serialization and deserialization of
)h
this class by adding the two methods called during serialization/deserialization.
c m
o ideฺ

a. Add a writeObject method invoked during serialization. This method should
r a cle t Gu
serialize the current object fields and then add a timestamp (Date object instance) to
end of the object stream.
@ o e n
t e tu d
8.
t r a
Add a method to the ShoppingCart class that is invoked during deserialization.
S
r a ฺis this
a. Add a readObject method with the appropriate signature. This method will
n d use
recalculate the total cost of the shopping cart and print the timestamp that was added
a
to the stream. l e x to
b. Save the file. ( a ns e
a t e c e
9. tr le li
Test the application. This application has two main methods, so you will need to run each
I s
n d ra erab
main in turn.

x a n s f
a. To run the SerializeTest class, right-click the class name and select Run File.
e
Al n-tra
b. The output will look like this:
noEnter the ID of the cart file to create and serialize or q exit.
101
Shopping cart 101 contains 3 items
Shopping cart total: $58.39
Successfully serialized shopping cart with ID: 101
c. To run the DeserializeTest, right-click the class name and select Run File.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 9
d. Enter the ID 101 and the output will look like something this:
Enter the ID of the cart file to deserialize or q exit.
101
Restored Shopping Cart from: Oct 26, 2011
Successfully deserialized shopping cart with ID: 101
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Shopping cart contains:


Item ID: 101 Description: Duke Plastic Circular Flying Disc
Cost: 10.95
Item ID: 123 Description: Duke Soccer Pro Soccer ball Cost:
29.95
Item ID: 45 Description: Duke "The Edge" Tennis Balls - 12-Ball
Bag Cost: 17.49
Shopping cart total: $58.39

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 10
Practice 10-2: Detailed Level: Serializing and Deserializing a
ShoppingCart

Overview
In this practice, you use the java.io.ObjectOutputStream class to write a Java object to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

the file system (serialize), and then use the same stream to read the file back into an object
reference. You will also customize the serialization and deserialization of the ShoppingCart
object.

Tasks
1. Open the SerializeShoppingCart project in the
D:\labs\10-IO_Fundamentals\practices directory.
a. Select File > Open Project.
b. Browse to the D:\labs\10-IO_Fundamentals\practices directory.
c. Select the project SerializeShoppingCart. s a
)h a
d. Click the Open Project button.
2. Expand the com.example.test package. Notice there are two Javaฺmain c m
o classes e ฺin this
le theGcode
cwriting i d
u in these
package, SerializeTest and DeserializeTest. You will be a
o r n t
main classes to serialize and deserialize ShoppingCart objects.
e @ d e
3. Open the SerializeTest class. You will write the r a t
methods S intu
this class to write several
ShoppingCart objects to the file system. ฺis
t i s
d a e th
rthat
a. Read through the code. You will n
a note sclass prompts for the cart ID and
the
u
x o
le se t with the cart ID in the constructor.
constructs an instance of ShoppingCart
( a
b. The code then adds
t r a c enobjects to the ShoppingCart.
tethreeliItem
c. The code then
a s printsbout
ILook l the number of items in the cart, and the total cost of the items
e the
n d r
in the cart.
e ra package
through ShoppingCart and Item classes in the
x a s f
com.example.domain
n for details on how these classes work.
e
Ad.l You - rabe writing the code to open an ObjectOutputStream and write the
twill
n
noShoppingCart as a serialized object on the file system.
4. Create the try block to open a FileOutputStream chained to an
ObjectOutputStream. The file name is already constructed for you.
a. Your code will go where the comment line is at the bottom of the file.
b. Open a FileOutputStream with the cartFile string in a try-with-resources block.
c. Pass the file output stream instance to an ObjectOutputStream to write the
serialized object instance to the file.
d. Write the cart object to the object output stream instance by using the writeObject
method.
e. Be sure to catch any IOException and exit with an error as necessary.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 11
f. Your code might look like this:
try (FileOutputStream fos = new FileOutputStream (cartFile);
ObjectOutputStream o = new ObjectOutputStream (fos)) {
o.writeObject(cart);
} catch (IOException e) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

System.out.println ("Exception serializing " + cartFile + ":


" + e);
System.exit (-1);
}
g. Add a success message before the method ends:
System.out.println ("Successfully serialized shopping cart with
ID: " + cart.getCartId());
h. Add any missing import statements.
i. Save the file. a
5. Open the DeserializeTest class. The main method in this class reads from the console a s
for the ID of the customer shopping cart to deserialize. m )h
6. Your code will go where the comment line is at the bottom of the file. ฺ c o ideฺ
r a cle t Gu
a. Open a FileInputStream with the cartFile string in a try-with-resources block.
@ o e nto write the serialized
e
b. Pass the file output stream instance to an ObjectInputStream
t tu d
object instance to the file. t r a S
s the readObject method.
c. Read the cart object from the objectra ฺis stream
output t hiusing
nd uobject
Be sure to cast the result to theaappropriate
e
s type.
e x t o
d. You will need to catch (both
e al ClassNotFoundException
n s e and IOException, so use a

t r a t lice
multi-catch expression.
s
I look
e. Your code should
a b lelike this:
r er a
nd(FileInputStream
x
try
a s f fis = new FileInputStream (cartFile);

Ale n-tcart an
rObjectInputStream in = new ObjectInputStream (fis)) {

no} catch (final ClassNotFoundException | IOException e) {


= (ShoppingCart)in.readObject();

System.out.println ("Exception deserializing " + cartFile +


": " + e);
System.exit (-1);
}
System.out.println ("Successfully deserialized shopping cart
with ID: " + cart.getCartId());

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 12
f. Finally, print out the results of the cart (all of its contents) and the cart total cost
using the following code:
System.out.println ("Shopping cart contains: ");
List<Item> cartContents = cart.getItems();
for (Item item : cartContents) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

System.out.println (item);
}
System.out.println ("Shopping cart total: " +
NumberFormat.getCurrencyInstance().format(cart.getCartTotal()));
g. Save the file.
7. Open the ShoppingCart class. You will customize the serialization and deserialization of
this class by adding the two methods called during serialization/deserialization.
a. Add a method invoked during serialization that will add a timestamp (Date object
instance) to the end of the object stream.
b. Add a method with the signature: s a
)h a
private void writeObject(ObjectOutputStream oos) throws
c m
o ideฺ
IOException { ฺ
le andGthen
u write the
c. Make sure that the method serializes the current object fields r a cfirst, t
Date object instance: @ o e n
t e tu d
oos.defaultWriteObject(); t r a S
oos.writeObject(new Date()); r a ฺis this
a n d use
}
l e x tothat is invoked during deserialization. This
(
8. Add a method to the ShoppingCarta e
class
nofs the shopping cart and print the timestamp that was
method will recalculatea t e
the e
totalccost
I s
added to the stream. tr le li
a. Add d
n ra ewith
a method
f rabthe signature:
e a
xprivate n s readObject(ObjectInputStream ois) throws
l -t r
A IOException,a void

n o n ClassNotFoundException {
b. This method will deserialize the fields from the object stream, and recalculate the total
dollar value of the current cart contents:
ois.defaultReadObject();
if (cartTotal == 0 && (items.size() > 0)) {
for (Item item : items)
cartTotal += item.getCost();
}
c. Get the Date object from the serialized stream and print the timestamp to the console.
Date date = (Date)ois.readObject();
System.out.println ("Restored Shopping Cart from: " +
DateFormat.getDateInstance().format(date));
}
d. Save the ShoppingCart.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 13
9. Test the application. This application has two main methods, so you will need to run each
main in turn.
a. To run the SerializeTest class, right-click the class name and select Run File.
Enter a cart id, such as 101.
b. The output will look like this:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Enter the ID of the cart file to create and serialize or q exit.


101
Shopping cart 101 contains 3 items
Shopping cart total: $58.39
Successfully serialized shopping cart with ID: 101
c. To run the DeserializeTest, right-click the class name and select Run File.
d. Enter the ID 101 and the output will look like this:
Enter the ID of the cart file to deserialize or q exit.
101
s a
Restored Shopping Cart from: Oct 26, 2011
) h a
Successfully deserialized shopping cart with ID: 101
c o m e ฺ
ฺ i d
Shopping cart contains:
r a cle t Gu
o
Item ID: 101 Description: Duke Plastic Circular Flying Disc
@ e n
Cost: 10.95 t e tu d
t r a S
r a ฺis this
Item ID: 123 Description: Duke Soccer Pro Soccer ball Cost:
29.95
a n d use
x to
Item ID: 45 Description: Duke "The Edge" Tennis Balls - 12-Ball
l e
Bag Cost: 17.49
( a ns e
a t e c e
I s tr le li
Shopping cart total: $58.39

n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 14
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
)h a
c m
o ideฺ

Practices for r a cle t G11:
Lesson
u
Java
@ o e n
File I/O
r a t e(NIO.2)
S t ud
r a ฺist 11 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 1
Practices for Lesson 11: Overview

Practices Overview
In the first practice, you will use the JDK 7 NIO.2 API to write an application to create custom
letters by merging a template letter with a list of names, utilizing Files and Path methods. In
the second practice, you will use the walkFileTree method to copy all the files and directories
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

from one folder to another on the disk. In the final optional practice, you will use the same
method to write an application to recursively find and delete all the files that match a supplied
pattern.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 2
Practice 11-1: Summary Level: Writing a File Merge Application
Overview
In this practice, you will use the Files.readAllLines method to read the entire contents of
two files: a form template, and a list of names to send form letters to. After creating a form letter
with a name from the name list, you will use the Files.write method to create the custom
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

letter. You will also use the Pattern and Matcher classes that you saw in the “String
Processing” lesson.
Assumptions
You participated in the lecture for this lesson. Note there are Netbeans projects in the example
directory to help you understand how to use the Files class readAllLines and write
methods.
Tasks
1. Open the file FormTemplate in the resources directory.
s a
a
Note that this is a form letter with a string <NAME> that will be replaced by a name from the
)h
name list file. m
2. Open the file NamesList.txt in the resources directory. ฺ c o ideฺ
a. This file contains the names to send the form letters to. r a cle t Gu
@ o e n
b. Add your name to the end of the list.
t e tu d
c. Save the file. t r a S
3. r a ฺis this
Open the project FormLetterWriter in the practices directory.
4. Expand the FormLetterWriterxclass. a ndNoticeuthat sethis class contains the main method, and
that the application requires(twoa leparameters:
e toOne is the path to the form letter template, and
the second is the pathato t e e ns the list of names to substitute in the form letter.
the file containing
c
I s r a valid
tfor e i
lnumber
a. After checking
r a a b l of arguments, the main method then checks to see

a n d fer
whether the Path objects point to valid files.
s
b. xThe mainnmethod creates an instance of the FileMerge class with the form letter
Ale Pathn - a and the list of names Path object.
trobject
o
c.n In a try block, the main method calls the writeMergedForm method of the
FileMerge class. This is the method that you will write in this practice.
5. Expand the FileMerge class.
a. Note the writeMergedForms method is empty. This is the method that you will write
in this practice.
b. The mergeName method uses the Pattern object defined in the field declarations to
replace the string from the form template (first argument) with a name from the name
list (second argument). It returns a String. For example, it replaces "Dear <NAME>,"
with "Dear Wilson Ball,".
c. The hasToken method returns a boolean to indicate whether the string passed in
contains the token. This is useful to identify which string has the token to replace with
the name from the name list.
6. Code the writeMergedForms method. The overall plan for this method is to read in the
entire form letter, line by line, and then read in the entire list of names and merge the
names with the form letter, replacing the placeholder in the template with a name from the
list and then writing that out as a file. The net result should be that if you have ten names in

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 3
the name list, you should end up with ten custom letter files addressed to the names from
the name list. These ten files will be written to the resources directory.
a. Read in all of the lines of the form letter into the formLetter field, and all of the lines
from the name list into the nameList field.
Note: Because writeMergedForms throws IOException, you do not need to put
these statements into a try block. The caller of this method is responsible for handling
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

any exceptions thrown.


b. Create a for loop to iterate through the list of names (nameList) strings.
c. Inside this for loop, create a new List object to hold the strings of the form letter. You
need this new List to hold the modified form template strings to write out.
d. Still inside the for loop, you will need to create a name for the custom letter. One easy
way to do this is to use the name from the name list. You should replace any spaces in
the name with underscores for readability of the file name. Create a new Path object
relative to the form template path.
e. Create another for loop, nested in the first loop, to iterate through the lines of the form
s a
) h a
template and look for the token string ("<NAME>") to replace with the String name

c o m
from the nameList. Use the hasToken method to look for the String that contains the
e ฺ
ฺ d
token string and replace that string with one containing the name from the nameList.
i
a cle t Gu
Use the mergeName method to create the new String. Add the modified String and all
r
o e n
of the other Strings from the formLetter to the new customLetter List.
@
t e tu d
r a S
f. Still inside the first for loop, write the modified List of Strings that represents the
t
r a ฺis this
customized form letter to the file system by using the Files.write method. Print a
a n d use
message that the file write was successful and close the outer for loop.
g. Save the FileMerge class. l e x to
( a ns e
7.
a t e
Modify the FormLetterWriter project to pass the form letter file and the name list file to
c e
the main method.
I s tr le li
n d ra erab
a. Right-click the project and select Properties.
a s
b. Select Run.
x n f
e
Al n-tra
c. In the Arguments text field, enter: D:\labs\resources\FormTemplate.txt
no D:\labs\resources\NamesList.txt
d. Click OK.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 4
8. Run the project. You should see new files created with the names from the name list. Each
file should be customized with the name from the name list. For example, the
Tom_McGinn.txt file should contain:
Dear Tom McGinn,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

It has come to our attention that you would like to prove


your Java Skills. May we recommend that you consider
certification from Oracle? Oracle has globally recognized
Certification exams that will test your Java knowledge and
skills.

Start with the Oracle Certified Java Associate exam, and


then continue to the Oracle Certified Java Programmer
Professional for a complete certification profile.

s a
Good Luck!
) h a
c o m e ฺ
ฺ i d
cle t Gu
Oracle University

o r a n
e @ d e
t r a t S tu
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 5
Practice 11-1: Detail Level: Writing a File Merge Application
Overview
In this practice, you will use the Files.readAllLines method to read the entire contents of
two files: a form template, and a list of names to send form letters to. After creating a form letter
with a name from the name list, you will use the Files.write method to create the custom
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

letter. You will also use the Pattern and Matcher classes that you saw in the “String
Processing” lesson.
Assumptions
You participated in the lecture for this lesson. Note there are Netbeans projects in the example
directory to help you understand how to use the Files class readAllLines and write
methods.
Tasks
1. Open the file FormTemplate in the resources directory. a
a. Select File > Open File a s
m )h
b. Navigate to the resources directory in D:\labs
ฺ c o ideฺ
c. Select the file FormTemplate.txt and click the Open button.
r a cle t Gu
Note that this is a form letter with a string placeholder tokeno n will be replaced
<NAME> that
e @ d e
by a name from the name list file.
t r a t S tu
2. Open the file NamesList.txt in the resources
r a ฺis this
directory.
a. This file contains the names to send
n d form
the
u e to.
sletters
b. Add your name to the end e of x a
the list. to
c. Save the file. ( a l se
t e e n
I tra le lic
3. Open the projectsFormLetterWriter in the practices directory.

n d a > Open
a. Select rFile
f e rabProject.
a tonD:\labs\11-NIO.2\practices.
b. xBrowse
e s
l r a
-t FormLetterWriter.
Ac. Select
o n
d.n Select the “Open as Main Project” check box.
e. Click the Open Project button.
4. Expand the FormLetterWriter class. Notice that this class contains the main method,
and that the application requires two parameters: One is the path to the form letter
template, and the second is the path to the file containing the list of names to substitute in
the form letter.
a. After checking for a valid number of arguments, the main method then checks to see
whether the Path objects point to valid files.
b. The main method creates an instance of the FileMerge class with the form letter
Path object and the list of names Path object.
c. In a try block, the main method calls the writeMergedForm method of the
FileMerge class. This is the method that you will write in this practice.
5. Expand the FileMerge class.
a. Note the writeMergedForms method is empty. This is the method that you will write
in this practice.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 6
b. The mergeName method uses the Pattern object defined in the field declarations to
replace the string from the form template (first argument) with a name from the name
list (second argument). It returns a String. For example, it replaces "Dear <NAME>,"
with "Dear Wilson Ball,".
c. The hasToken method returns a boolean to indicate whether the string passed in
contains the token. This is useful to identify which string has the token to replace with
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

the name from the name list.


6. Code the writeMergedForms method. The overall plan for this method is to read in the
entire form letter, line by line, and then read in the entire list of names and merge the
names with the form letter, replacing the placeholder in the template with a name from the
list and then writing that out as a file. The net result should be that if you have ten names in
the name list, you should end up with ten custom letter files addressed to the names from
the name list. These ten files will be written to the resources directory.
a. Create an instance of the default Charset. This argument is required for the
Files.readAllLines method.
Charset cs = Charset.defaultCharset(); s a
b. Read in all of the lines of the form letter into the formLetter field, and all) of
a
hthe lines
from the name list into the nameList field. c m
o ideฺ

le do not uneed to put
Note: Because writeMergedForms throws IOException,
r a cyou t G
these statements into a try block. The caller of this method
@ o is responsible
e n for handling
any exceptions thrown. t e tu d
t r a S
formLetter = Files.readAllLines(form,
a ฺis thcs); is
nameList = Files.readAllLines(list, r
nd us cs); e
e x a tolist of names (nameList) strings.
c. Create a for loop to iterate
( a l through the
e
d. Inside this for loop,te
a create a new
c e nsList object to hold the strings of the form letter. You
will need thissnewtr List tolihold the modified form template strings to write out.
I l e
for d
n ra j e=ra0;b j < nameList.size(); j++) {
(int
x a customLetter
n s f
e
Ae.l Still t r a = new ArrayList<>();

nowayn-inside the for loop, you need to create a name for the custom letter. One easy
to do this is to use the name from the name list. You should replace any spaces in
the name with underscores for readability of the file name. Create a new Path object
relative to the form template path.
String formName = nameList.get(j).replace(' ',
'_').concat(".txt");
Path formOut = form.getParent().resolve(formName);

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 7
f. Create another for loop, nested in the first loop, to iterate through the lines of the form
template and look for the token placeholder string ("<NAME>") to replace with the
String name from the nameList. Use the hasToken method to look for the String
that contains the token string and replace that string with one containing the name from
the nameList. Use the mergeName method to create the new String. Add the
modified String and all of the other Strings from the formLetter to the new
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

customLetter List.
for (int k = 0; k < formLetter.size(); k++) {
if (hasToken(formLetter.get(k))) {
customLetter.add(mergeName(formLetter.get(k),
nameList.get(j)));
} else {
customLetter.add(formLetter.get(k));
}
} s a
g. Finally, still inside the first for loop, write the modified List of Strings )that h a
represents the customized form letter to the file system by using the c m
oFiles.writee ฺ
ฺ i d
method. Print a message that the file write was successful and
r a clecloset the
G uouter for loop.
Files.write(formOut, customLetter, cs);
@ o e n
e
tletterStto: d
u "+
System.out.println ("Wrote form
t r a
nameList.get(j));
aฺis for is
thloop
} // closing brace for thedouter r s e
e x anyou thave
o ueverything
h. Reformat the code to ensure
Alt-F key combination (
ora l that
s
right-click e
in the editor pane
in the right place. Press the Ctrl-
and choose Format.
a t e c e n
i. Save the FileMerge
I s tr leclass.li
n d ra erab
7. Modify the FormLetterWriter project to pass the form letter file and the name list file to
a
the main method.
xRight-click
n s f
l e r a
A n-t the project and select Properties.
a.
b.no Select Run.
c. In the Arguments text field, enter: D:\labs\resources\FormTemplate.txt
D:\labs\resources\NamesList.txt
d. Click OK.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 8
8. Run the project. You should see new files created with the names from the name list. Each
file should be customized with the name from the name list. For example, the
Tom_McGinn.txt file should contain:
Dear Tom McGinn,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

It has come to our attention that you would like to prove


your Java Skills. May we recommend that you consider
certification from Oracle? Oracle has globally recognized
Certification exams that will test your Java knowledge and
skills.

Start with the Oracle Certified Java Associate exam, and


then continue to the Oracle Certified Java Programmer
Professional for a complete certification profile.

s a
Good Luck!
) h a
c o m e ฺ
ฺ i d
cle t Gu
Oracle University

o r a n
e @ d e
t r a t S tu
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 9
Practice 11-2: Summary Level: Recursive Copy

Overview
In this practice, you write Java classes that use the FileVisitor class to recursively copy one
directory to another.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You participated in the lecture for this lesson.

Tasks
1. Open the project RecursiveCopyExercise in the directory D:\labs\11-
NIO.2\practices.
2. Expand the Source Packages folder and subfolders and look at the Copy.java class.
a. Note that the Copy.java class contains the main method.
b. The application takes two arguments, a source and target paths. s a
)h a
c. If the target file or directory exists, the user is prompted whether to overwrite.
c m
o ideฺ
d. If the answer is yes (or the letter y), the method continues. ฺ
e. a cle t Gu
An instance of the CopyFileTree class is created with the source and target.
r
@ o e n
f.
t e tu d
This instance is then passed to the walkFileTree method (with the source Path
object). t r a S
a ฺis this
You will need to provide method bodies for the methods in the CopyFileTree.java
r
class. a n d use
3. Open the CopyFileTree.java class. l e x to
a e
(the FileVisitor
ns
a. This class implements
r a t e i c e interface. Note that FileVisitor is a
I s
generic interface,t and l e l
this interface is boxed with the Path class. This allows the
r
interface a
d to define b
rathe type of the arguments passed to its methods.
a n s
b. xThe CopyFileTree f e implements all the methods defined by FileVisitor.
n
Ac.le Your t r a
n- task You
is to write method bodies for the preVisitDirectory and visitFile
nomethods. will not need the postVisitDirectory method, and you have been
provided a method body for the visitFileFailed method.
4. Write the method body for preVisitDirectory. This method is called for the starting
node of the tree and every subdirectory. Therefore, you should copy the directory of the
source to the target. If the file already exists, you can ignore that exception (because you
are doing the copy because the user elected to overwrite.)
a. Start by creating a new directory that is relative to the target passed in, but is the node
name from the source. The method call to do this is:
Path newdir = target.resolve(source.relativize(dir));
b. In a try block, copy the directory passed to the preVisitDirectory method to the
newdir that you created.
c. You can ignore any FileAlreadyExistsException thrown, because you are
overwriting any existing folders and files in this copy.
d. Catch any other IOExceptions, and use the SKIP_SUBTREE return to avoid
repeated errors.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 10
5. Write the method body for the visitFile method. This method is called when the node
reached is a file. The file is passed as an argument to the method.
a. As with the preVisitDirectory, you must rationalize the file reached (source path)
with the path that you wanted for the target. Use the same method call as above (only
using file instead of dir):
Path newdir = target.resolve(source.relativize(file));
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

b. As in the preVisitDirectory method, use the Files.copy method in a try block.


Make sure that you pass REPLACE_EXISTING in as an option to overwrite any existing
file in the directory.
c. Catch any IOException thrown and report an error.
d. Fix any missing imports.
e. Save your class.
6. Test your application by copying a directory (ideally with subdirectories) to another location
on the disk. For example, copy the D:\labs\11-NIO.2 directory to D:\Temp.
a. Right-click the project and select Properties. s a
b. Click Run. ) h a
c. Enter the following as Arguments: c o m e ฺ
ฺ i d
D:\labs\11-NIO.2 D:\Temp
r a cle t Gu
d. Click OK. @ o e n
t e tu d
7.
t r a
Run the project and you should see the following message: S
a ฺis this
Successfully copied D:\labs\11-NIO.2 to D:\Temp
r
n d use
a. Run the project again, and you should be prompted:
a
l e x to
a e
Target directory exists. Overwrite existing files? (yes/no):
( ns
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 11
Practice 11-2: Detailed Level: Recursive Copy

Overview
In this practice, you write Java classes that use the FileVisitor class to recursively copy one
directory to another.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You participated in the lecture for this lesson.

Tasks
1. Open the project RecursiveCopyExercise in the directory D:\labs\11-
NIO.2\practices.
a. Select File > Open Project.
b. Browse to D:\labs\11-NIO.2\practices.
c. Select RecursiveCopyExercise. s a
d. Select the “Open as Main Project” check box. )h a
e. Click the Open Project button. c m
o ideฺ

2. Expand the Source Packages folder and subfolders and look atathe
r cleCopy.java
t G u class.
a. Note that the Copy.java class contains the main method. @ o e n
e d
tu paths.
tand target
b. The application takes two arguments, a source t r a S
c. If the target file or directory exists, thera user
e his whether to overwrite.
ฺisis prompted
t
d. If the answer is yes (or the letter
x a ny),dthe method
us continues.
e t o
al nseclass is created with the source and target.
e. An instance of the CopyFileTree
e (
s t at passed
f. This instance isrthen l i ceto the walkFileTree method (with the source Path
object).
r a I
a b le
x a s f er method bodies for the methods in the CopyFileTree.java
d to provide
You willnneed
le -tran
class.
3. AOpen n
n o the CopyFileTree.java class.
a. This class implements the FileVisitor interface. Note that FileVisitor is a
generic interface, and this interface is boxed with the Path class. This allows the
interface to define the type of the arguments passed to its methods.
b. The CopyFileTree implements all the methods defined by FileVisitor.
c. Your task is to write method bodies for the preVisitDirectory and visitFile
methods. You will not need the postVisitDirectory method, and you have been
provided a method body for the visitFileFailed method.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 12
4. Write the method body for preVisitDirectory. This method is called for the starting
node of the tree and every subdirectory. Therefore, you should copy the directory of the
source to the target. If the file already exists, you can ignore that exception (because you
are doing the copy because the user elected to overwrite.)
a. Start by creating a new directory that is relative to the target passed in, and is the node
name from the source. The method call to do this is:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Path newdir = target.resolve(source.relativize(dir));


b. In a try block, copy the directory passed to the preVisitDirectory method to the
newdir that you created.
try {
Files.copy(dir, newdir);
c. You can ignore any FileAlreadyExistsException thrown, because you are
overwriting any existing folders and files in this copy.
} catch (FileAlreadyExistsException x) {
s a
// ignore
a
) havoid
d. Do catch any other IOExceptions, and use the SKIP_SUBTREE return m to
repeated errors. ฺ c o ideฺ
} catch (IOException x) { r a cle t Gu
@ o%s: %s%n",
e n
System.err.format("Unable to create:
t e tu d
newdir, x);tra S
return SKIP_SUBTREE; r a ฺis this
a n d use
}
l e x o
tmethod.
5. Write the method body for the ( a visitFile
n e
san argument toThis method is called when the node
reached is a file. Thea
r t
fileeis passed
i c e as the method.
s t le
a. As with theIpreVisitDirectory,
l you must rationalize the file reached (source path)
r a a b
x a ndthefile
with
s f er youof wanted
path that for the target. Use the same method call as above (only
using
Ale Path - t r an = target.resolve(source.relativize(file));
instead dir):

on newdir
b.n As in the preVisitDirectory method, use the Files.copy method in a try block.
Make sure that you pass REPLACE_EXISTING in as an option to overwrite any existing
file in the directory.
try {
Files.copy(file, newdir, REPLACE_EXISTING);
Note: To use the REPLACE_EXISTING enum type, you must import the
java.nio.file.StandardCopyOption enum class using a static import, like this:
import static java.nio.file.StandardCopyOption.*;
c. Catch any IOException thrown and report an error.
} catch (IOException x) {
System.err.format("Unable to copy: %s: %s%n", source, x);
}
d. Fix any missing imports.
e. Save your class.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 13
6. Test your application by copying a directory (ideally with subdirectories) to another location
on the disk. For example, copy the D:\labs\11-NIO.2 directory to D:\Temp.
a. Right-click the project and select Properties.
b. Click Run.
c. Enter the following as Arguments:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

D:\labs\11-NIO.2 D:\Temp
d. Click OK.
7. Run the project and you should see the following message:
Successfully copied D:\labs\11-NIO.2 to D:\Temp
a. Run the project again, and you should be prompted:
Target directory exists. Overwrite existing files? (yes/no):

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 14
(Optional) Practice 11-3: Summary Level: Using PathMatcher to
Recursively Delete
Overview
In this practice, you write a Java main that creates a PathMatcher class and uses
FileVisitor to recursively delete a file or directory pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have completed the previous practice.
Tasks
1. Open the project RecursiveDeleteExercise in the practices directory.
2. Expand the Source Packages folders.
3. Open the Delete.java class file. This is the class that contains the main method. The
main class accepts two arguments: the first is the starting path and the other the pattern to
delete. s a
)h a
4. You must code the remainder of this class. Look at the comments for hints as to what to do.
c m
o ideฺ

a. Start by creating a PathMatcher object from the search string passed in as the
a cle t Gu
second argument. To obtain a PathMatcher instance, you will need to use the
r
o e n
FileSystems class to get a path matcher instance from the default file system.
@
t e tu d
b. Create a Path object from the first argument.
t r a S
c. If the starting path is a file, check it against
r a e hisusing the PathMatcher
ฺisthe pattern
t
instance that you created. If therenis
a da match,u sdelete the file, and then terminate the
application. x
le se t o
( a
d. If the starting path tisea directory,
t
starting directoryr a i c encreate anobject
and the lPathMatcher
instance of the DeleteFileTree with the
as initial arguments in the constructor.
Pass the
I
a rabs
starting l e
directory and the file tree to a method to
d r Files.walkFileTree

x an nslook
recursively fe for the pattern to delete.
e tramissing imports.
Ae.l Fixn-any
f. o Save the Delete class.
n
5. Open the DeleteFileTree class file. This class implements FileVisitor. This class
recursively looks for instances of files or directories that match the PathMatcher object
passed into the constructor. This class is complete with the exception of the delete
method.
a. The delete method is called by the preVisitDirectory and visitFile methods.
You must check whether the file or directory reached by these methods matches the
pattern.
b. We only want to match the path name at the node, so use the Path.getFileName
method to obtain the file name at the end of the full path.
c. If the name matches, use the Files.delete method to attempt to delete the file
pattern and print a result statement, or print an error if an IOException is thrown.
d. Save the DeleteFileTree class.
6. Run the Delete application using a temporary directory.
a. For example, if you completed the first practice, you can delete all the Java class files
from the D:\Temp directory.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 15
b. Right-click the project and select Properties.
c. Click Run and enter the following in the Arguments text field:
D:\Temp\examples *.class
d. Run the project.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 16
(Optional) Practice 11-3: Detailed Level: Using PathMatcher to
Recursively Delete

Overview
In this practice, you write a Java main that creates a PathMatcher class and uses
FileVisitor to recursively delete a file or directory pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have completed the previous practice.

Tasks
1. Open the project RecursiveDeleteExercise in the practices directory.
a. Select File > Open Project.
b. Browse to D:\labs\11-NIO.2\practices.
c. Select RecursiveDeleteExercise. s a
) h a
d. Click the Open Project button.
c o m e ฺ
2. Expand the Source Packages folders. ฺ i d
3. a cle t Gu
Open the Delete.java class file. This is the class that contains the main method. The
r
o e n
main class accepts two arguments: the first is the starting path and the other the pattern to
@
t e tu d
delete.
t r a S
4. ฺis this
You must code the remainder of this class. Look at the comments for hints as to what to do.
r a
n d use
a. Start by creating a PathMatcher object from the search string passed in as the
a
l e x to
second argument. To obtain a PathMatcher instance, you will need to use the
( a ns e
FileSystems class to get a path matcher instance from the default file system.
a t e c e
s tr le li
PathMatcher matcher =
I
n d ra erab
FileSystems.getDefault().getPathMatcher("glob:" + args[1]);

x a n s f
b. Create a Path object from the first argument.
e
Al n-tra
Path root = Paths.get(args[0]);
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 17
c. If the starting path is a file, check it against the pattern using the PathMatcher
instance that you created. If there is a match, delete the file, and then terminate the
application.
if (!Files.isDirectory(root)) {
Path name = root.getFileName();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

if (name != null && matcher.matches(name)) {


try {
Files.delete(root);
System.out.println("Deleted :" + root);
System.exit(0);
} catch (IOException e) {
System.err.println("Exception deleting file: " +
root);
System.err.println("Exception: " + e);
s a
System.exit(-1);
)h a
}
c m
o ideฺ

}
r a cle t Gu
}
@ o e n
d. If the starting path is a directory, create an instance e tu d
t of theSDeleteFileTree with the
t r a
starting directory and the PathMatcher iobject
Pass the starting directory and the d filera
ฺ s this as initial arguments
tree to aeFiles.walkFileTree
in the constructor.
method to
recursively look for the pattern a
tondelete. u s
l e x toDeleteFileTree(root, matcher);
DeleteFileTree deleter ( a ns
= e
new
a t e c e
try {
I s tr le li
d r a rab
Files.walkFileTree(root, deleter);

x}an
s fe
catch (IOException
n
e) {
e ra
Al }n-tSystem.out.println("Exception: " + e);

no
e. Fix any missing imports.
f. Save the Delete class.
5. Open the DeleteFileTree class file. This class implements FileVisitor. This class
recursively looks for instances of files or directories that match the PathMatcher object
passed into the constructor. This class is complete with the exception of the delete
method.
a. The delete method is called by the preVisitDirectory and visitFile methods.
You must check whether the file or directory reached by these methods matches the
pattern.
b. We only want to match the path name at the node, so use the Path.getFileName
method to obtain the file name at the end of the full path.
Path name = file.getFileName();

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 18
c. If the name matches, use the Files.delete method to attempt to delete the file
pattern and print a result statement, or print an error if an IOException is thrown.
if (matcher.matches(name)) {
//if (name != null && matcher.matches(name)) {
try {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Files.delete(file);
System.out.println("Deleted: " + file);
} catch (IOException e) {
System.err.println("Unable to delete: " + name);
System.err.println("Exception: " + e);
}
}
d. Save the DeleteFileTree class.
6. Run the Delete application using a temporary directory. s a
) h a
a. For example, if you completed the first practice, you can delete all the Java class files
from the D:\Temp directory. c o m e ฺ
ฺ i d
b. Right-click the project and select Properties.
r a cle t Gu
o
c. Click Run and enter the following in the Arguments text field:
@ e n
t e tu d
D:\Temp\examples *.class
t r a S
d. Run the project.
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Java File I/O (NIO.2)


Chapter 11 - Page 19
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G12:
Lesson
u
@ o e n
Threading t e tu d
t r a S
r a ฺis 12 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 1
Practices for Lesson 12: Overview

Practices Overview
In these practices, you will use the multithreaded features of the Java programming language.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 2
Practice 12-1: Summary Level: Synchronizing Access to Shared Data

Overview
In this practice, you will add code to an existing application. You must determine whether the
code is run in a multithreaded environment, and, if so, make it thread-safe.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the sections covering the use of the Thread class and the synchronized
keyword of this lesson.

Summary
You will open a project that purchases shirts from a store. The file-reading code will be provided
to you. Your task is to add the appropriate exception handling code.

Tasks
1. Open the project Synchronized as the main project. s a
a. Select File > Open Project. ) h a
c o m e ฺ
b. Browse to D:\labs\12-Threading\practices. ฺ i d
a cle t Gu
c. Select Synchronized and select the "Open as Main Project" check box.
r
@ o e n
d. Click the Open Project button.
t e tu d
2. t r a S
Expand the project directories but avoid opening and review the provided classes at this
a ฺis this
point. You will attempt to discover whether this application is multithreaded by observing the
r
behavior of code that you provide.
a n d use
3. l e x to
Create a PurchasingAgent class in the com.example package.
( a ns e
4. t e
Complete the PurchasingAgent class.
a c e
s tr le li
a. Add a purchase method.
I
n d
public
f ab
ravoiderpurchase() {}
a s
x ranthe purchase method. The purchase() method should:
Ab.le Complete
n -t a Store reference. Note that the Store class implements the Singleton
Obtain
o
n design pattern.
Store store = Store.getInstance();

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 3
 Buy a Shirt.
 Verify that the store has at least one shirt in stock.
store.getShirtCount()
 Use the store to authorize a credit card purchase. Use a credit card account
number of "1234" and a purchase amount of 15.00. A boolean result is returned.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

store.authorizeCreditCard("1234", 15.00)
 If there are shirts in stock and the credit card purchase was authorized, you should
take a shirt from the store.
Shirt shirt = store.takeShirt();
 Print out the shirt and a success message if a shirt was acquired or a failure
message if one was not.
5. Run the project multiple times. Note that the store contains only a single shirt. You can see
many possible variations of output. You might see:
 Two success messages and two shirts (output may appear in varying order) s a
 Two success messages, one shirt, and one null ) h a
 Two success messages, one shirt, and one exception c o m e ฺ
ฺ i d
r a cle t Gu
 One success message, one shirt, and one failure message (desired behavior, but least
likely)
@ o e n
6. Discover how the PurchasingAgent class is being used.t e tu d
t r a S
r a ฺis this
a. Use a constructor and a print statement to discover how many instances of the

a n d use
PurchasingAgent class are being created when running the application.
x to
Reminder: Sometimes objects are created per-request and sometimes an object may
l e
( a ns e
be shared by multiple requests. The variations in the model affect which code must be
thread-safe. a t e c e
I s tr le li
b. Within the purchase method use the Thread.currentThread() method to obtain
d ra erab
a reference to the thread currently executing the purchase() method. Use a single
n
x a s f
print statement to print the name and ID of the executing thread.
n
e
Al n-tra
c. Run the project and observe the output.
7. no
Open the Store class and add a delay to the authorizeCreditCard method.
 Obtain a random number in the range of 1–3, the number of seconds to delay. Print a
message indicating how many seconds execution will be delayed.
int seconds = (int) (Math.random() * 3 + 1);
 Use the appropriate static method in the Thread class to delay execution for 1 to 3
seconds.
Optional Task: What if your delay is interrupted? How can you be sure that execution is
delayed for the desired number of seconds? Or should a different action be taken?
8. Run the project multiple times. You should see a stack trace for a
java.util.NoSuchElementException. Locate the line within the
com.example.PurchasingAgent.purchase method that is displayed in the stack
trace. Review the action occurring on that line.
9. Use a synchronized code block to create predictable behavior.
 Modify the purchase method in the PurchasingAgent class to contain a
synchronized code block.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 4
Note: Adding synchronized to the method signature or using a synchronized
block that uses the this object’s monitor will not work.
10. Run the project. You should now see the desired behavior. In the output window, you
should see one success message, one shirt, and one failure message.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 5
Practice 12-1: Detailed Level: Synchronizing Access to Shared Data

Overview
In this practice, you will add code to an existing application. You must determine whether the
code is run in a multithreaded environment, and, if so, make it thread-safe.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the sections covering the use of the Thread class and the synchronized
keyword of this lesson.

Summary
You will open a project that purchases shirts from a store. The file-reading code will be provided
to you. Your task is to add the appropriate exception handling code.

Tasks
1. Open the project Synchronized as the main project. s a
a. Select File > Open Project. ) h a
c o m e ฺ
b. Browse to D:\labs\12-Threading\practices. ฺ i d
a cle t Gu
c. Select Synchronized and select the "Open as Main Project" check box.
r
@ o e n
d. Click the Open Project button.
t e tu d
2. t r a S
Expand the project directories but avoid opening and review the provided classes at this
a ฺis this
point. You will attempt to discover whether this application is multithreaded by observing the
r
behavior of code that you provide.
a n d use
3. l e x to
Create a PurchasingAgent class in the com.example package.
( a ns e
4. t e
Complete the PurchasingAgent class.
a c e
s tr le li
a. Add a purchase method. The purchase() method should:
I
d ra erab
 Obtain a Store reference. Note that the Store class implements the Singleton
n
x a s f
design pattern.
n
e
Al n-tra
 Buy a Shirt.
no  Verify that the store has at least one shirt in stock.
 Use the store to authorize a credit card purchase. Use a credit card account
number of "1234" and a purchase amount of 15.00. A boolean result is returned.
 If there are shirts in stock and the credit card purchase was authorized, you should
take a shirt from the store.
 Print out the shirt and a success message if a shirt was acquired or a failure
message if one was not.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 6
public class PurchasingAgent {

public void purchase() {


Store store = Store.getInstance();
if (store.getShirtCount() > 0 &&
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

store.authorizeCreditCard("1234", 15.00)) {
Shirt shirt = store.takeShirt();
System.out.println("The shirt is ours!");
System.out.println(shirt);
} else {
System.out.println("No shirt for you");
}
}
}
s a
5. h a
Run the project multiple times. Note that the store contains only a single shirt. You can see
)
many possible variations of output. You might see:
c o m e ฺ
ฺ i d
r a cle t Gu
 Two success messages and two shirts (output may appear in varying order)
Adding a shirt to the store.
@ o e n
Total shirts in stock: 1 t e tu d
t r a S
The shirt is ours!
r a ฺis this
The shirt is ours!
a n d use
Shirt ID: 1
Description: Polo(a
lex se to
t
Color: Rainbowr a te licen
Size:ra Is ble
d fera
Large
a n
xShirtraID:s
l e n
A n-t 1
noDescription:
Color: Rainbow
Polo

Size: Large
 Two success messages, one shirt, and one null
Adding a shirt to the store.
Total shirts in stock: 1
The shirt is ours!
The shirt is ours!
null
Shirt ID: 1
Description: Polo
Color: Rainbow
Size: Large
 Two success messages, one shirt, and one exception
Adding a shirt to the store.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 7
Total shirts in stock: 1
The shirt is ours!
Shirt ID: 1
Description: Polo
Color: Rainbow
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Size: Large
Exception in thread "Thread-0" java.util.NoSuchElementException
 One success message, one shirt, and one failure message (desired behavior but least
likely)
Adding a shirt to the store.
Total shirts in stock: 1
The shirt is ours!
Shirt ID: 1
Description: Polo
s a
Color: Rainbow
)h a
Size: Large
c m
o ideฺ

r a cle t Gu
No shirt for you
@ o e n
6. Discover how the PurchasingAgent class is being e
tused. Stu d
t r a
ฺis thand
a. In the PurchasingAgent class, use a constructor
a is a print statement to discover
how many instance of the PurchasingAgent
n r
d us e class are being created when running
the application.
e x a to
( a l e
a t e
public PurchasingAgent()
c e ns{
s tr le li
System.out.println("Creating
I a purchasing agent");
}
n d ra erab
x a
Reminder:
n s f
Sometimes objects are created per-request and sometimes an object may
l e be t r
shared
A thread-safe.
- a by multiple requests. The variations in the model affect which code must be
no n
b. Within the purchase method use the Thread.currentThread() method to obtain
a reference to the thread currently executing the purchase() method. Use a single
print statement to print the name and ID of the executing thread.
Thread t = Thread.currentThread();
System.out.println("Thread:" + t.getName() + "," + t.getId());
c. Run the project and observe the output.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 8
7. Open the Store class and add a delay to the authorizeCreditCard method.
 Math.random() is used to obtain a random number in the range of 1–3, the number of
seconds to delay.
int seconds = (int) (Math.random() * 3 + 1);
System.out.println("Sleeping for " + seconds + " seconds");
try {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
8. Run the project multiple times. You should see a stack trace for a
java.util.NoSuchElementException. Locate the line within the
com.example.PurchasingAgent.purchase method that is displayed in the stack
trace. The exception is being generated by the call to store.takeShirt().
Note: The delay introduced in the previous step makes it more likely that concurrent
s a
PurchasingAgent.purchase methods calls will both believe that a shirt can be taken
) h a
but take the shirt at a different time. Taking the shirt at the near the same time typically
results in some of the other errors shown in step 5. c o m e ฺ
ฺ i d
9. Use a synchronized code block to create predictable behavior.
r a cle t Gu
o e n
 Modify the purchase method in the PurchasingAgent class to contain a
@
synchronized code block. t e tu d
t r a S
synchronized (store) {
r a ฺis this
if (store.getShirtCount()
a n d >u0se&&
l e x
store.authorizeCreditCard("1234", to 15.00)) {
a e
( = store.takeShirt();
n s
Shirt shirt
a t e c e
I s tr le li
System.out.println("The shirt is ours!");

n d raelse e{rab
System.out.println(shirt);

x a }
n s f
e
Al n-t}ra System.out.println("No shirt for you");

no}
Note: Adding synchronized to the method signature or using a synchronized
block that uses the this object’s monitor will not work.
10. Run the project. You should now see the desired behavior. In the output window, you
should see one success message, one shirt, and one failure message.
Adding a shirt to the store.
Total shirts in stock: 1
The shirt is ours!
Shirt ID: 1
Description: Polo
Color: Rainbow
Size: Large

No shirt for you

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 9
Practice 12-2: Summary Level: Implementing a Multithreaded Program

Overview
In this practice, you will create a new project and start a new thread.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have reviewed the sections covering the use of the Thread class.

Summary
You will create a project that slowly prints an incrementing number. A new thread will be used to
increment and print the number. The application should wait for Enter to be pressed before
interrupting any threads.

Tasks
1. Create a new project ThreadInterrupted as the main project. a
a. Select File > New Project. h a s
m )
b. Select Java under Categories and Java Application under Projects. Click the Next
ฺ c o d e ฺ
button.
cle t Gu i
r a
c. Enter the following information in the “Name and Location” dialog box:
o n
 Project Name: ThreadInterrupted e @ d e
t r a t
 Project Location: D:\labs\12-Threading\practices. S tu
r a ฺis this
 (checked) Create Main Class: com.example.ThreadInterruptedMain
a n d use
l e x
 (checked) Set as Main Project
to
(
d. Click the Finish button.a ns e
a t e c e
2. tr le li
Create a Counter class in the com.example package.
I s
3. ra erab
Complete the Counter class. The Counter class should:
n d
x n s f
 Implement the Runnable interface.
a
e
Al n-tra
 Within the run method:
no  Create an int variable called x and initialize it to zero.
 Construct a loop that will repeat until the executing thread is interrupted.
 Within the loop, print and increment the value of x.
 Within the loop, delay for 1 second. Return from the run method or exit the loop if the
thread is interrupted while delayed.
4. Add the following to the main method in the ThreadInterruptedMain class:
 Create a Counter instance.
 Create a thread and pass to its constructor the runnable Counter.
 Start the thread.
5. Run the project. You should see an incrementing sequence of numbers with a one second
delay between each number. Notice that while the main method has completed the
application continues to run.
6. Stop the project.
a. Open the Run menu.
b. Click Stop Build/Run.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 10
Note: You can also stop a build/run by clicking the red square along the left side of the
output window.
7. Modify the main method in the ThreadInterruptedMain class.
 After starting the thread, wait for Enter to be pressed in the output window. You can use
the following code:
try(BufferedReader br = new BufferedReader(new
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

InputStreamReader(System.in))) {
br.readLine();
} catch (IOException e) {}
Note: You may need to fix your imports and update the project properties to support
JDK 7 features.
 Print out a message indicating whether or not the thread is alive.
 Interrupt the thread.
 Delay for one second (to allow the thread time to complete) and then print out a
message indicating whether or not the thread is alive. s a
8. ) h a
Run the project. You should see an incrementing sequence of numbers with a one second
o m ฺ
delay between each number. Press Enter while the output window is selected to gracefully
c e
ฺ i d
terminate the application.
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 11
Practice 12-2: Detailed Level: Implementing a Multithreaded Program

Overview
In this practice, you will create a new project and start a new thread.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have reviewed the sections covering the use of the Thread class.

Summary
You will create a project that slowly prints an incrementing number. A new thread will be used to
increment and print the number. The application should wait for Enter to be pressed before
interrupting any threads.

Tasks
1. Create a new project ThreadInterrupted as the main project.
s a
a. Select File > New Project.
) h a
b. Select Java under Categories and Java Application under Projects. Click the Next
m
button. ฺ c o d e ฺ
cle t Gu i
o r a
c. Enter the following information in the “Name and Location” dialog box:
n
 Project Name: ThreadInterrupted
e @ d e
 Project Location: D:\labs\12-Threading\practices. t r a t S tu
r a ฺis this
 (checked) Create Main Class: com.example.ThreadInterruptedMain
 (checked) Set as Main Project a n d use
d. Click the Finish button.(al
ex e to
2. Create a Counter r a t
class e ns
ein theiccom.example package.
I s
3. Complete theaCounter b
t l e l
class. The Counter class should:
n d r e r a
 Implement
x a the
s fRunnable interface.

AleWithin
- tthe
r anrun method:
nonConstruct
Create an int variable called x and initialize it to zero.
a loop that will repeat until the executing thread is interrupted.
 Within the loop, print and increment the value of x.
 Within the loop, delay for 1 second. Return from the run method or exit the loop if the
thread is interrupted while delayed.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 12
int x = 0;
while(!Thread.currentThread().isInterrupted()) {
System.out.println("The current value of x is: " + x++);
try {
Thread.sleep(1000);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

} catch (InterruptedException e) {
return;
}
}
4. Add the following to the main method in the ThreadInterruptedMain class:
 Create a Counter instance.
 Create a thread and pass to its constructor the runnable Counter.
 Start the thread.
Runnable r = new Counter(); s a
Thread t = new Thread(r); )h a
c m
o ideฺ
t.start(); ฺ
a cle with
5. Run the project. You should see an incrementing sequence ofrnumbers
t Gauone second
delay between each number. Notice that while the main method
@ o hasecompleted
n the
application continues to run. t e t u d
i s t ra is S
6. Stop the project.
d r aฺ e th
a. Open the Run menu.
b. Click Stop Build/Run. e x an to us
Note: You can also stop ea ( al nbysclicking
build/run
e the red square along the left side of the
output window. tra
t lic e
I s l e
n d f r ab to support the try-with-resources statement.
ra eproperties
7. Modify the project
a
a. xRight-click
e n sthe ThreadInterrupted project and click Properties.
l r a
-t Project Properties dialog box select the Sources category.
Ab. Innthe
o
c.n In the Source/Binary Format drop-down list select JDK 7.
d. Click the OK button.
8. Modify the main method in the ThreadInterruptedMain class.
 After starting the thread, wait for Enter to be pressed in the output window. You can use
the following code:
try(BufferedReader br = new BufferedReader(new
InputStreamReader(System.in))) {
br.readLine();
} catch (IOException e) {}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 13
 Add the needed import statements.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 Print out a message indicating whether or not the thread is alive.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

System.out.println("Thread is alive:" + t.isAlive() );


 Interrupt the thread.
t.interrupt();
 Delay for one second (to allow the thread time to complete), and then print out a
message indicating whether or not the thread is alive.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
s a
}
)h a
System.out.println("Thread is alive:" + t.isAlive());
c m
o ideฺ

r
delay between each number. Press Enter while the output windowa cliseselected
9. Run the project. You should see an incrementing sequence of numbers with auone second
t G to gracefully
terminate the application.
o
@ tude n
a t e
ฺ i s tr is S
d r a e th
e x an to us
e ( al nse
s t r at lice
r a I
a b le
x a nd sfer
n
Ale n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 14
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G13:
Lesson
u
@ o e n
Concurrency t e tu d
t r a S
r a ฺis 13 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Concurrency


Chapter 13 - Page 1
Practices for Lesson 13: Overview

Practices Overview
In these practices, you will use the java.util.concurrent package and sub-packages of
the Java programming language.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Concurrency


Chapter 13 - Page 2
(Optional) Practice 13-1: Using the java.util.concurrent Package

Overview
In this practice, you will modify an existing project to use an ExecutorService from the
java.util.concurrent package.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have reviewed the sections covering the use of the java.util.concurrent package.

Summary
You will create a multithread networking client that will rapidly read the price of a shirt from
several different servers. Instead of manually creating threads, you will leverage an
ExecutorService from the java.util.concurrent package.

Tasks
1. Open the ExecutorService project as the main project. s a
) h a
a. Select File > Open Project.
c o m e ฺ
b. Browse to D:\labs\13-Concurrency\practices. ฺ i d
r a cle t Gu
c. Select ExecutorService and select the "Open as Main Project" check box.
@ o e n
d. Click the Open Project button.
t e tu d
2. Expand the project directories. t r a S
3. r a ฺis this
Run the NetworkServerMain class in the com.example.server package by
a n d use
right-clicking the class and selecting Run File.
l e x to
4. a e
Open the NetworkClientMain class in the com.example.client package.
( ns
5. t e e
Run the NetworkClientMain class package by right-clicking the class and selecting Run
a c
I s tr le li
File. Notice the amount of time it takes to query all the servers sequentially.
6. d ra erab
Create a NetworkClientCallable class in the com.example.client package.
n
x a n s f
 Add a constructor and a field to receive and store a RequestResponse reference.
e
Al n-tra
 Implement the Callable interface with a generic type of RequestResponse.
nopublic class NetworkClientCallable implements
Callable<RequestResponse>
 Complete the call method by using a java.net.Socket and a
java.util.Scanner to read the response from the server. Store the result in the
RequestResponse object and return it.
Note: You may want to use a try-with-resource statement to ensure that the
Socket and Scanner objects are closed.
7. Modify the main method of the NetworkClientMain class to query the servers
concurrently by using an ExecutorService.
a. Comment out the contents of the main method.
b. Obtain an ExecutorService that reuses a pool of cached threads.
c. Create a Map that will be used to tie a request to a future response.
Map<RequestResponse, Future<RequestResponse>> callables = new
HashMap<>();
d. Code a loop that will create a NetworkClientCallable for each network request.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Concurrency


Chapter 13 - Page 3
 The servers should be running on localhost, ports 10000–10009.
 Submit each NetworkClientCallable to the ExecutorService. Store each
Future in the Map created in step 7c.
e. Shut down the ExecutorService.
f. Await the termination of all threads within the ExecutorService for 5 seconds.
g. Loop through the Future objects stored in the Map created in step 7c. Print out the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

servers’ response or an error message with the server details if there was a problem
communicating with a server.
8. Run the NetworkClientMain class by right-clicking the class and selecting Run File.
Notice the amount of time it takes to query all the servers concurrently.
9. When done testing your client, be sure to select the ExecutorService output tab and
terminate the server application.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Concurrency


Chapter 13 - Page 4
(Optional) Practice 13-2: Using the Fork-Join Framework

Overview
In this practice, you will modify an existing project to use the Fork-Join framework.

Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

You have reviewed the sections covering the use of the Fork-Join framework.

Summary
You are given an existing project that already leverages the Fork-Join framework to process the
data contained within an array. Before the array is processed, it is initialized with random
numbers. Currently the initialization is single-thread. You must use the Fork-Join framework to
initialize the array with random numbers.

Tasks
1. Open the ForkJoinFindMax project as the main project. s a
a. Select File > Open Project. ) h a
c o m e ฺ
b. Browse to D:\labs\13-Concurrency\practices. ฺ i d
a cle t Gu
c. Select ForkJoinFindMax and select the "Open as Main Project" check box.
r
@ o e n
d. Click the Open Project button.
t e tu d
2. Expand the project directories. t r a S
3. r a ฺis this
Open the Main class in the com.example package.
a n d use
 Review the code within the main method. Take note of how the compute method splits
l e x to
a e
the data array if the count of elements to process is too great.
( ns
3. a t e e
Open the FindMaxTask class in the com.example package.
c
I s tr le li
 Review the code within the class. Take note of the for loop used to initialize the data
d ra erab
array with random numbers.
n
4. lex
a n s f
Create a RandomArrayAction class in the com.example package.
A n-tra
a. Add four fields.
noprivate final int threshold;
private final int[] myArray;
private int start;
private int end;
b. Add a constructor that receives parameters and saves their values within the fields
defined in the previous step.
public RandomArrayAction(int[] myArray, int start, int end, int
threshold)
c. Extend the RecursiveAction class from the java.util.concurrent package.
Note: A RecursiveAction is used when a ForkJoinTask with no return values is
needed.
d. Add the compute method. Note that unlike the compute method from a
RecursiveTask, the compute method in a RecursiveAction returns void.
protected void compute() { }

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Concurrency


Chapter 13 - Page 5
e. Begin the compute method. If the number of elements to process is below the
threshold, you should initialize the array.
for (int i = start; i <= end; i++) {
myArray[i] = ThreadLocalRandom.current().nextInt();
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Note: ThreadLocalRandom is used instead of Math.random()because


Math.random() does not scale when executed concurrently by multiple threads and
would eliminate any benefit of applying the Fork-Join framework to this task.
f. Complete the compute method. If the number of elements to process is above or
equal to the threshold you should find the midway point in the array and create two
new RandomArrayAction instances for each section of the array to process. Start
each RandomArrayAction.
Note: When starting a RecursiveAction, you can use the invokeAll method
instead of the fork/join/compute combination typically seen with a
RecursiveTask.
s a
RandomArrayAction r1 = new RandomArrayAction(myArray, )start, h a
midway, threshold);
c m
o ideฺ

RandomArrayAction r2 = new RandomArrayAction(myArray,
r a cle t Gumidway +
1, end, threshold);
@ o e n
invokeAll(r1, r2); t e tu d
5. Modify the main method of the Main class toฺiuse t r
s thisa
the
S
RandomArrayAction class.
a. Comment out the for loop withinnthe r a
d mainumethode that initializes the data array with
a s
random values.
l e x to
b. After the line that creates a ns e
( the ForkJoinPool, create a new RandomArrayAction.
a t e c e
I s tr le ltoi invoke the ForkJoinPool.
c. Use the ForkJoinPool

n d ra erab project by right-clicking the project and choosing Run.


6. Run the ForkJoinFindMax
Note:
x aIf you have
n s fa multi-CPU system you can use System.currentTimeMillis() to
l e
Abenchmark- trathe sequential and Fork-Join solutions.
no n

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Concurrency


Chapter 13 - Page 6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G14:
Lesson
u
@ o e n
Building e
t Database
tu d
t r a S
r a ฺis this with JDBC
Applications
a n d use
l e x to 14
Chapter
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 1
Practices for Lesson 14: Overview

Practices Overview
In these practices, you will work with the JavaDB (Derby) database, creating, reading, updating,
and deleting data from a SQL database by using the Java JDBC API.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 2
Practice 14-1: Summary Level: Working with the Derby Database and
JDBC

Overview
In this practice, you will start the JavaDB (Derby) database, load some sample data using a
script, and write an application to read the contents of an employee database table and print the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

results to the console.

Tasks
1. Create the Employee Database by using the SQL script provided in the resource directory.
a. Open the Services window by selecting Windows > Services, or by pressing Ctrl-5.
b. Expand the Databases folder.
c. Right-click JavaDB and select Start Server.
d. Right-click JavaDB again and select Create Database.
e. Enter the following information: s a
)h a
Window/Page Description Choices or Values
c m
o ideฺ

Database Name EmployeeDB
r a cle t Gu
User Name public
@ o e n
t e tu d
Password tiger
t r a S
Confirm Password tiger
r a ฺis this
f. Click OK a n d use
l e x to
g. Right-click the connection ( a that you
ns e
created:
r a t e i c e
jdbc:derby://localhost:1527/EmployeeDB[public on PUBLIC]and select
Connect. I s t le l
r a r a b
and nD:\labs\resources
h. Select File > Open File.
i.lexBrowseato sfe and open the EmployeeTable.sql script. The file
tr in a SQL Execute window.
A willn-open
o
j. n Select the connection that you created from the drop-down list, and click the Run-SQL
icon or press Ctrl-Shift-E to run the script.
k. Expand the EmployeeDB connection. You will see that the PUBLIC schema is now
created. Expand the PUBLIC Schema and look at the table Employee.
l. Right-click the connection again and select Execute Command to open another SQL
window. Enter the command:
select * from Employee
and click the Run-SQL icon to see the contents of the Employee table.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 3
2. Open the SimpleJDBCExample project and run it.
a. You should see all the records from the Employee table displayed.
3. (Optional) Add a SQL command to add a new Employee record.
a. Modify the SimpleJDBCExample class to add a new Employee record to the
database.
b. The syntax for adding a row in a SQL database is:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

INSERT INTO <table name> VALUES (<column 1 value>, <column 2


value>, ...)
c. Use the Statement executeUpdate method to execute the query. What is the return
type for this method? What value should the return type be? Test to make sure that the
value of the return is correct.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 4
Practice 14-1: Detailed Level: Working with the Derby Database and
JDBC

Overview
In this practice, you will start the JavaDB (Derby) database, load some sample data using a
script, and write an application to read the contents of an employee database table and print the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

results to the console.

Tasks
1. Create the Employee Database by using the SQL script provided in the resource directory.
a. Open the Services Window by selecting Windows > Services, or by pressing Ctrl-5.
b. Expand the Databases folder.
c. Right-click JavaDB and select Start Server.
d. Right-click JavaDB again and select Create Database.
e. Enter the following information: s a
)h a
Window/Page Description Choices or Values
c m
o ideฺ

Database Name EmployeeDB
r a cle t Gu
User Name public
@ o e n
t e tu d
Password tiger
t r a S
Confirm Password tiger
r a ฺis this
f. Click OK. a n d use
l e x to
g. Right-click the connection ( a that you
ns e
created:
r a t e i c e
jdbc:derby://localhost:1527/EmployeeDB[public on PUBLIC]and select
Connect. I s t le l
r a r a b
and nD:\labs\resources
h. Select File > Open File.
i.lexBrowseato sfe and open the EmployeeTable.sql script. The file
tr in a SQL Execute window.
A willn-open
o
j. n Select the connection that you created from the drop-down list and click the Run-SQL
icon or press Ctrl-Shift-E to run the script.
k. Expand the EmployeeDB connection. You will see that the PUBLIC schema is now
created. Expand the PUBLIC Schema, expand Tables, and then expand the table
Employee.
l. Right-click the connection again and select Execute Command to open another SQL
window. Enter the command:
select * from Employee
and click the Run-SQL icon to see the contents of the Employee table.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 5
2. Open the SimpleJDBCExample Project and run it.
a. Select Windows > Projects, or press Ctrl-1.
b. Select File > Open Project.
c. Select D:\labs\12-JDBC\practices\SimpleJDBCExample.
d. Select “Open as Main Project.”
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

e. Click OK.
f. Expand the Source Packages and test packages and look at the
SimpleJDBCExample.java class.
g. Run the project: Right-click the project and select Run, or click the Run icon, or press
F6.
h. You should see all the records from the Employee table displayed.
3. (Optional) Add a SQL command to add a new Employee record.
a. Modify the SimpleJDBCExample class to add a new Employee record to the
database.
s a
b. The syntax for adding a row in a SQL database is:
)h a
INSERT INTO <table name> VALUES (<column 1 value>, <column 2
c m
o ideฺ
value>, ...)

le What uis the return
c. Use the Statement executeUpdate method to execute the
r a cquery. t G
type for this method? What value should the return typeobe? Test e n make sure that the
to
value of the return is correct. t e @ tu d
t r a S
d. Your code may look like this:
r a ฺis this
query = "INSERT INTO Employee n d VALUES u s e (200, 'Bill',
e a
x 150000)";
to
'Murray','1950-09-21',
( a l e
a t e
if (stmt.executeUpdate(query)
c e ns != 1) {
s tr le li ("Failed to add a new employee record");
System.out.println
I
}
n d ra erab
Note:
x aIf you run
n s f application again, it will throw an exception, because this key already
the
e
l in-the
Aexists tradatabase.
no n

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 6
Practice 14-2: Summary Level: Using the Data Access Object Pattern

Overview
In this practice, you will take the existing Employee DAO Memory application and refactor the
code to use JDBC instead. The solution from the “Exceptions and Assertions” lesson has been
renamed to EmployeeDAOJDBC. You will need to create an EmployeeDAOJDBCImpl class to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

replace the EmployeeDAOMemoryImpl class, and modify the EmployeeDAOFactory to


return an instance of your new implementation class instead of the Memory version.
You will not have to alter the other classes. This example illustrates how a well designed Data
Access Object application can use an alternative persistence class without significant change.

Tasks
1. Open and examine the EmployeeDAOJDBC project in the
D:\labs\12-JDBC\practices folder.
a. In the com.example.test package, you see the class a
EmployeeTestInteractive. This class contains the main method and provides a
h a s
)
console-based user interface. Through this UI, you will be able to create new records,
m
ฺ c o
read all the records, update a record, and delete a record from the Employee
d e ฺ
cle t Gu i
database. Note how the main method creates an instance of a Data Access Object
(DAO). o r a n
e @ d e
t r a t S tu
b. In the com.example.model package, look at the Employee class. This class is a

r a ฺis this
Plain Old Java Object (POJO) that encapsulates all of the data from a single employee
record and row in the Employee table. Note that there are no set methods in this class,
a n d use
only get methods. Once an Employee object is created, it cannot be changed. It is
immutable. l e x to
( a ns e
a t e
c. Expand the com.example.dao package. Look at the EmployeeDAO class and you
c e
s tr le li
see the methods that an implementation of this interface is expected to implement.
I
n d ra erab
Each of these methods throws a DAOException. Note that this interface extends
x a n s f
AutoCloseable. Therefore, you will need to provide a close() method to satisfy the
e
Al n-tra
contract with AutoCloseable.

no
d. Look at the EmployeeDAOFactory. You see that this class has one method,
getFactory(), that returns an instance of an EmployeeDAOMemoryImpl.
e. Look at the EmployeeDAOMemoryImpl class. This class is the workhorse of the DAO
pattern. This is the class that the EmployeeDAOJDBCFactory returns as an instance
from the createEmployeeDAO method. This is the class that you will replace with a
JDBC implementation.
2. Create a new class, EmployeeDAOJDBCImpl, that implements EmployeeDAO in the
com.example.dao package.
a. Note that the class has an error.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 7
3. Implement the method signatures defined by EmployeeDAO.
a. Click anywhere in the line that is showing an error (a light bulb with a red dot on it):
public class EmployeeDAOJDBCImpl implements EmployeeDAO {
b. Press the Alt-Enter key combination to show the suggestions for fixing the error in this
class. You should see the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Note: Your line numbers may differ from the picture shown.
c. The class must implement all the methods in the interface because this is a concrete
class (not abstract). You can have NetBeans provide all the method bodies by pressing
the Enter key to accept the suggestion “Implement all abstract methods.”
d. You will notice that the error in the file goes away immediately, and NetBeans has
s
provided all the method signatures based on the EmployeeDAO interface declarations. a
) h a
e. Your next task is to add a constructor and fill in the bodies of the methods.
c o m e ฺ
4. ฺ
Add a private instance variable, con, to hold a Connection object instance. i d
5. a cle t Gu
Write a package-level constructor for the class. The constructor for this class will create an
r
o e n
instance of a Connection object that the methods of this class can reuse during the
@
t e tu d
t r a
lifetime of the application. Be sure to catch a SQLException.
S
6. ฺis this
Write a method body for the add method. The add method creates a new record in the
r a
n d use
database from the Employee object passed in as a parameter. Recall that the SQL
a
e x to
command to create a new record in the database is: INSERT INTO <table> VALUES
l
( a ns e
(...).
a t e c e
I s tr le li
Note: Use single quotes for the strings and the date.

n d ra erab
a. Rethrow any SQLException caught as a DAOException.
7. a s f
Write a method body for the findById method. This method is used by the update and
x n
e
Al n-tra
delete methods and is used to locate a single record to display. Recall that the SQL
no
command to read a single record is: SELECT * FROM <table> WHERE <pk>=<value>.
a. Rethrow any SQLException caught as a DAOException.
8. Write a method body for the update method. The update method updates an existing
record in the database from the Employee object passed in as a parameter. Recall that the
SQL command to create a new record in the database is: UPDATE <table> SET
COLUMNNAME=<value>, COLUMNNAME=<value>, ... WHERE <pk>=<value>.
Note: Be sure to add single quotes around string and date values.
a. Rethrow any SQLException caught as a DAOException.
9. Write a method body for the delete method. The delete method tests to see whether an
employee exists in the database by using the findById method, and then deletes the
record if it exists. Recall that the SQL command to delete a record from the database is:
DELETE FROM <table> WHERE <pk>=<value>.
a. Rethrow any SQLException caught as a DAOException.
10. Write the method body for the getAllEmployees method. This method returns an array of
Employee records. The SQL query to return all records is quite simple: SELECT * FROM
<table>.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 8
a. Rethrow any SQLException caught as a DAOException.
11. Write the method body for the close method. This method is defined by the
AutoCloseable interface. This method should explicitly close the Connection object
that you created in the constructor.
a. Rather than rethrow the SQLException, simply report it.
12. Save the class. Fix any missing imports and compilation errors if you have not already done
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

so.
13. Update the EmployeeDAOFactory to return an instance of your new
EmployeeDAOJDBCImpl.
return new EmployeeDAOJDBCImpl();
14. Add the JDBC Derby driver class to the project, but adding the derbyclient.jar file to
the Libraries for the project.
a. Right-click the Libraries folder in the project and select Add Jar/Folder.
b. Browse to D:\Program Files\Java\jdk1.7.0\db\lib.
c. Select derbyclient.jar. s a
) h a
d. Absolute Path should be checked. m
ฺ c o d e ฺ
e. Click Open.
cle t Gu i
r a
15. Save the updated class, and if you have no errors, compile and run the project. This
o n
@ e
application has an interactive feature that allows you to query the database and read one or
e d
a t tu
all of the records, find an employee by ID, and update and delete an employee record.
t r S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 9
Practice 14-2: Detailed Level: Using the Data Access Object Pattern

Overview
In this practice, you will take the existing Employee DAO Memory application and refactor the
code to use JDBC instead. The solution from the “Exceptions and Assertions” lesson has been
renamed to EmployeeDAOJDBC. You will need to create an EmployeeDAOJDBCImpl class to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

replace the EmployeeDAOMemoryImpl class, and modify the EmployeeDAOFactory to


return an instance of your new implementation class instead of the Memory version.
You will not have to alter the other classes. This example illustrates how a well designed Data
Access Object application can use an alternative persistence class without significant change.

Tasks
1. Open and examine the EmployeeDAOJDBC project in the
D:\labs\12-JDBC\practices folder.
a. In the com.example.test package, you see the class a
EmployeeTestInteractive. This class contains the main method and provides a
h a s
)
console-based user interface. Through this UI, you will be able to create new records,
m
ฺ c o
read all the records, update a record, and delete a record from the Employee
d e ฺ
cle t Gu i
database. Note how the main method creates an instance of a Data Access Object
(DAO). o r a n
e @ d e
t r a t S tu
b. In the com.example.model package, look at the Employee class. This class is a

r a ฺis this
Plain Old Java Object (POJO) that encapsulates all the data from a single employee
record and row in the Employee table. Note that there are no set methods in this class,
a n d use
only get methods. Once an Employee object is created, it cannot be changed. It is
immutable. l e x to
( a ns e
a t e
c. Expand the com.example.dao package. Look at the EmployeeDAO class and you
c e
s tr le li
see the methods that an implementation of this interface is expected to implement.
I
n d ra erab
Each of these methods throws a DAOException. Note that this interface extends
x a n s f
AutoCloseable; therefore, you will need to provide a close() method to satisfy the
e
Al n-tra
contract with AutoCloseable.

no
d. Look at the EmployeeDAOFactory. You see that this class has one method,
getFactory(), that returns an instance of an EmployeeDAOMemoryImpl.
e. Look at the EmployeeDAOMemoryImpl class. This class is the workhorse of the DAO
pattern. This is the class that the EmployeeDAOJDBCFactory returns as an instance
from the createEmployeeDAO method. This is the class that you will replace with a
JDBC implementation.
2. Create a new class, EmployeeDAOJDBCImpl, in the com.example.dao package.
a. Right-click on the com.example.dao package and choose New Java Class
b. Enter EmployeeDAOJDBCImpl as the class name and click Finish.
c. Change this class to implement EmployeeDAO.
d. Note that causes an error.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 10
3. Implement the method signatures defined by EmployeeDAO.
a. Click anywhere in the line that is showing an error (a light bulb with a red dot on it):
public class EmployeeDAOJDBCImpl implements EmployeeDAO {
b. Press the Alt-Enter key combination to show the suggestions for fixing the error in this
class. You should see the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Note: Your line numbers may differ from the picture shown.
c. The class must implement all the methods in the interface because this is a concrete
class (not abstract). You can have NetBeans provide all of the method bodies by
pressing the Enter key to accept the suggestion “Implement all abstract methods.”
d. You will notice that the error in the file goes away immediately, and NetBeans has
provided all the method signatures based on the EmployeeDAO interface declarations.
s a
)h
e. Your next task is to add a constructor and fill in the bodies of the methods.
a
4. Add a private instance variable, con, to hold a Connection object instance.
c m
o ideฺ

private Connection con = null;
r a cle t Gu
5. Write a constructor for the class. The constructor for this@ o will create
class e n an instance of a
Connection object that the methods of this class a e
t reuseSduring
can
d
tu the lifetime of the
t r
application.
r a ฺis this
d uaccess.
a. Write the constructor to use package-level
n s e This will enable only classes within
a
x of this
the package to create an instance
e to class (like the EmployeeDAOFactory).
( a l e
EmployeeDAOJDBCImpl()
a t e c e
{
ns
I s tr lusing
b. Open the connection
e li the JDBC URL, name, and password from the
application:
n d ra erab
SimpleJDBCExample

x a
String
n s
urlf = "jdbc:derby://localhost:1527/EmployeeDB";
e
Al String- tra username = "public";
n
noString password = "tiger";
c. In a try block (not a try-with-resources, because you want to keep this connection
open until you exit the application) create an instance of a Connection object and
catch any exception. If the connection cannot be made, exit the application.
Note: Ideally you would rather indicate to the user that the connection could not be
made and retry the connection a number of times before exiting.
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException se) {
System.out.println("Error obtaining connection with the
database: " + se);
System.exit(-1);
}
6. Write a method body for the add method. The add method creates a new record in the
database from the Employee object passed in as a parameter. Recall that the SQL

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 11
command to create a new record in the database is: INSERT INTO <table> VALUES
(...).
a. Delete the boiler-plate code created by NetBeans for the add method.
b. Look at the other methods in the class. They each begin by creating an instance of a
Statement object in a try-with-resources statement:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

try (Statement stmt = con.createStatement()) {

}
c. Inside the try block, create a query to insert the values passed in the Employee
instance to the database. Your query string should look something like this:
String query = "INSERT INTO EMPLOYEE VALUES (" + emp.getId()
+ ", '" + emp.getFirstName() + "', "
+ "'" + emp.getLastName() + "', "
+ "'" +
s a
new java.sql.Date(emp.getBirthDate().getTime()) + "',"
)h a
+ emp.getSalary() + ")";
c m
o ideฺ
Note the use of single quotes for the strings and the date. ฺ
r
d. Since you are not expecting a result from the query, the appropriate a cle tStatement
G u class
o n
method to use is updateQuery. Make sure to test @
t e t u deFortheexample:
to see whether statement
executed properly by looking at the integer result
s a
tr is S
of the method.
if (stmt.executeUpdate(query) r ฺ i
a 1)e {th
!=
throw new DAOException("Error
d
an to us adding employee");
e x
}
e ( al nse
e. At the end of the
s t r atryt block,liccatch
e any SQLException thrown, and wrap them in the
a I to bbelehandled by the calling application. For example:
DAOException
r
n f e ra
d (SQLException
x a
catch
s se) {
ran new DAOException("Error adding employee in DAO", se);
Ale }n-tthrow
n o
7. Write a method body for the findById method. This method is used by the update and
delete methods and is used to locate a single record to display. Recall that the SQL
command to read a single record is: "SELECT * FROM <table> WHERE
<pk>=<value>".
a. Delete the boiler-plate code created by NetBeans for the findById method.
b. Create an instance of a Statement object in a try-with-resources block:
try (Statement stmt = con.createStatement()) {

}
c. Inside the try block, write a query statement to include the integer id passed in as an
argument to the method and execute the query, returning a ResultSet instance:
String query = "SELECT * FROM EMPLOYEE WHERE ID=" + id;
ResultSet rs = stmt.executeQuery(query);
d. Test the ResultSet instance for null using the next() method and return the result
as a new Employee object:
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 12
if (!rs.next()) {
return null;
}
return (new Employee(rs.getInt("ID"),
rs.getString("FIRSTNAME"),
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

rs.getString("LASTNAME"),
rs.getDate("BIRTHDATE"),
rs.getFloat("SALARY")));
e. At the end of the try block, catch any SQLException thrown, and wrap them in the
DAOException to be handled by the calling application. For example
catch (SQLException se) {
throw new DAOException("Error finding employee in DAO", se);
}
8. Write a method body for the update method. The update method updates an existing s a
)h a
record in the database from the Employee object passed in as a parameter. Recall that the
SQL command to create a new record in the database is: "UPDATE <table> SET
c m
o ideฺ

COLUMNNAME=<value>, COLUMNNAME=<value>, ... WHERE <pk>=<value>".
r a cle t Gu
o
Note: Be sure to add single quotes around string and date values.
@ e n
t e tu d
a. Delete the boiler-plate code created by NetBeans for the update method.
t r a S
r a ฺis this
b. Create an instance of a Statement object in a try-with-resources block:

a n d use
try (Statement stmt = con.createStatement()) {
x
le se t o
( a
}
t r a te licen
Isblock,bcreate
c. Inside the try
r a le the SQL UPDATE query from the Employee object passed
in: d
n query f er a
x a n s
Ale n-t+ra"SET FIRSTNAME='" + emp.getFirstName() + "',"
String = "UPDATE EMPLOYEE "

no + "LASTNAME='" + emp.getLastName() + "',"


+ "BIRTHDATE='" + new
java.sql.Date(emp.getBirthDate().getTime()) + "',"
+ "SALARY=" + emp.getSalary()
+ "WHERE ID=" + emp.getId();
d. You may want to test to see that the update was successful by evaluating the return
value of the executeUpdate method:
if (stmt.executeUpdate(query) != 1) {
throw new DAOException("Error updating employee");
}
e. At the end of the try block, catch any SQLException thrown, and wrap them in the
DAOException to be handled by the calling application. For example
catch (SQLException se) {
throw new DAOException("Error updating employee in DAO",
se);
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 13
}
9. Write a method body for the delete method. The delete method tests to see whether an
employee exists in the database by using the findById method, and then deletes the
record if it exists. Recall that the SQL command to delete a record from the database is:
"DELETE FROM <table> WHERE <pk>=<value>".
a. Delete the boiler-plate code created by NetBeans for the delete method.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

b. Call the findById method with the id passed in as a parameter and if the record
returned is null, throw a new DAOException.
Employee emp = findById(id);
if (emp == null) {
throw new DAOException("Employee id: " + id + " does not
exist to delete.");
}
c. Create an instance of a Statement object in a try-with-resources block:
s a
try (Statement stmt = con.createStatement()) {
)h a
c m
o ideฺ

}
r a cle t Gu
d. Inside the try block, create the SQL DELETE query andotest the e n returned to
result
e @ tu d
make sure a single record was altered – throw atnew DAOException if not:
t r a S
String query = "DELETE FROM EMPLOYEE
a ฺis thWHEREis ID=" + id;
if (stmt.executeUpdate(query)
r
nd us != 1) {e
e x a to
( a l
throw new DAOException("Error
s e deleting employee");
}
t r a te licen
r a Isthe trybblock,
e. At the end of l e catch any SQLException thrown, and wrap them in the
a n d fertoa be handled by the calling application. For example:
DAOException

l e s
xcatchra(SQLException
n se) {
A n-tthrow new DAOException("Error deleting employee in DAO",
nose);
}

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 14
10. Write the method body for the getAllEmployees method. This method returns an array of
Employee records. The SQL query to return all records is quite simple: "SELECT * FROM
<table>".
a. Delete the boiler-plate code created by NetBeans for the getAllEmployees method.
b. Create an instance of a Statement object in a try-with-resources block:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

try (Statement stmt = con.createStatement()) {

}
c. Inside the try block, create and execute the query to return all the employee records:
String query = "SELECT * FROM EMPLOYEE";
ResultSet rs = stmt.executeQuery(query);
d. The easiest way to create an array of employees to return is to use a Collection object,
ArrayList, and then convert the ArrayList object to an array. Iterate through the
a
ResultSet and add each record to the ArrayList. In the return statement, use the
s
toArray method to convert the collection to an array:
)h a
ArrayList<Employee> emps = new ArrayList<>();
c m
o ideฺ

while (rs.next()) {
r a cle t Gu
emps.add(new Employee(rs.getInt("ID"),
@ o e n
t e tu
rs.getString("FIRSTNAME"), d
t r a S
r a ฺis this
rs.getString("LASTNAME"),

a n d use
rs.getDate("BIRTHDATE"),

l e x rs.getFloat("SALARY")));
to
}
( a ns e
a t e c e
return emps.toArray(new Employee[0]);
I
e. At the end ofs tr le licatch any SQLException thrown, and wrap them in the
the try block,
n d ra ertoabbe handled by the calling application. For example:
x
DAOException
n s f
a (SQLException
e ra new DAOException("Error
Al n-tthrow
catch se) {

nose);
getting all employees in DAO",

}
11. Write the method body for the close method. This method is defined by the
AutoCloseable interface. This method should explicitly close the Connection object
that you created in the constructor.
a. Delete the boiler-plate code created by NetBeans for the close method.
b. In a try block (you must use a try block, because Connection.close throws an
exception that must be caught or rethrown), call the close method on the
Connection object instance, con. Rather than rethrow the exception, simply report it.
try {
con.close();
} catch (SQLException se) {
System.out.println ("Exception closing Connection: " + se);
}
12. Save the class. Fix any missing imports and compilation errors if you have not already.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 15
13. Update the EmployeeDAOFactory to return an instance of your new
EmployeeDAOJDBCImpl.
return new EmployeeDAOJDBCImpl();
14. Add the JDBC Derby driver class to the project, by adding the derbyclient.jar file to
the Libraries for the project.
a. Right-click the Libraries folder in the project and select Add Jar/Folder.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

b. Browse to D:\Program Files\Java\jdk1.7.0\db\lib.


c. Select derbyclient.jar.
d. Absolute Path should be checked.
e. Click Open.
15. Save the updated class, and if you have no errors, compile and run the project. This
application has an interactive feature that allows you to query the database and read one or
all of the records, find an employee by ID, and update and delete an employee record.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 16
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G15:
Lesson
u
@ o e n
Localizationt e tu d
t r a S
r a ฺis 15 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 1
Practices for Lesson 15: Overview

Practices Overview
In these practices, you create a date application that is similar to the example used in the
lesson. For each practice, a NetBeans project is provided for you. Complete the project as
indicated in the instructions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 2
Practice 15-1: Summary Level: Creating a Localized Date Application

Overview
In this practice, you create a text-based application that displays dates and times in a number of
different ways. Create the resource bundles to localize the application for French, Simplified
Chinese, and Russian.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have attended the lecture for this lesson. You have access to the JDK7 API documentation.

Summary
Create a simple text-based date application that displays the following date information for
today:
• Default date
• Long date a
• Short date h a s
m )
• Full date
ฺ c o d e ฺ
• Full time cle t Gu i
• Day of the week o r a n
e @ d e

t r a t S tu
And a custom day and time that displays: day of the week, long date, era, time, and time
zone
r a ฺis this
a n d use
Localize the application so that it displays this information in Simplified Chinese and Russian.

l e x
The user should be able to switch between the languages.
to
( a ns e
The application output in English is shown here.
a t e c e
I s tr le li
=== Date App ===

n d ra erab
Default Date is: Aug 1, 2011

x a s f
Long Date is: August 1, 2011
n
e
Al n-tra
Short Date is: 8/1/11

no Full Date is: Monday, August 1, 2011


Full Time is: 10:13:56 AM MDT
Day of week is: Monday
My custom day and time is: Monday August 1, 2011 AD 10:13:56
Mountain Daylight Time

--- Choose Language Option ---


1. Set to English
2. Set to French
3. Set to Chinese
4. Set to Russian
q. Enter q to quit
Enter a command:

Tasks
Open the Localized-Practice01 project in NetBeans and make the following changes:
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 3
1. Edit the DateApplication.java file.
2. Create a message bundle for Russian and Simplified Chinese.
• The translated text for the menus can be found in the MessagesText.txt file in the
practices directory.
3. Add code to display the specified date formats (indicated with comments) and localized
text.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

4. Add code to change the Locale based on the user input.


5. Run the DateApplication.java file and verify that it operates as described.

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 4
Practice 15-1: Detailed Level: Creating a Localized Date Application

Overview
In this practice, you create a text-based application that displays dates and times in a number of
different ways. Create the resource bundles to localize the application for French, Simplified
Chinese, and Russian.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have attended the lecture for this lesson. You have access to the JDK7 API documentation.

Summary
Create a simple text-based date application that displays the following date information for
today:
• Default date
• Long date a
• Short date h a s
m )
• Full date
ฺ c o d e ฺ
• Full time cle t Gu i
• Day of the week o r a n
e @ d e

t r a t S tu
And a custom day and time that displays: day of the week, long date, era, time, and time
zone
r a ฺis this
a n d use
Localize the application so that it displays this information in Simplified Chinese and Russian.

l e x
The user should be able to switch between languages.
to
( a ns e
The application output in English is shown here.
a t e c e
I s tr le li
=== Date App ===

n d ra erab
Default Date is: Aug 1, 2011

x a s f
Long Date is: August 1, 2011
n
e
Al n-tra
Short Date is: 8/1/11

no Full Date is: Monday, August 1, 2011


Full Time is: 10:13:56 AM MDT
Day of week is: Monday
My custom day and time is: Monday August 1, 2011 AD 10:13:56
Mountain Daylight Time

--- Choose Language Option ---


1. Set to English
2. Set to French
3. Set to Chinese
4. Set to Russian
q. Enter q to quit
Enter a command:

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 5
Tasks
Open the Localized-Practice01 project in NetBeans and make the following changes:
1. Edit the DateApplication.java file.
2. Open the MessagesText.txt file found in the practices directory for this practice in a
text editor.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

3. Create a message bundle file for Russian text named


MessagesBundle_ru_RU.properties.
 Right-click the project and select New > Other > Other > Properties File.
 Click Next.
 Enter MessagesBundle_ru_RU in the File Name field.
 Click Browse.
 Select the src directory.
 Click Select Folder.
 Click Finish.
s a
 Paste the localized Russian text into the file and save it. )h a
4. Create a message bundle file for Simplified Chinese text named
c m
o ideฺ

MessagesBundle_zh_CN.properties.
r a cle t Gu
o n
 Right-click the project and select New > Other > Other > Properties File.
@ e
 Click Next. t e tu d
t r a S
r a ฺis this
 Enter MessagesBundle_zh_CN in the File Name field.
 Click Finish.
a n d use
e x to
 Paste the localized Simplified Chinese text into the file and save it.
l
5. ( a ns e
Update the code that sets the locale based on user input.
a t e c e
I
publics tvoid l e li
r setEnglish(){
n d f e rab
ra currentLocale = Locale.US;
a
x ran s
Ale currentLocale);
messages = ResourceBundle.getBundle("MessagesBundle",

o n -t
n }

public void setFrench(){


currentLocale = Locale.FRANCE;
messages = ResourceBundle.getBundle("MessagesBundle",
currentLocale);
}

public void setChinese(){


currentLocale = Locale.SIMPLIFIED_CHINESE;
messages = ResourceBundle.getBundle("MessagesBundle",
currentLocale);
}

public void setRussian(){


currentLocale = ruLocale;
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 6
this.messages =
ResourceBundle.getBundle("MessagesBundle", currentLocale);
}
6. Add the code that displays the date information to the printMenu method.
df = DateFormat.getDateInstance(DateFormat.DEFAULT,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

currentLocale);
pw.println(messages.getString("date1") + " " +
df.format(today));
df = DateFormat.getDateInstance(DateFormat.LONG,
currentLocale);
pw.println(messages.getString("date2") + " " +
df.format(today));
df = DateFormat.getDateInstance(DateFormat.SHORT,
currentLocale);
pw.println(messages.getString("date3") + " " +
s a
df.format(today));
) h a
df = DateFormat.getDateInstance(DateFormat.FULL,
c o m e ฺ
ฺ i d
currentLocale);
r a cle t Gu
pw.println(messages.getString("date4") + " " +
@ o e n
df.format(today));
t e tu d
t r a S
df = DateFormat.getTimeInstance(DateFormat.FULL,
currentLocale);
r a ฺis this
a n d use
pw.println(messages.getString("date5") + " " +
df.format(today)); l e x to
( a ns e
t e e
sdf = new SimpleDateFormat("EEEE", currentLocale);
a c
I s tr le li
pw.println(messages.getString("date6") + " " +

n d ra erab
sdf.format(today));

x a n s f
sdf = new SimpleDateFormat("EEEE MMMM d, y G kk:mm:ss
e
Al n-tra
zzzz", currentLocale);

no pw.println(messages.getString("date7") + " " +


sdf.format(today));
7. Run the DateApplication.java file and verify that it operates as described.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 7
Practice 15-2: Summary Level: Localizing a JDBC Application
(Optional)

Overview
In this practice, you localize the JDBC application that you created in the practices for the
“Building Database Applications with JDBC” lesson.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

Assumptions
You have attended the lecture for this lesson. You have completed the practices for the
“Building Database Applications with JDBC” lesson.

Summary
Localize the JDBC application from the previous lesson. Identify any object that displays menu
or object information and change them so that localized messages are displayed instead of
static text.
Localize the application so that it displays this information in English, French, and Russian. The s a
user should be able to switch between languages. )h a
c m
o ideฺ

Tasks
r a cle t Gu
You have a couple of project choices in this lab. First you can use
@ o the project
e n files from Lesson
14, Practice 2, “Using the Data Access Object Pattern,” and t e just continue
t d
uthe following
with that project.
Alternatively, open the Practice02 project for thisslesson. t r a S
Perform
s steps:
ฺ i t h i
1. Open the EmployeeTestInteractive.java
n d ra file. s e Examine the source code and
determine which messages printed xato the console
t o u should be converted into resource
bundles. Notice that not all text
( l
a nseeoutput is included in this class file.
Note: You do not have
r e
attoshould
includee
i cbeerror messages in the bundle. Only prompt and
s
informational messages
I t l included.
leinterface is required.
r a r a b
x a ndthe main
2. A slight change
s
to
f the user
einterface
Currently n looks like this:
Ale [C]reate
n- t r a | [R]ead | [U]pdate | [D]elete | [L]ist | [Q]uit:
n o
Changing the user interface to the following makes it easier to translate just the words in
the menu.
[C] - Create | [R] - Read | [U] - Update | [D] - Delete | [L] -
List | [S] – Set Language | [Q] - Quit:
This separates the single character commands from the words. For the solution only the
words were translated. You could, of course, translate both. Notice a new option has been
added to set the language.
3. Create a message bundle for English, French, and Russian.
• The translated text for the menus can be found in the MessagesText02.txt file in
the practices directory.
4. Add a ResourceBundle object to any object that displays menu-related information.
Replace the static text with a call to the resource bundle and get the appropriate string
message.
5. Examine all the date-related source code. Make sure that date information will print in the
appropriate localized format.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 8
6. When you have finished, run EmployeeTestInteractive.java and make sure that all
the menus have been localized.
7. Additional improvements you could make:
• Localize all the error messages in the application.
• Localize the single character options for the main menu.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ

s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 10

You might also like