Download as pdf or txt
Download as pdf or txt
You are on page 1of 214

CETPA Infotech Pvt Ltd

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

s a
Java SE 7 Programming ) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
r Guide
Activity
u s S
t p h i
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

D67238GC20
Edition 2.0
June 2012
D74998
CETPA Infotech Pvt Ltd

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

Michael Williams Disclaimer

Tom McGinn This document contains proprietary information and is protected by copyright and
Matt Heimer 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
Technical Contributors may not use, share, download, upload, copy, print, display, perform, reproduce,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

publish, license, post, transmit, or distribute this document in whole or in part without
and Reviewers the express authorization of Oracle.
Peter Hall
The information contained in this document is subject to change without notice. If you
Marnie Knue 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
Lee Klement warranted to be error-free.
Steve Watts
Restricted Rights Notice
Brian Earl
Vasily Strelnikov 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
Andy Smith applicable:
Nancy K.A.N
U.S. GOVERNMENT RIGHTS
Chris Lamb The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or

s a
disclose these training materials are restricted by the terms of the applicable Oracle
Todd Lowry
Ionut Radu
license agreement and/or the applicable U.S. Government contract.
)h ฺ a
Trademark Notice m
o ide
Joe Darcy
a i l ฺitscaffiliates.uOther names
Brian Goetz
may be trademarks of their respective owners. gm
Oracle and Java are registered trademarks of Oracle and/or
t G
Alan Bateman
8 @ u d en
David Holmes
p u ri0 is St
l s at e th
Editors
n c ha to us
Richard Wallis
( a a se
Daniel Milne
u i
r licen
a t
Vijayalakshmi Narasimhan p le
l S a b
c ha sfer
GraphicnDesigner
AaHansn-tran
James
no
Publishers
Syed Imtiaz Ali
Sumesh Koshy
CETPA Infotech Pvt Ltd

Table of Contents
Practices for Lesson 1: Introduction ........................................................................................................ 1-1
Practices for Lesson 1: Overview............................................................................................................. 1-2
Practice 1-1: Verifying Software Installation ............................................................................................. 1-3
Practice 1-2: Software Installation............................................................................................................ 1-5
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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


Practices for Lesson 2: Java Syntax and Class Review .......................................................................... 2-1
Practices for Lesson 2: Overview............................................................................................................. 2-2
Practice 2-1: Summary Level: Creating Java Classes............................................................................... 2-3
Practice 2-1: Detailed Level: Creating Java Classes ................................................................................. 2-5
Practices for Lesson 3: Encapsulation and Subclassing ........................................................................ 3-1
Practices for Lesson 3: Overview............................................................................................................. 3-2
Practice 3-1: Summary Level: Creating Subclasses.................................................................................. 3-3
Practice 3-1: Detailed Level: Creating Subclasses.................................................................................... 3-6
(Optional) Practice 3-2: Adding a Staff to a Manager ................................................................................ 3-11
Practices for Lesson 4: Java Class Design .............................................................................................. 4-1
s a
Practices for Lesson 4............................................................................................................................. 4-2
Practice 4-1: Summary Level: Overriding Methods and Applying Polymorphism ........................................ 4-3 )h ฺ a
o m
ilฺc Guide5-1
Practice 4-1: Detailed Level: Overriding Methods and Applying Polymorphism .......................................... 4-6
a
Practices for Lesson 5: Advanced Class Design .....................................................................................

@ gm ent
Practices for Lesson 5: Overview............................................................................................................. 5-2
8 u d
p u ri0 is St
Practice 5-1: Summary Level: Applying the Abstract Keyword .................................................................. 5-3

Practice 5-2: Summary Level: Applying the Singleton lDesign a t


Practice 5-1: Detailed Level: Applying the Abstract Keyword ....................................................................
s Pattern t h 5-7

h a u s e.........................................................
....................................................... 5-12
Practice 5-2: Detailed Level: Applying the Singleton
a n c ....................................................................................
Design
t o Pattern 5-14

i ( a
(Optional) Practice 5-3: Using Java Enumerations
n s e 5-16

t p ur Nested
(Optional) Practice 5-4: Recognizing
l i e ............................................................................... 5-18
cClasses
S a
(Optional) Solution 5-4: Recognizing
b l e
Nested Classes ............................................................................... 5-19

c h al 6: Inheritance
Practices for Lesson
f e ra with Java Interfaces ........................................................................ 6-1
Practicesn s ............................................................................................................. 6-2
nLevel:
for Lesson 6: Overview
Aa6-1:nSummary
Practice - t r a Implementing an Interface ......................................................................... 6-3

n o
Practice 6-1: Detailed Level: Implementing an Interface ........................................................................... 6-6
Practice 6-2: Summary Level: Applying the DAO Pattern .......................................................................... 6-11
Practice 6-2: Detailed Level: Applying the DAO Pattern ............................................................................ 6-13
(Optional) Practice 6-3: Implementing Composition .................................................................................. 6-18
Practices for Lesson 7: Generics and Collections ................................................................................... 7-1
Practices for Lesson 7: Overview............................................................................................................. 7-2
Practice 7-1: Summary Level: Counting Part Numbers by Using HashMaps.............................................. 7-3
Practice 7-1: Detailed Level: Counting Part Numbers by Using HashMaps ................................................ 7-5
Practice 7-2: Summary Level: Matching Parentheses by Using a Deque ................................................... 7-7
Practice 7-2: Detailed Level: Matching Parentheses by Using a Deque ..................................................... 7-8
Practice 7-3: Summary Level: Counting Inventory and Sorting by Using Comparators ............................... 7-10
Practice 7-3: Detailed Level: Counting Inventory and Sorting by Using Comparators ................................. 7-13
Practices for Lesson 8: String Processing............................................................................................... 8-1
Practices for Lesson 8: Overview............................................................................................................. 8-2
Practice 8-1: Summary Level: Parsing Text with split() ............................................................................. 8-3

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

Java SE 7 Programming Table of Contents


iii
CETPA Infotech Pvt Ltd

Practice 8-1: Detailed Level: Parsing Text with split() ............................................................................... 8-5
Practice 8-2: Summary Level: Creating a Regular Expression Search Program......................................... 8-8
Practice 8-2: Detailed Level: Creating a Regular Expression Search Program ........................................... 8-9
Practice 8-3: Summary Level: Transforming HTML by Using Regular Expressions .................................... 8-11
Practice 8-3: Detailed Level: Transforming HTML by Using Regular Expressions ...................................... 8-13
Practices for Lesson 9: Exceptions and Assertions ................................................................................ 9-1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Practices for Lesson 9: Overview............................................................................................................. 9-2


Practice 9-1: Summary Level: Catching Exceptions.................................................................................. 9-3
Practice 9-1: Detailed Level: Catching Exceptions .................................................................................... 9-6
Practice 9-2: Summary Level: Extending Exception.................................................................................. 9-9
Practice 9-2: Detailed Level: Extending Exception .................................................................................... 9-13
Practices for Lesson 10: Java I/O Fundamentals ..................................................................................... 10-1
Practices for Lesson 10: Overview ........................................................................................................... 10-2
Practice 10-1: Summary Level: Writing a Simple Console I/O Application.................................................. 10-3
Practice 10-1: Detailed Level: Writing a Simple Console I/O Application.................................................... 10-5
Practice 10-2: Summary Level: Serializing and Deserializing a ShoppingCart ........................................... 10-8
Practice 10-2: Detailed Level: Serializing and Deserializing a ShoppingCart.............................................. 10-11
Practices for Lesson 11: Java File I/O (NIO.2) .......................................................................................... 11-1
s a
)h ฺ a
Practices for Lesson 11: Overview ........................................................................................................... 11-2
o m
ilฺc Guide
Practice 11-1: Summary Level: Writing a File Merge Application ............................................................... 11-3

a
Practice 11-1: Detail Level: Writing a File Merge Application..................................................................... 11-6
gm ent
Practice 11-2: Summary Level: Recursive Copy ....................................................................................... 11-10
@
r i 0 8 Stud
Practice 11-2: Detailed Level: Recursive Copy ......................................................................................... 11-12

a t pu this
(Optional) Practice 11-3: Summary Level: Using PathMatcher to Recursively Delete ................................. 11-15
(Optional) Practice 11-3: Detailed Level: Using PathMatcher to Recursively Delete ................................... 11-17

h a ls use
Practices for Lesson 12: Threading ......................................................................................................... 12-1
n
a se c t o
Practices for Lesson 12: Overview ........................................................................................................... 12-2
i ( a n
Practice 12-1: Detailed Level: t p ur licAccess
Practice 12-1: Summary Level: Synchronizing
Synchronizing
e to Shared Data........................................................ 12-6
Access to Shared Data ...................................................... 12-3

l S aLevel: Implementing
b le a Multithreaded Program .................................................... 12-10
Practice 12-2: Summary
a Level:
hDetailed f a
erImplementing a Multithreaded Program ...................................................... 12-12
c
Practice 12-2:
n s
Aafor Lesson
Practices
- t r a13:n Concurrency ..................................................................................................... 13-1
forn
Practices o Lesson 13: Overview ........................................................................................................... 13-2
n
(Optional) Practice 13-1: Using the java.util.concurrent Package .............................................................. 13-3
(Optional) Practice 13-2: Using the Fork-Join Framework ......................................................................... 13-5
Practices for Lesson 14: Building Database Applications with JDBC ..................................................... 14-1
Practices for Lesson 14: Overview ........................................................................................................... 14-2
Practice 14-1: Summary Level: Working with the Derby Database and JDBC............................................ 14-3
Practice 14-1: Detailed Level: Working with the Derby Database and JDBC.............................................. 14-5
Practice 14-2: Summary Level: Using the Data Access Object Pattern...................................................... 14-7
Practice 14-2: Detailed Level: Using the Data Access Object Pattern........................................................ 14-10
Practices for Lesson 15: Localization ...................................................................................................... 15-1
Practices for Lesson 15: Overview ........................................................................................................... 15-2
Practice 15-1: Summary Level: Creating a Localized Date Application ...................................................... 15-3
Practice 15-1: Detailed Level: Creating a Localized Date Application ........................................................ 15-5
Practice 15-2: Summary Level: Localizing a JDBC Application (Optional).................................................. 15-8

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

Java SE 7 Programming Table of Contents


iv
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Java SE 7 Programming Table of Contents


v
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson o m
c uideฺ
1:
i l ฺ
Introduction ma t G
g
@ tude n
Chapter 1ri08
t p u his S
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 1
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 2
CETPA Infotech Pvt Ltd

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© 2014, 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: m
o
a. Click the Start button.
a ilฺc Guide
b. Click Run.
@ gm ent
i 8
button. Stu
0 d
c. Type cmd in the Run dialog box and click the OK r
pu that iasJRE is installed; this does not
2. Execute the java -version command. This s a tverifies t h
verify that the JDK is installed.
c h al use
a n -version
ajava e to command matches the following
a. Verify that the output of (the
i machines,
r64-bit e s
n the output should be:
example output. For
t p u l i c
l S a b le
java version
ha SE f r a
"1.7.0"
eRuntime
a n c
Java(TM)
n s Environment (build 1.7.0-b147)
A Java n - ra
tHotSpot(TM) 64-Bit Server VM (build 21.0-b17, mixed mode)
o 32-bit machines, the output should be:
nFor
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.

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 3
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
 The javac command is not in your path.
 The wrong JDK version is installed.
 Multiple JDKs are installed.
s a
)h ฺ a
Note: It is very common that the directory containing javac is not listed in your PATH
m
environment variable. You do not need to modify the PATH for most IDEs to function;
o
ilฺc Guide
instead, locate the path to your JDK and execute javac -version by using a fully
a
gm ent
qualified path to verify the presence and version of the JDK. For example:
@
"C:\Program Files\Java\jdk1.7.0\bin\javac.exe"
r i 0 8 Stud-version
4.
a pu ofththeisJDK used by the IDE.
Start the NetBeans IDE and verify the version tnumber
a. The installation of NetBeans places a s insyour
al menu u e Start menu. Locate the NetBeans
IDE 7.0.1 shortcut within the n c h o click it.
tand
( a aStart menu
s e
b. Within NetBeans, click
p u ri the Help
l i c e n and then click About.
menu,
c. The About S a t box displays
dialog le both the NetBeans and JDK version numbers that are
l
a fer
being used. For a b
64-bit machines, you should see:
c h s
n ranVersion:
AaProduct- t NetBeans IDE 7.0.1 (Build 201107282000)
on 1.7.0; Java HotSpot(TM) 64-Bit Server VM 21.0-b17
nJava:
For 32-bit machines, you should see:
Product Version: NetBeans IDE 7.0.1 (Build 201107282000)
Java: 1.7.0; Java HotSpot(TM) Client VM 21.0-b17
Note: Even if JDK7 was discovered in a previous step, you must verify that NetBeans
is using Java 1.7.0.
d. 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 4
CETPA Infotech Pvt Ltd

Practice 1-2: Software Installation

Overview
In this practice, you will install the software needed to perform Java 7 SE development.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, 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 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
http://www.oracle.com/technetwork/java/javase/config-417990.html. Java 7 support for
o m
additional operating systems may be available from other channels.
a ilฺc Guide
Tasks @ gm ent
1. Obtain the required software. r i 0 8 Stud
a t ptheueasiest
t h s
imethod
a. If you require both the JDK and NetBeans,
7 with NetBeans 7.0.1” cobundle.ha
s
l use is to download the “JDK

a n c to
1) Using a web browser, ( a go to s e
p u ri licen
http://www.oracle.com/technetwork/java/javase/downloads/index.html.
2) LocateS a
the
tJava SEleDevelopment Kit (JDK) Cobundles table.
al the Download
r a b
h
n ransf
3) cClick e button for “JDK 7 with NetBeans 7.0.1.”
a
A 4) nYou
o -t must accept
download the
the JDK 7 and NetBeans 7.0.1 Cobundle License Agreement to
software.
n
5) 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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 5
CETPA Infotech Pvt Ltd

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.
2. Install the required software.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

 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.
 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.
s a
3. Verify the software installation. ) h a
m
c uideฺ
o
 Repeat practice 1-1 to verify software installation.
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 6
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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
b. Click the Add Platform button and specify the directory that contains your m
co JDK 7eฺ
installation. i l
a t Gu ฺ i d
g m
8 u d en Sources zip
c. In the Platform Name step, verify that the default locations of the Platform
@
file and API documentation are valid.
p u s Stbox.
ri0 idialog
d. Click the Finish button to close the Add Java
l s at e th
Platform
e. Ensure that JDK 1.7 is selected in
c a Platforms
hthe us list and click Close.
n
aJava SE t o
2. Configure NetBeans to start with
r i ( a
e n se7 JDK.
a. Open the directory
t p ucontaining
l icthe NetBeans configuration files, typically: C:\Program
a bl
S 7.0.1\etc\.
Files\NetBeans
l e
a r a
a ncha text
b. Use
n s feto edit the netbeans.conf file.
editor
ra netbeans_jdkhome property to have a value of the JDK 7 installation
A Modify
c.
n - tthe
o for example: netbeans_jdkhome="C:\Program
nlocation,
Files\Java\jdk1.7.0".
3. Restart NetBeans and verify the JDK being used by NetBeans with the steps outlined in
practice 1-1, step 4.

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 7
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 8
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson m
c uJava
o 2: eฺ
i l ฺ i d
Syntax and Class
g ma Review
n t G
Chapter 2ri08
@ tude
t p u his S
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 1
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

within the IDE and learn how to pass command-line arguments to your main class.
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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 2
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

results to the command line output.

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
o m
5. Add a Java Class called Employee in the com.example.domain package.
a ilฺc Guide
6. Code the Employee class.
@ gm ent
r i
a. Add the following data fields to the Employee class—use 0 8 Syour t udjudgment as to what
t pu to thethlesson
you want to call these fields in the class. Refer
a is materials for ideas on the
field names and the syntax if you area s
l use
not sure. Use public as the access modifier.
n c h to Recommended field type
Field use
( a a s e
Employee id
p u ri licen int
a t le
Employee name
a l S r a b String

nchSocial
Employee
a n s fe Number String
Security
A n-salary
Employee tra double
7. n o
Create a no-arg constructor for the Employee class.
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 3
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Employee id 101
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.
o m
c uideฺ
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 4
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

results to the command-line output.

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
Window/Page Description Choices or Values ) h a
m
c uideฺ
o
Project Name: EmployeePractice
i l ฺ
Project Location g ma nt G
D:\labs\02-Review\practices
Use Dedicated Folder for Storing Deselected i08
@ tude
Libraries t p ur his S
Create Main Class a l sa se t
Selected
a n chChanget o u
i ( a n s e the name to

p u r lice com.example.EmployeeTest –
a t l e com.example is the package name.
S
l era
aProject b
n c h
Set as Main
s f Selected

tran
AaClickn-Finish.
e.
o notice that NetBeans has saved you a great deal of typing by creating a class
Younwill
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.

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

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 5
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
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.
s a
a. Add the following data fields to the Employee class. )h ฺ a
m
o ide
Field use Access Recommended field ilฺc Fielduname
type a
m nt G
g e
@ tudempId
Employee id public int
i 0 8
Employee name public
t p ur his S name
String
l saString e t
Employee Social public
c a
h to u s ssn
Security Number
a n
a se
Employee salary public i (
r licen double
t p u salary

S a to the
b. Add a constructor
l b leEmployee class:
ha Employee()
f a
er { }
n c
public s
n your code at any time for you. Right-click anywhere in the class and
Aa n-can
NetBeans t raformat
selectoFormat, or press the Alt-Shift-F key combination.
n
c. Create accesor/mutator (getter/setter) 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). Select “Getter and Setter” from the Generate menu, and click the boxes
next to the fields for which you want getter and setter methods generated. You can also
click the class name (Employee) to select all fields. Click Generate to insert the code.
The built-in automated syntax checker for NetBeans should have provided you with hints
when you have syntax errors or code errors. Save your class.

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

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 6
CETPA Infotech Pvt Ltd

7. Write code in the EmployeeTest main class to test your Employee class.
a. Add an import statement to your class for the Employee object:
import com.example.domain.Employee;
b. In the main method of EmployeeTest, create an instance of your Employee class,
like this:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
a
a s
arrow keys or the mouse to select the appropriate method from the list. To narrow the list
)h ฺ
down, continue typing some of the first letters of the method name. For example, typing
m
o
choose it. a ilฺc Guide
set will limit the list to the method names that begin with set. Double-click the method to

@ gm emethod n t
d. In the body of the main method, use the System.out.println
i 0 8 t u d to write
messages to the console output.
t p ur his S
System.out.println ("Employee
a l said: se t " + emp.getEmpId());
System.out.println ("Employee
a n ch toname: u " + emp.getName());
System.out.println(a("Employee
r i e n se Soc Sec #: " + emp.getSsn());
a tpu le("Employee
System.out.println
lic salary: " + emp.getSalary());
S is inrathebjava.lang package, which is why you do not have to import it
The System lclass
a
h
ncworks,
(by default, you fe get java.lang). You will learn more about how this multiple dot
always
s
a
notation n
A n-totrathe console
but for now understand that this method takes a string argument and writes
that string output.
e.
noSave the EmployeeTest class.
8. Examine the Project Properties.
a. Right-click the project and select Properties.
b. Expand Build, if necessary, and select Compiling. The option at the top, “Compile on
Save,” is selected by default. This means that as soon as you saved the Employee and
EmployeeTest classes, they were compiled.
c. Select Run. You will see that the Main Class is com.example.EmployeeTest. This
is the class the Java interpreter will execute. The next field is Arguments, which is used
for passing arguments to the main method. You will use arguments in a future lesson.
d. Click Cancel to close the Project Properties.
9. Run the EmployeePractice project.

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

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 7
CETPA Infotech Pvt Ltd

a. To run your EmployeePractice project, right-click the project and select Run, or click
the Run Main Project icon (the green triangle), or press F6.
b. If your classes have no errors, your should see the following output in the Output
window:
run:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Employee 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.

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 2: Java Syntax and Class Review


Chapter 2 - Page 8
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson o m
c uideฺ
3:
i
a tGl ฺ
Encapsulationmand
Subclassing @ g en
8 u d
p u ri0 is St
l s at 3 e th
Chapter

n c ha to us
( a a se
u i
r licen
a t p le
l S a b
n c ha sfer
Aa n-tran
no

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

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 1
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 2
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

create a test class with a main method to test your new classes.

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

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
Tasks n
o
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.

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

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 3
CETPA Infotech Pvt Ltd

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.
b. Create a constructor that includes all the parameters needed for Employee and
deptName.
c. Add a getter method for deptName.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
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
s a
following:
)h ฺ a
m
a. Remove the code that creates an instance of the “Jane Smith” Employee.
a i l ฺco uide
b. Create an instance of an Engineer with the following information:
g m nt G
Field
i 8
Choices
0 u de
@ ortValues
ID 101 tpu
r is S
l s a e th
Name
n c haJanetSmith
o us
SSN
( a a s012-34-5678
e
r i e n
Salary
a tpu le lic 120_345.27
a S an error
You will likelyl see
r a bbeside the line that you added to create an Engineer. This is
because
nThe h
c nsf
NetBeans e
cannot resolve Engineer using the existing import statements in the
A a
class.
t r a
quick way to fix import statements is to allow NetBeans to fill them in for you.
-
non will automatically add the import statement for Engineer in the appropriate place
Right-click in the class and select Fix Imports, or press the Ctrl + Shift + I key combination.
NetBeans
in the class and the error will disappear.
c. Create an instance of a Manager with the following information:
Field Choices or Values
ID 207
Name Barbara Johnson
SSN 054-12-2367
Salary 109_501.36
Department US Marketing

d.

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

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 4
CETPA Infotech Pvt Ltd

Create an instance of an Admin with the following information:


Field Choices or Values
ID 304
Name Bill Monroe
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

SSN 108-23-6509
Salary 75_002.34
e. Create an instance of a Director:
Field Choices or Values
ID 12
Name Susan Wheeler
SSN 099-45-2340
Salary 120_567.36
Department Global Marketing
s a
Budget 1_000_000.00 )h ฺa
o m
f. Save EmployeeTest and correct any syntax errors.
a ilฺc Guide
8. Add a printEmployee method to EmployeeTest to print out
@ gm n
a formatted
e t Employee
object (its data fields). The printEmployee method should 8 take andEmployee object as a
u
r i 0 S t
parameter.
a t pu this
9. Use the printEmployee method to print
h a lsout information
u s e about each of your Employee
objects.
a n c to
10. (Optional) Use the raiseSalaryi ( a andn s e methods on some of your objects to make
u r lic e setName

a tp work.
sure that those methods
l e
11. l S erabclass and test your work.
Save the EmployeeTest
h a
12. a nc Improve
(Optional)
a n sfthe look of the salary print output using the NumberFormat class.
A n-tr
o thethatfollowing
a. Use
nclass code to get an instance of a static java.text.NumberFormat
you can use to format the salary to look like a standard US dollar currency:
NumberFormat.getCurrencyInstance().format(emp.getSalary())
In the lesson on abstract classes, you will see how to use an abstract factory, such as
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.

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

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 5
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

create a test class with a main method to test your new classes

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

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
Tasks n
o
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.

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

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 6
CETPA Infotech Pvt Ltd

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) {
this.empId = empId;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

this.name = name;
this.ssn = ssn;
this.salary = salary;
}
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;
}
s a
f. Save Employee.java
)h ฺa
m
3. Create a subclass of Employee called Manager.
a i lฺco uide
a. Right-click the package com.example.domain and selectm
g t
New > Java
n GClass.
b. Enter the class name Manager and click Finish. 08@ tud
e
i
r is S
c. Modify the class to subclass Employee. tpu
l s a e th
Note that the class declaration now has
n c haan error
t o
s on it from Netbeans. Recall that
umark
(aainherited
constructors are not inherited from the parent class, so you will need to add a constructor
i
that sets the value of the rfields n e the parent class. The easiest way to do this is
sfrom
u calls the
tpthat
to write a constructor
e
licparent constructor using the super keyword.
a
l S String l e
b to store the department name in a field called deptName.
h a
d. Add a private
e r afield
e. aAdd
a n sf that takes empId, name, ssn, salary, and a deptName of type
nca constructor
A String.
o n -tr The Manager constructor should call the Employee constructor with the
nsuper keyword, and then set the value of deptName.
public Manager(int empId, String name, String ssn, double
salary, String deptName) {
super (empId, name, ssn, salary);
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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 7
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

6. Save the class.


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:

Field Choices or Values


ID 101
Name Jane Smith s a
a
)h ฺ
SSN 012-34-5678
o m
Salary 120_345.27 a ilฺc Guide
You will likely see an error beside the line that you added @ gm aneEngineer.
to create n t This is
because NetBeans cannot resolve Engineer using the r i 0 8 Simport
existing t udstatements in the
class. The quick way to fix import statements istp touallow NetBeans
is to fill them in for you.
s a t h
h
NetBeans will automatically add thecimportal statement
Right-click in the class and select Fix Imports, or
u sefor Engineer
press the Ctrl + Shift + I key combination.
in the appropriate place
in the class and the error will a a n e to
disappear.
r ia(Manager
e n s
c. Create an instanceuof
a tp le lic with the following information:

h a l SFielderab Choices or Values


ID nc
a a n sf 207
A
Name n- t r Barbara Johnson
n o
SSN 054-12-2367
Salary 109_501.36
Department US Marketing
d. Create an instance of an Admin with the following information:
Field Choices or Values
ID 304
Name Bill Monroe
SSN 108-23-6509
Salary 75_002.34

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

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 8
CETPA Infotech Pvt Ltd

Create an instance of a Director:


Field Choices or Values
ID 12
Name Susan Wheeler
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

SSN 099-45-2340
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
Employee object as the parameter:
s a
public static void printEmployee (Employee emp) {
)h ฺa
System.out.println(); // Print a blank line as a separator
o m
// Print out the data in this Employee object
a ilฺc Guide
System.out.println ("Employee id:
gm ent
" + emp.getEmpId());
@
System.out.println ("Employee name:
r i 0 8 Stud
" + emp.getName());

pu this
System.out.println ("Employee Soc Sec #: " + emp.getSsn());
System.out.println ("Employee salary:
a t " + emp.getSalary());
}
h a ls use
Note that all the object instancesa n c tocreating are Employee objects, so
that youeare
( a s
ri youliccreate,
n the printEmployee method will work. However,
regardless of which subclass
the Employee class p u e
t cannotleknow about the specialization of its subclasses. You will see
S a
l ethisrainbthe next lesson.
how to work around
h a
9. Use the
a a n sf
ncprintEmployee method to print out information about your classes. For example:
r
A printEmployee(eng);
t
on-
nprintEmployee(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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 9
CETPA Infotech Pvt Ltd

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(emp.getSalary())
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

In the lesson on abstract classes, you will see how to use an abstract factory, such as
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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 10
CETPA Infotech Pvt Ltd

(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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Finally, add a method to Manager to print the staff names and IDs.

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
integer field employeeCount to keep a count of the number of employees. Initialize s a
the employee count with 0. a
)h ฺ
c. In the constructor, initialize the staff array with a maximum of 20 c m
o ide
a ilฺ employees.
G u array
2. Add a method called findEmployee. This method scans the current
g m staff tEmployee
to see whether there is a match between the any member@
8 d
of staff and
u ethenEmployee
passed in.
p u ri0 is St
at number
a. Return -1 if there is no match, and thesindex
l e thof the Employee if there is a
match.
n c ha to us
3. (
Add a method called addEmployee. a a This semethod adds the Employee passed in as a
parameter to the end ofuther i array.cen
a tp returnl e li
a. This method
a l S rab boolean value and take an Employee object as a
should a
h The
parameter.
n c s f emethod should return true if the employee was successfully added and
ranemployee already exists as a member of staff.
Aafalsen-iftthe
o the
b. Call
nstaff findEmployee method to determine whether the Employee is a member of
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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 11
CETPA Infotech Pvt Ltd

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.
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 3: Encapsulation and Subclassing


Chapter 3 - Page 12
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson m
c uJava
o 4: eฺ
i l ฺ i d
Class Design ma t G
g
@ tude n
Chapter 4ri08
t p u his S
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 1
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

which object was passed to the method.

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 2
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, 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.
2. Edit the Employee class to override the toString() method from the Object class.
Object’s toString method returns a String.
a. Add a return statement that returns a string that includes the employee ID, name,
s a
)h ฺa
Social Security number, and a salary as a formatted string, with each line separated
with a newline character ("\n").
o m
b. To format the double salary, use the following: a ilฺc Guide
@ gm ent
NumberFormat.getCurrencyInstance().format(getSalary())
c. Fix any missing import statements. r i 0 8 Stud
a t pu this
d. Save the class.
h a ls use
3. Override the toString() method
a n cin the Manager
t o class to include the deptName field
i the e
(a ens string with a newline character.
value. Separate this string from Employee
piconr
u with the lic “o” in the center beside the method signature in the
a t
Note the Green circle
l e
Manager class.
a l S rab
This indicates that NetBeans is aware that this method overrides the

nch ransfe
method from the parent class, Employee. Hold the cursor over the icon to read what this
iconarepresents:
A n-t
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 3
CETPA Infotech Pvt Ltd

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© 2014, 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.
d. Save the EmployeeStockPlan class.
s a
6. Modify the EmployeeTest class. Replace the four print statements in the )h ฺa
m
o ide
printEmployee method with a single print statement that uses the toString
that you created. a ilฺc Gumethod
@ gm ent
7. Overload the printEmployee method to take a second parameter,
EmployeeStockPlan, and print out the number ofrstock i 0 8 options
S t uthatd this employee will
receive.
a t pu this
a s in the
lcalls semain method, create an instance of
a. Above the printEmployee method
c h u
n passethattoinstance to each of the printEmployee
the EmployeeStockPlana and
methods. r i ( a n s
u
tp le lmethod e
ic should call the first printEmployee method and
a
b. The new printEmployee
l Sof stocks bgranted to this employee:
a
the number
h e r a
a nc ransf (emp);
A System.out.println("Stock
printEmployee
n -t
n o 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 4
CETPA Infotech Pvt Ltd

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© 2014, 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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 5
CETPA Infotech Pvt Ltd

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© 2014, 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.
c. Select EmployeePractice and click Open Project. s a
a
) hclass.ฺ
2. Edit the Employee class to override the toString() method from the Object
o m
Object's toString method returns a String.
a ilฺc Guide
a. Add the toString method to the Employee class with the
@ gmfollowing
e n tsignature:
public String toString() { r i 0 8 Stud
b. Add a return statement that returns a a t puthat includes
string t h is the employee information:
ID, name, Social Security number, a ands
l a formatted
se salary like this:
c h to u
return "Employee ID:
( a an "se+ getEmpId() + "\n" +
"Employee i
ur Name: c n
e " + getName() + "\n" +
t p
a blSSN: e l i
l S
"Employee
a
" + getSsn() + "\n" +

n c ha "Employee
s f er Salary: " +
Aa n-the n
NumberFormat.getCurrencyInstance().format(getSalary());
traEmployee
c. Save class.
n o
3. Override the toString method in the Manager class to include the deptName field value.
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 6
CETPA Infotech Pvt Ltd

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© 2014, 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.
4. s a
(Optional) Override the toString method in the Director class as well, to display all the
fields of a director and the available budget.
a
)h ฺ
m
5. Create a new class called EmployeeStockPlan in the package
a i lฺco uide
com.example.business. This class will include a single method,
g m grantStock,
n t G which
takes an Employee object as a parameter and returns an@
i 0 8 t u de of stock options
integer number
based on the employee type:
t p ur his S
Employee Type
l sa Numbere t of Stock Options
Director
a
ch to u s 1000
a n e
Manager i (a n s 100
u r e
a tp le lic
All other Employees 10
S b
athel newfepackage
ra and class in one step by right-clicking Source Package, and
a. Create
c h
A
n selecting
athen t r a nsNew > Java Class.
-EmployeeStockPlan as the Class Name and com.example.business as
onPackage
b. Enter
nthe 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 7
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

return directorShares;
} else {
if (emp instanceof Manager) {
return managerShares;
} else {
return employeeShares;
}
}
f. Resolve any missing import statements.
g. Save the EmployeeStockPlan class.
s a
6. Modify the EmployeeTest class. Replace the four print statements in the
)h ฺa
printEmployee method with a single print statement that uses the toString method
m
o
that you created.
a ilฺc Guide
a. Replace these lines:
@ gm ent
System.out.println("Employee id:
r i 0 ud
8 " S+ temp.getEmpId());
System.out.println("Employee name:
a t pu this" + emp.getName());
System.out.println("Employee
h a lsSoc uSec
se #: " + emp.getSsn());
System.out.println("Employee c to
an se salary: " +
( a
ri licen
NumberFormat.getCurrencyInstance().format((double)
t
emp.getSalary()));p u
S
b. With onelline
athat usesb e toString() method:
lthe
ha sfer a
n c n
System.out.println(emp);
7. Aa n-the
Overload traprintEmployee method to take a second parameter,
no
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));

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

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 8
CETPA Infotech Pvt Ltd

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:
EmployeeStockPlan esp = new EmployeeStockPlan();
printEmployee(eng, esp);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

... 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
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
s a
a
original printEmployee method above the print statement that prints the employee data
)h ฺ
fields: m
System.out.println("Employee type: " +
a i lฺco uide
emp.getClass().getSimpleName());
g m nt G
This will print out the simple name of the class (Manager,
i 0 8 @ t u
Engineer,deetc). The output of
the first employee record should now look like this:
t p ur his S
Employee type:
a
Engineerl sa se t
Employee id:
a n
101ch to u
Employee name:
i (a Jane n e
sSmith
Employee SoctpSec
r e
u #: li012-34-5678
c
a
l Ssalary: l e
b $120,345.27
Employee
h a e r a
a nc ransf
Stock Options: 10
A n-t
no

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

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 9
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 4: Java Class Design


Chapter 4 - Page 10
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson o m
c uideฺ
5:
i l ฺ
Advanced Class
g maDesignn t G
Chapter 5ri08
@ tude
t p u his S
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 1
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 2
CETPA Infotech Pvt Ltd

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© 2014, 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
Your class design should reflect this. Additional types of accounts might be added in the future. a
) h a
Tasks o m
c uideฺ
i l ฺ
1. Open the AbstractBanking project as the main project.
g ma nt G
a. Select File > Open Project.
0 8 @ tude
i
ur his S
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
t p
a “Openeast Main Project” check box.
a l sthe
c. Select AbstractBanking and select
n c h to us
d. Click the Open Project button.
( a a se
u i
r licen
2. Expand the project directories.
a p
t shouldlesee a report of all customers and their accounts.
3. Run the project.
a S
l erab
You
h sf
ncthe rTimeDepositAccount
4. Review class.
a
A Open a n
t TimeDepositAccount.java file (under the com.example package).
a.
o n -the
b. nIdentify 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 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.

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 3
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
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.
s a
8. Modify the Customer and CustomerReport classes to use Account references.
) h a
a. Open the Customer.java file (under the com.example package). o m
c uideฺ
i l ฺ
a references.
b. Change all TimeDepositAccount references to Account g mtype n t G
c. Open the CustomerReport.java file (under the 0 8 @ tudepackage).
i com.example
urto Account
s S
d. Change all TimeDepositAccount references t
a et p h i type references.
l s
9. Run the project. You should see a report
n c haof alltocustomers
us and their accounts.
( a a se in the com.example package.
10. Create a new Java class, CheckingAccount,
u i
rshouldlibe
c e n
a. CheckingAccount
a t p l e a subclass of Account.
l S erab field to the CheckingAccount class.
b. Add anaoverDraftLimit
h
a nc ranfinalsf double overDraftLimit;
private
A n-t
no a CheckingAccount constructor that has two parameters.
c. Add
 double balance: Pass this value to the parent class constructor.
 double overDraftLimit: Store this value in the overDraftLimit field.
d. Add a CheckingAccount constructor that has one parameter. This constructor
should set the overDraftLimit field to zero.
 double balance: Pass this value to the parent class constructor.
e.

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 4
CETPA Infotech Pvt Ltd

Override the abstract getDescription method inherited from the Account class.
@Override
public String getDescription() {
return "Checking Account";
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, 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
bank.addCustomer("Jane", "Simms"); s a
customer = bank.getCustomer(0); ) h a
m
c uideฺ
o
customer.addAccount(new TimeDepositAccount(500.00,
i l ฺ
ma nt G
cal.getTime()));
g
@ tude
customer.addAccount(new CheckingAccount(200.00, 400.00));
i 0 8
t p ur his S
sa se t
bank.addCustomer("Owen", "Bryant");
customer = bank.getCustomer(1);a l
h to u
customer.addAccount(new
a n cCheckingAccount(200.00));
r i (a ense
a tpu le lic "Soley");
bank.addCustomer("Tim",
a l S= bank.getCustomer(2);
customer
h e r a b
a nc ransf
customer.addAccount(new TimeDepositAccount(1500.00,
A n-t
cal.getTime()));
o
ncustomer.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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 5
CETPA Infotech Pvt Ltd

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© 2014, 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


Time Deposit Account Sat Feb 04 11:14:54 CST 2012: current
balance is 1500.0
s a
Checking Account: current balance is 200.0 a
)h ฺ
o m
Customer: Soley, Maria a ilฺc Guide
Checking Account: current balance is 200.0
@ gm ent
Time Deposit Account Sat Feb 04 i11:14:54
r 0 ud 2012: current
8 StCST
balance is 150.0
a t pu this
h a ls use
a n c to
( a s e
p u ri licen
a t le
l S a b
n c ha sfer
Aa n-tran
no

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 6
CETPA Infotech Pvt Ltd

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© 2014, 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
Your class design should reflect this. Additional types of accounts might be added in the future. a
) h a
Tasks o m
c uideฺ
i l ฺ
1. Open the AbstractBanking project as the main project.
g ma nt G
a. Select File > Open Project.
0 8 @ tude
i
ur his S
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
t p
a “Openeast Main Project” check box.
a l sthe
c. Select AbstractBanking and select
n c h to us
d. Click the Open Project button.
( a a se
u i
r licen
2. Expand the project directories.
a p
t shouldlesee a report of all customers and their accounts.
S
l erab
3. Run the project.
a
You
h
nc ransf CUSTOMERS REPORT
a
A n-t ================
n o
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

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 7
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

methods. For example:


// 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.
6. Code the Account class.
s a
a. This class should be declared as abstract. )h ฺ a
o m
public abstract class Account
a ilฺc Guide
b. Move the balance field and the getBalance, deposit, m toString
gand n t methods
from TimeDepositAccount to the Account class. @
8 Stud e
r i 0
t pu from
Note: The fields and methods should be removed
a t h isTimeDepositAccount.
s
l utosthe
amethod e Account class.
c. Add an abstract getDescription
c h to
public abstract String ( a an getDescription();
s e
d. Add an abstract p u ri limethod
c e n to the Account class.
a t withdraw
le
public a l S
abstract
r a bboolean withdraw(double amount);
h
ncAccount e
sfclass should have a protected access level balance field. If you have
e. aThe
a n
A already
o n
level.
-trmoved this field from the TimeDepositAccount, just change the access
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 8
CETPA Infotech Pvt Ltd

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© 2014, 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
d. Change all TimeDepositAccount references to Account type references.
c o m eฺ
9. Run the project. You should see a report of all customers and theira i l ฺ u i d
g m accounts. t G
10.
8 @
Create a new Java class, CheckingAccount, in the com.example
u d en
package.
a. CheckingAccount should be a subclass of u
p ri0 is St
Account.
l s at e Account
th
public class CheckingAccount a
ctohthe us
extends
b. Add an overDraftLimita n
field
e t o
CheckingAccount class.
( a s
ri lioverDraftLimit;
n
private final u
t p double
c e
S a
c. Add a CheckingAccount
l b le constructor.
f er a
ha CheckingAccount(double
a n c
public
n s balance, double overDraftLimit) {
A n-tr a
super(balance);
no this.overDraftLimit = overDraftLimit;
}
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 9
CETPA Infotech Pvt Ltd

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) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

if(amount <= balance + overDraftLimit) {


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
bank.addCustomer("Jane", "Simms");
s a
customer = bank.getCustomer(0);
) h a
customer.addAccount(new TimeDepositAccount(500.00,
o m
c uideฺ
cal.getTime()));
i l ฺ
ma nt G
customer.addAccount(new CheckingAccount(200.00, 400.00));
g
0 8 @ tude
bank.addCustomer("Owen", "Bryant");r
u i s S
t p h i
customer = bank.getCustomer(1);
a l sa se t
a n ch to u
customer.addAccount(new CheckingAccount(200.00));

r i n se
(a e"Soley");
tpu le lic
bank.addCustomer("Tim",
customer =abank.getCustomer(2);
h a l S erab
n c s f
customer.addAccount(new TimeDepositAccount(1500.00,

- t r an
Aacustomer.addAccount(new
cal.getTime()));

non
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 10
CETPA Infotech Pvt Ltd

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© 2014, 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


Time Deposit Account Sat Feb 04 11:14:54 CST 2012: current
balance is 1500.0
s a
Checking Account: current balance is 200.0 a
)h ฺ
o m
Customer: Soley, Maria a ilฺc Guide
Checking Account: current balance is 200.0
@ gm ent
Time Deposit Account Sat Feb 04 i11:14:54
r 0 ud 2012: current
8 StCST
balance is 150.0
a t pu this
h a ls use
a n c to
( a s e
p u ri licen
a t le
l S a b
n c ha sfer
Aa n-tran
no

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 11
CETPA Infotech Pvt Ltd

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© 2014, 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
Using the static and final keywords you will limit the number of Bank instances to one per Java a
virtual machine (JVM). ) h a
c o m eฺ
Tasks i l
a t Guฺ i d
g m
1. Open the SingletonBanking project as the main project.
8 @ u d en
a. Select File > Open Project.
p u ri0 is St
l s at e th
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
c. Select SingletonBanking and c a the u“Open
hselect s as Main Project” check box.
n
a se t o
( a
d. Click the Open Project button.
i
r licen
p u
2. Expand the project directories.
t
l S a b lesee a report of all customers and their accounts.
3. Run the project. You a
should
ha sfer CUSTOMERS REPORT
n c
Aa n-tran ================
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

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 12
CETPA Infotech Pvt Ltd

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


a. Open the Bank.java file (under the com.example package).
b. Change the constructor’s access level to private.
c. Add a new field named instance. The field should be:
 private
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

 Marked static
 Marked final
 Type of Bank
 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).
s a
b. Replace any calls to the Bank constructor with calls to the previously created
getInstance method.
a
)h ฺ
m
o andidinitialize
e
c. In the main method, create a second local Bank reference named
a i lฺcbank2 u
it using the getInstance method.
g m nt G
d. Use reference equality checking to determine whether 8 @bank andu e reference the
dbank2
same object. i 0
ur his S t
t p
if(bank == bank2) {
a l sa se t
System.out.println("bank
a n ch and t o ubank2 are the same object");
}
r i (a ense
a tputhe second
e. Try initializing only
l e lic Bank but running the report on the first Bank.
h a l S erab
initializeCustomers(bank2);
a nc ransf
A // nrun-t the customer report
o
nCustomerReport report = new CustomerReport();
report.setBank(bank);
report.generateReport();
6. Run the project. You should see a report of all customers and their accounts.

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 13
CETPA Infotech Pvt Ltd

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© 2014, 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
Using the static and final keywords you will limit the number of Bank instances to one per Java a
Virtual Machine (JVM). ) h a
c o m eฺ
Tasks i l
a t Gu ฺ i d
g m
1. Open the SingletonBanking project as the main project.
8 @ u d en
a. Select File > Open Project.
p u ri0 is St
s at e th
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
l
c a the u“Open
hselect s as Main Project” check box.
c. Select SingletonBanking n and
a se t o
d. Click the Open Project i ( a
r licen
button.
t p u
2. Expand the project
l S a le
directories.
b
ha You
3. Run the project. f a
r see a report of all customers and their accounts.
eshould
n c s
Aa the
4. Modify
- t r
Bankanclass to implement the Singleton design pattern.
on the Bank.java file (under the com.example package).
a. nOpen
b. Change the constructor’s access level to private.
private Bank() {
customers = new Customer[10];
numberOfCustomers = 0;
}
c.

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 14
CETPA Infotech Pvt Ltd

Add a new field named instance. The field should be:


 private
 Marked static
 Marked final
 Type of Bank
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

 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() {
return instance;
}
5. Modify the SingletonBankingMain class to use the Bank singleton.
a. Open the SingletonBankingMain.java file (under the com.example package).
s a
)h ฺ
b. Replace any calls to the Bank constructor with calls to the previously created
a
m
getInstance method.
a i lฺco uide
Bank bank = Bank.getInstance();
g m nt G
8 @ named
c. In the main method, create a second local Bank reference
i 0 t u debank2 and initialize
it using the getInstance method.
t p ur his S
Bank bank2 = Bank.getInstance();
a l sa se t
n
d. Use reference equality checking
a chto determine
t o u whether bank and bank2 reference the
same object.
r i (a ense
tpu le{ lic
if(bank ==abank2)

h a l S erab
System.out.println("bank and bank2 are the same object");
c f
A a}n trans
on- only the second Bank, but run the report on the first Bank.
e. Initialize
ninitializeCustomers(bank2);
// run the customer report
CustomerReport report = new CustomerReport();
report.setBank(bank);
report.generateReport();
6. Run the project. You should see a report of all customers and their accounts.

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 15
CETPA Infotech Pvt Ltd

(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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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
TimeDepositAccount instances with a maturity date that is 90 or 180 in the future. ) h a
By creating a new Java enum you will modify the application to only allow for the creation of
m
c uideฺ
o
i l ฺ
Tasks
g ma nt G
1. Open the EnumBanking project as the main project.
0 8 @ tude
a. Select File > Open Project.
i
ur his S
t p
l sa se t
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
a
c. Select EnumBanking and a n chthe “Open
select t o uas Main Project” check box.
r i (a ense
a t pu le lic
d. Click the Open Project button.

a l S directories.
2. Expand the project
r a b
h e
n ransf should see a report of all customers and their accounts.
3. Run thecproject. You
a
A n
4. Create
o -t Java enum, DepositLength, in the com.example package.
a new
n the DepositLength enum.
5. Code
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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 16
CETPA Infotech Pvt Ltd

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).
b. Modify the existing constructor to receive an enum as the second parameter.
public TimeDepositAccount(double balance, DepositLength
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

duration) {
super(balance);
Calendar cal = Calendar.getInstance();
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.
s a
c. Within the initializeCustomers method, modify the creation of all ) h
a
c o m eฺ
TimeDepositAccount instances to use the DepositLength enum.
a il Guid

customer.addAccount(new TimeDepositAccount(500.00,
@ gm ent
DepositLength.SIX_MONTHS));
r i 0 8 Stud
a static import to reduce the length of s
the tpu this values. You can also use
Note: Try using both the SIX_MONTHS and THREE_MONTHS
a statement.
8. c haofl alltocustomers
Run the project. You should see anreport use and their accounts. It is now
a thatscreates
impossible to compile a line (ofacode e a TimeDepositAccount with an invalid
r i e n
tpu le lic
maturity date.
a
l S erab
h a
a nc ransf
A n-t
no

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 17
CETPA Infotech Pvt Ltd

(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© 2014, 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
a. Select File > Open Project. ) h a
m
c uideฺ
o
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
i l ฺ
c. Select NestedClasses and select the “Open as Main Project”g macheck n t G
box.
0 8 @ tude
d. Click the Open Project button. i
ur his S
2. Expand the project directories. t p
a et
a l s s window.
3. h intotheuoutput
Run the project. You should see the output
n c
4. Count the number of classes(a a insthe
created e OuterClass.java file.
r i e n
tpu le lic file (under the com.example package).
a. Open the OuterClass.java
a
a
b. Determine
h l Sthe total
e r a b of classes created in this file.
number
nc ranthesftotal number of top-level classes created in this file.
c. aDetermine
A n-t the total number of nested classes created in this file.
e.
no
d. Determine
Determine the total number of inner classes.
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 18
CETPA Infotech Pvt Ltd

(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© 2014, 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
a. Select File > Open Project. ) h a
m
c uideฺ
o
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
i l ฺ
c. Select NestedClasses and select the “Open as Main Project” g macheck n t G
box.
0 8 @ tude
d. Click the Open Project button. i
ur his S
2. Expand the project directories. t p
a et
a l s s window.
3. Run the project. You should see the output
n c h intotheuoutput
4. Open the OuterClass.java ( a a (undersethe com.example package).
file
u i
r licfile e n
a t p
 Within the OuterClass.java
l e there are:

a
 10 classes
h l S erab
a a n sfclass
n c1 top-level
r
A  n9-tnested
n o classes
 8 inner classes
 3 member classes
 2 local classes
 3 anonymous classes
 1 static nested class

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 19
CETPA Infotech Pvt Ltd

 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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

 line 32: anonymous inner class


 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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 5: Advanced Class Design


Chapter 5 - Page 20
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson o m
c uideฺ
6:
i l ฺ
Inheritance with
g maJava n t G
Interfaces
0 8 @ tude
i
u6r his S
t p
a l sa se t
Chapter

a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 1
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 2
CETPA Infotech Pvt Ltd

Practice 6-1: Summary Level: Implementing an Interface

Overview
In this practice, you will create an interface and implement that interface.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 3
CETPA Infotech Pvt Ltd

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).
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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:
 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:
s a
 Extend the Animal class
)h ฺ a
m
 Implement the Pet interface
a i lฺco uide
b. Complete this class by creating:
g m nt G
 A String field called name
0 8 @ tude
i
ur his S
 Getter and setter methods for the name field
t p
 A no-argument constructor that passes l saa valuee oft0 to the parent constructor
a s
couth"Justto keep
u swimming."
 A play() method that prints
a n e eat pond scum."
 An eat() method rthat i (aprintseoutns"Fish
 A walk() method
a tpu thatleoverrides
lic the Animal class walk method. It should first call
l Sclassewalk
the super
h a r a b method, and then print "Fish, of course, can't walk;
a sf
nca newraJava
they swim."
n
9. A n-t
Create class: Cat in the com.example package.
10. nothe Cat class.
Code
a. This class should:
 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 4
CETPA Infotech Pvt Ltd

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;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

//test a spider with a spider reference


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
 Experiment with using every reference type possible and determine which methods s a
)h ฺ
can be called with each type of reference. Use a Pet reference while testing the
a
m
Fish and Cat classes.
a i l ฺco uide
d. Implement and test the playWithAnimal(Animal a) method.
g m nt G
 Determine whether the argument implements the 8
i 0 @interface.
Pet
t u deIf so, cast the
reference to a Pet and invoke the play method.
t p ur Ifhnot,
i s S a message of "Danger!
print
Wild Animal".
l s a et
 Call the playWithAnimal(Animal
c a us from within main, passing in each
h ta)o method
type of animal.
a n
a se
i (
r seelitext
e ndisplayed in the output window.
12. u
Run the project. You should
t p c
l S a b le
ha sfer a
n c
Aa n-tran
no

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 5
CETPA Infotech Pvt Ltd

Practice 6-1: Detailed Level: Implementing an Interface

Overview
In this practice, you will create an interface and implement that interface.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 6
CETPA Infotech Pvt Ltd

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).
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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:
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.
s a
public class Fish extends Animal implements Pet
) h a
b. Complete this class by creating: o m
c uideฺ
i l ฺ
 A String field called name.
g ma nt G
private String name;
0 8 @ tude
i
ur his S
p
 Getter and setter methods for the name field.
t
a l sa se t
c{h to u
@Override
a n
(a ense
public String getName()
return name; r i
} a tpu le lic
h a l S erab
a nc ransf
@Override
A public
n -t void setName(String name) {
o
n this.name = name;
}
 A no-argument constructor that passes a value of 0 to the parent constructor.
public Fish() {
super(0);
}
 A play() method that prints out "Just keep swimming."
@Override
public void play() {
System.out.println("Just keep swimming.");
}

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 7
CETPA Infotech Pvt Ltd

 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© 2014, 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.");
}
9. Create a new Java class: Cat in the com.example package.
s a
10. Code the Cat class.
) h a
m
co uideฺ
a. This class should extend the Animal class and implement the Pet interface.
i l ฺ
public class Cat extends Animal implements Pet
g ma nt G
b. Complete this class by creating:
0 8 @ tude
i
ur his S
 A String field called name.
t p
 Getter and setter methods for thea l
namesafield.se t
 A constructor that receives a n ch to and
a name String
u
passes a value of 4 to the parent
constructor. i ( a n s e
t p ur lice
S a blename) {
public Cat(String
l
c h a fera
super(4);
n rans = name;
Aa} n-this.name
t
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."

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 8
CETPA Infotech Pvt Ltd

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;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

//test a spider with a spider reference


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
 Experiment with using every reference type possible and determine which methods
a
) h a
can be called with each type of reference. Use a Pet reference while testing the
Fish and Cat classes. o m
c uideฺ
i l ฺ
Pet p;
g ma nt G
0 8 @ tude
Cat c = new Cat("Tom"); i
ur his S
t p
c.eat();
a l sa se t
c.walk();
a n ch to u
c.play();
r i ( a nse
a = new Cat();u
t p l i ce
a.eat();Sa le
l a b
c ha sfer
a.walk();
n= newan
Aapp.setName("Mr.
- t r Cat();
on
np.play();
Whiskers");

Fish f = new Fish();


f.setName("Guppy");
f.eat();
f.walk();
f.play();
a = new Fish();
a.eat();
a.walk();
d.

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 9
CETPA Infotech Pvt Ltd

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© 2014, 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.
playWithAnimal(s);
s a
playWithAnimal(c);
) h a
playWithAnimal(f);
o m eฺ
12. Run the project. You should see text displayed in the output window.ilฺc u i d
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 10
CETPA Infotech Pvt Ltd

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© 2014, 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
Tasks ) h a
m
c uideฺ
o
1. Open the EmployeeMemoryDAO project as the main project.
i l ฺ
a. Select File > Open Project. g ma nt G
b. Browse to D:\labs\06-Interfaces\practices. 0 8 @ tude
i
r is S
u"Open
c. Select EmployeeMemoryDAO and select t p
a e thas Main Project" check box.
the
l s
d. Click the Open Project button. cha us
n
a se t o
(
2. Expand the project directories.
i a
3. Run the project. Youtpshould
en Test all the menu choices.
ur seeliacmenu.
l S a ble
h a f[R]ead
[C]reate
c
|
e ra | [U]pdate | [D]elete | [L]ist | [Q]uit:
n When
AaNote: t r a nsentering dates, they should be in the form of: Nov 26, 1976
on- IDs should be in the range of 0 through 9.
nEmployee
4. Review the Employee class.
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 11
CETPA Infotech Pvt Ltd

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© 2014, 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
b. Create an EmployeeDAO instance in the main method. Use the EmployeeDAO ) h a
interface as the reference type. o m
c uideฺ
i
a tGl ฺ
c. Modify any lines containing errors to use the EmployeeDAOm instance.
@ g
choices.de
n
11. 8
Run the project. You should see a menu. Test all the menu
u
Stis still tied to a specific
ri0 isclass
p u
Note: While functional, the EmployeeTestInteractive
s at e implementing
type of DAO because it references the EmployeeDAO
l th class by name.
a
ch to u s
EmployeeDAO dao = new nEmployeeDAOMemoryImpl();
a
(a this se coupling from the
r
In the following steps, you iremove e ntight
a tpu le lclass
EmployeeTestInteractive ic by creating a DAO factory.
12. a l S erab
Modify the EmployeDAOMemoryImpl
h interface.
c f
n rans no-argument constructor.
Aa na -protected,
 Add
t
13. Create
n o an EmployeeDAOFactory class in the com.example.dao package.
14. Complete the EmployeeDAOFactory class.
 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 12
CETPA Infotech Pvt Ltd

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© 2014, 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
Tasks ) h a
m
c uideฺ
o
1. Open the EmployeeMemoryDAO project as the main project.
i l ฺ
a. Select File > Open Project. g ma nt G
b. Browse to D:\labs\06-Interfaces\practices. 0 8 @ tude
i
r is S
u"Open
c. Select EmployeeMemoryDAO and select t p
a e thas Main Project" check box.
the
l s
d. Click the Open Project button. cha us
n
a se t o
(
2. Expand the project directories.
i a
3. Run the project. Youtpshould
en Test all the menu choices.
ur seeliacmenu.
l S a ble
h a f[R]ead
[C]reate
c
|
e ra | [U]pdate | [D]elete | [L]ist | [Q]uit:
n When
AaNote: t r a nsentering dates, they should be in the form of: Nov 26, 1976
on- IDs should be in the range of 0 through 9.
nEmployee
4. Review the Employee class.
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.

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 13
CETPA Infotech Pvt Ltd

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);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
EmployeeDAOMemoryImpl class:

s a
)h ฺa
o m
a ilฺc Guide
@ gm ent
r i 0 8 Stud
a t pu this
h a ls use
a n c to
( a s e
previous step totp uri thelicmethods
b. Implement the EmployeeDAO
become
e n Modify the methods that you moved in the
interface.
required by the EmployeeDAO interface.
a
l Smethod b l e
h a
 The save
f e r abecomes the add method and is modified to have an Employee
c
n rans
parameter.
Aa Then t method is duplicated to become the update method and is modified to
-save
o
n have an Employee parameter.
 The delete method is modified to have an id parameter.
 The findById method is no longer static.
 The getAllEmployees method is no longer static.

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 14
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

public void update(Employee emp) {


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

public void delete(int id) {


employeeArray[id] = null;
}

s a
public Employee findById(int id) {
return employeeArray[id]; ) h a
m
c uideฺ
o
}
i l ฺ
g ma nt G
public Employee[] getAllEmployees() @
i 0 8 {
t u de
r is S
List<Employee> emps = newuArrayList<>();
p
s
for (Employee e : employeeArray)t
a e th {
l
ha{ to us
if (e != null)
a sen c
( a
emps.add(e);
i n
} ur c e
} at
p l i
l S a b le
n c ha return
s f er emps.toArray(new Employee[0]);
Aa} n-}tran
10.
no
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();
c.

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 15
CETPA Infotech Pvt Ltd

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© 2014, 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) {
System.out.println("\n\nEmployee " + id + " not found");
s a
break;
) h a
}
o m eฺ
11. Run the project. You should see a menu. Test all the menu choices. ilฺc i d
u
Note: While functional, the EmployeeTestInteractive class g misastill tied
t G
n specific
to a
@
8 Stu
type of DAO because it references the EmployeeDAO implementing d e
class by name.
r i 0
a t
EmployeeDAO dao = new EmployeeDAOMemoryImpl();pu this
In the following steps, you remove thish a lscoupling
tight u sefrom the
EmployeeTestInteractivea c to a DAO factory.
n by creating
class
( a s e
12. ri liceninterface.
Modify the EmployeDAOMemoryImpl
p u
a. Add a protected,a t no-argument
le constructor.
l S a b
c ha sfer
EmployeeDAOMemoryImpl()
n {
a
A } n-tra n
13. noan EmployeeDAOFactory class in the com.example.dao package.
Create
14. Complete the EmployeeDAOFactory class.
 Add a method that returns an EmployeeDAO.
public class EmployeeDAOFactory {

public EmployeeDAO createEmployeeDAO() {


return new EmployeeDAOMemoryImpl();
}
}

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 16
CETPA Infotech Pvt Ltd

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:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

EmployeeDAOFactory factory = new EmployeeDAOFactory();


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
without changing the reference types or method calls used in the s a
) h a
EmployeeTestInteractive class. Notice that none of the *MemoryImpl classes are
used by name from within the EmployeeTestInteractive class. o m
c uideฺ
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 17
CETPA Infotech Pvt Ltd

(Optional) Practice 6-3: Implementing Composition

Overview
In this practice, you will take an existing application and refactor it to make use of composition.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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
a
)h ฺ
Tasks
o m
1. Open the PetComposition project as the main project.
a ilฺc Guide
a. Select File > Open Project.
@ gm ent
b. Browse to D:\labs\06-Interfaces\practices. r i 0 8 Stud
a t pu as tMain
h isProject" check box.
c. Select PetComposition and selectlthe
a s "Open
se
c h u
d. Click the Open Project button.
( a an se to
p u ri licen
2. Expand the project directories.
a
3. Run the project. You t shouldlesee output in the output window.
a S r a b
l“name”efunctionality.
4. Centralizehall
a sf but you may want to give names to objects that cannot play. For
nccanrbeannamed,
A n-you
All pets
instance,
t could name a volleyball “Wilson.” Your design should reflect this.
n o
a. Create a Nameable interface (under the com.example package).
b. 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.

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 18
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

e. Modify the Pet interface.


 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.
private Nameable nameable = new NameableImpl();
 Add getName and setName methods that delegate to the Nameable field.
s a
) h a
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
m
c uideฺ
o
box, and click the Generate button.
i l ฺ
ma and
 Replace any use of the old name field with calls to the getName
g n t G
setName
methods.
0 8 @ tude
5. Centralize all walking functionality. i
ur his S
t p tfrom the Animal class and use
Only some animal can walk. Remove the lwalk
a sa methods e
a n chwalking.
interfaces and composition to facilitate
t o u
a. Create an Ambulatory(a
r i e n se the com.example package).
interface (under
tpu le liinterface
b. Complete the Ambulatory
a
c with the walk method signature.
S
alinterface b
ra Ambulatory {
c h
public
n rans f e
Aa n-public
t void walk();
n}o
c. Create an AmbulatoryImpl class (under the com.example package).
d. Complete the AmbulatoryImpl class. It should:
 Implement the Ambulatory interface
 Contain a private int field called legs
 Contain a single argument constructor that receives an int value to be stored in the
legs field
 Contain a walk method
public void walk() {
System.out.println("This animal walks on " + legs + "
legs.");
}

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 19
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
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
on Spider, Cat, or Ambulatory references.
s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 6: Inheritance with Java Interfaces


Chapter 6 - Page 20
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson o m
c uideฺ
7:
i
a tGl ฺ
Generics and m Collections
@ g en
8 u d
Chapter 7ri0
p u i s St
l s at e th
n c ha to us
( a a se
u i
r licen
a t p le
l S a b
n c ha sfer
Aa n-tran
no

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

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 1
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

the instructions.

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 2
CETPA Infotech Pvt Ltd

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© 2014, 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 Description
1S01 Blue Polo Shirt s a
1S02 Black Polo Shirt ) h a
m
c uideฺ
o
1H01 Red Ball Cap i l ฺ
1M02 Duke Mug g ma nt G
0 8 @ tude
i
ur his S
Once complete, your report should look like this: a t p t
a l s s e
=== Product Report === ch u
a n e t o
Name: Black Polo Shirt
r i (a ensCount: 6
Name: Blue Polo
t p u Shirtlic Count: 7
l
Name: Duke S aMug ble Count: 3
a r a
nch ransfe
Name: Red Ball Cap Count: 5
a
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 3
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 4
CETPA Infotech Pvt Ltd

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© 2014, 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 Description
1S01 Blue Polo Shirt s a
1S02 Black Polo Shirt ) h a
m
c uideฺ
o
1H01 Red Ball Cap i l ฺ
1M02 Duke Mug g ma nt G
0 8 @ tude
i
ur his S
Once complete, your report should look like this: a t p t
a l s s e
=== Product Report === ch u
a n e t o
Name: Black Polo Shirt
r i (a ensCount: 6
Name: Blue Polo
t p u Shirtlic Count: 7
l
Name: Duke S aMug ble Count: 3
a r a
nch ransfe
Name: Red Ball Cap Count: 5
a
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 5
CETPA Infotech Pvt Ltd

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© 2014, 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++;
productCountMap.put(itemNumber, new s a
Long(curVal));
) h a
} else { o m
c uideฺ
i l ฺ
ma nt G
productCountMap.put(itemNumber,new Long(1));
g
}
0 8 @ tude
} i
ur his S
t p
sa se t
}
a l
a n ch to u
4. Create a printReport() r i methode
se out the results.
(a tonprint
a t pu le lic
l S void
public
a r a bprintReport(){
a nch ranSystem.out.println("===
s fe 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 6
CETPA Infotech Pvt Ltd

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© 2014, 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
o m
Line 2 is invalid
a ilฺc Guide
Line 3 is valid
@ gm ent
r i 0 8 Stud
Tasks a t pu this
h a ls use
Open the Generics-Practice02 project
a n c and make the following changes.
to
1. Modify the processLine() i ( a
method n
ins e to read a line in and convert
u r lic e ParenMatcher.java

a tp array.
the string into a character
l e
2. Loop throughlthe
a S array.raPush
b “(“ onto the stack. When a “)” is encountered, pop a “(“ from
the stack.h Two e
nc ransf should return false.
conditions
a
A If you t to call a pop operation and the stack is empty, the number of parentheses
a.
o n -need
n match, return false.
do not
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 7
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, 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.
Line 0 is valid
s a
Line 1 is invalid
)h ฺa
Line 2 is invalid
o m
Line 3 is valid
a ilฺc Guide
@ gm ent
r i 0 8 Stud
Tasks
a t puthe following
t h is changes.
Open the Generics-Practice02 project and smake
al use
1. Modify the processLine() method n c h
in t o
ParenMatcher.java to read a line in and convert
a e
i (a cenClear
the string into an array of characters.
u r s the stack and convert the line to a character
array.
a tp le li
h a lS e r a b
stack.clear();

a nc rancurLinesf = line.toCharArray();
A n-t
no

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

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 8
CETPA Infotech Pvt Ltd

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).
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

for (char c:curLine){


switch (c){
case '(':stack.push(c);break;
case ')':{
if (stack.size() > 0){
stack.pop();
} else {
return false;
}
break;
}
s a
}
)h ฺa
o m
ilฺc Guide
}
if (stack.size()> 0){ a
@ gm ent
return false; // Missing match invalid expression
} else {
r i 0 8 Stud
return true; //
a t pu this
}
h a ls use
3. Run the ParanMatcher.javaaclassn c to ensure
to that your program produces the desired
( a s e
output.
p u ri licen
a t le
l S a b
n c ha sfer
Aa n-tran
no

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

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 9
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

inventory level for a number of shirts. Then print out the shirt data sorted by description and by
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
create two classes that implement the Comperator interface to allow sorting shirts by count and
by description. s a
For example, the output from the program might look like the following. ) h a
m
c uideฺ
o
=== Inventory Report - Description === i l ฺ
Shirt ID: P002
g ma nt G
Description: Black Polo Shirt
0 8 @ tude
i
ur his S
Color: Black
t p
Size: M
a l sa se t
Inventory: 15
a n ch to u
r i (a ense
Shirt ID: P001u
a lic Shirt
tpBluelePolo
Description:
a S rab
lBlue
h
c nsfe
Color:
n
a
A Size: trLa 24
n -
no
Inventory:

Shirt ID: P003


Description: Maroon Polo Shirt
Color: Maroon
Size: XL
Inventory: 20

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

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 10
CETPA Infotech Pvt Ltd

Shirt ID: P004


Description: Tan Polo Shirt
Color: Tan
Size: S
Inventory: 19
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

=== Inventory Report - Count ===


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

Shirt ID: P004


Description: Tan Polo Shirt
Color: Tan
s a
Size: S
) h a
Inventory: 19 o m
c uideฺ
i l
a tG ฺ
g m
Shirt ID: P003
8 @ u d en
Description: Maroon Polo Shirt
p u ri0 is St
Color: Maroon
l s at e th
Size: XL
n c ha to us
Inventory: 20
( a a se
u i
r licen
Shirt ID: a t
P001p lePolo Shirt
l S a b
n c ha Blue
Description:
s f erBlue

AaSize:
Color:
- t r an
on
L
nInventory: 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 11
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

the count field to increment and decrement the inventory levels.


 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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 12
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

inventory level for a number of shirts. Then print out the shirt data sorted by description and by
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
create two classes that implement the Comperator interface to allow sorting shirts by count and
by description. s a
For example, the output from the program might look like the following. ) h a
m
c uideฺ
o
=== Inventory Report - Description === i l ฺ
Shirt ID: P002
g ma nt G
Description: Black Polo Shirt
0 8 @ tude
i
ur his S
Color: Black
t p
Size: M
a l sa se t
Inventory: 15
a n ch to u
r i (a ense
Shirt ID: P001u
a lic Shirt
tpBluelePolo
Description:
a S rab
lBlue
h
c nsfe
Color:
n
a
A Size: trLa 24
n -
no
Inventory:

Shirt ID: P003


Description: Maroon Polo Shirt
Color: Maroon
Size: XL
Inventory: 20

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

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 13
CETPA Infotech Pvt Ltd

Shirt ID: P004


Description: Tan Polo Shirt
Color: Tan
Size: S
Inventory: 19
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

=== Inventory Report - Count ===


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

Shirt ID: P004


Description: Tan Polo Shirt
Color: Tan
s a
Size: S
) h a
Inventory: 19 o m
c uideฺ
i l
a tG ฺ
g m
Shirt ID: P003
8 @ u d en
Description: Maroon Polo Shirt
p u ri0 is St
Color: Maroon
l s at e th
Size: XL
n c ha to us
Inventory: 20
( a a se
u i
r licen
Shirt ID: a t
P001p lePolo Shirt
l S a b
n c ha Blue
Description:
s f erBlue

AaSize:
Color:
- t r an
on
L
nInventory: 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 14
CETPA Infotech Pvt Ltd

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© 2014, 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
s1.getDescription().compareTo(s2.getDescription());
s a
}
)h ฺa
o m
ilฺc Guide
}
a
5. Update the TestItemCounter class to process the shirts @ gm
and e n t and produce
transactions
the desired report. r i 0 8 Stud
t u his shirt object contained in the
pappropriate
a l s countsefor teach product.
 Loop through the transactions and updateathe
polos Map. This will produce an inventory
a n ch to u
// Count the shirtsa
i ( n s e
r e
tpu le litransaction:transactions){
for (DukeTransaction
a
c
h a lS e r b = polos.get(transaction.getProductID());
if (polos.containsKey(transaction.getProductID())){
a
a nc } relse
a n sf{
currentShirt
A n-t System.out.println("Error: Invalid part number");
no }
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 15
CETPA Infotech Pvt Ltd

 Print the list of shirts by description.


// Convert to List
List<Shirt> poloList = new ArrayList<>(polos.values());
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

// Init Comparators
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
o m
a ilฺc Guide
 Print the list of shirts by count.
@ gm ent
r i 0 8 Stud
pu this
// Print Results - Sort by Count
Collections.sort(poloList, sortCount); a t
System.out.println("=== Inventory h a ls usReporte - Count ===");
c
an se to
( a
ri licen
t p u
for(Shirt shirt:poloList){

S a le
System.out.println(shirt.toString());
l b
}
ha sfer a
n c
6.
A - t r an
Runathe TestItemCounter.java class to ensure that your program produces the desired
output. n
no

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

Practices for Lesson 7: Generics and Collections


Chapter 7 - Page 16
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
a
)h ฺ
Practices for Lesson m
co 8: uString
a i l ฺ ide
Processing m t G
g
@ tude n
Chapter 8ri08
t p u his S
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 8: String Processing


Chapter 8 - Page 1
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

indicated in the instructions.

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 8: String Processing


Chapter 8 - Page 2
CETPA Infotech Pvt Ltd

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

Overview
In this practice, parse comma-delimited text and convert the data into Shirt objects.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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
o m
c uideฺ
i l ฺ
Shirt ID: S002
g ma nt G
Description: Black Polo Shirt
0 8 @ tude
Color: Black i
ur his S
t p
Size: L
a l sa se t
a n ch to u
Shirt ID: S003
r i (a ense
p
Description: Blue
t u Polo l ic Shirt
a
S rabl
Color: Blue
l e
a
nch ransfe
Size: XL
a
A Shirt
o n -t ID: S004
nDescription: 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 3
CETPA Infotech Pvt Ltd

Shirt ID: S007


Description: White T-Shirt
Color: White
Size: XL
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, 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
Shirt ID: S010
) h a
Description: Orange T-Shirt
c o m eฺ
Color: Orange i l
a t Guฺ i d
g m
Size: S
8 @ u d en
p u ri0 is St
Shirt ID: S011
l s at e th
Description: Maroon Polo Shirt
n c ha to us
Color: Maroon
( a a se
Size: S
u i
r licen
a t p le
l S
a fer a b
Tasks nch
OpenA
a trans
o n -
the StringsPractice01 project and make the following changes.
1. Editnthe 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 4
CETPA Infotech Pvt Ltd

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

Overview
In this practice, parse comma-delimited text and convert the data into Shirt objects.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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
o m
c uideฺ
i l ฺ
Shirt ID: S002
g ma nt G
Description: Black Polo Shirt
0 8 @ tude
Color: Black i
ur his S
t p
Size: L
a l sa se t
a n ch to u
Shirt ID: S003
r i (a ense
p
Description: Blue
t u Polo l ic Shirt
a
S rabl
Color: Blue
l e
a
nch ransfe
Size: XL
a
A Shirt
o n -t ID: S004
nDescription: 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 5
CETPA Infotech Pvt Ltd

Shirt ID: S007


Description: White T-Shirt
Color: White
Size: XL
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, 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
Shirt ID: S010
) h a
Description: Orange T-Shirt
c o m eฺ
Color: Orange i l
a t Guฺ i d
g m
Size: S
8 @ u d en
p u ri0 is St
Shirt ID: S011
l s at e th
Description: Maroon Polo Shirt
n c ha to us
Color: Maroon
( a a se
Size: S
u i
r licen
a t p le
l S
a fer a b
Tasks nch
OpenA
a trans
o n -
the StringsPractice01 project and make the following changes.
1. Editnthe 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 6
CETPA Infotech Pvt Ltd

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© 2014, 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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 8: String Processing


Chapter 8 - Page 7
CETPA Infotech Pvt Ltd

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© 2014, 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
m
Tasks
a i l ฺco uide
Open the StringsPractice02 project and make the following changes.
g m Please n t Gnote that the
code to read a file has been supplied for you.
0 8 @ tude
i
Note: The gettys.html file is located in the root of the
the project open, click the Files tab. Double-click a t
the pfileurtoproject
t h
open i it
S To examine the file, with
folder.
s and examine its contents.
l s e
1. Edit the FindText.java file.
n c ha to us
2. Create a Pattern and a Matcher ( a a field.se
u i
r licen
3. Generate a Matcher a p
t basedleon the supplied Pattern object.
4. Search each a S b supplied.
lline foretherapattern
h
ntheclineranumbersf and the line that has matching text.
5. Printa
A n-t n
6. Runnthe o FindText.java file and search for these patterns.
 All lines that contain: <h4>
 All the lines that contain the word “to” (For example, line 17 should not be selected.)
 All the lines that start with 4 spaces’
 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 8
CETPA Infotech Pvt Ltd

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© 2014, 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
a
)h ฺ
Tasks m
co uide
a i l ฺ
Open the StringsPractice02 project and make the following changes. Please
g m nt Gnote that the
code to read a file has been supplied for you.
0 8 @ tude
i
Note: The gettys.html file is located in the root of the
the project open, click the Files tab. Double-click a t
the pfileurtoproject
t h
open i it
S To examine the file, with
folder.
s and examine its contents.
l s e
1. Edit the FindText.java file.
n c ha to us
2. Create fields for a Pattern(and a aa Matcher
se object.
u r i e n
a tpPattern e ic
lpattern;
private
l S eMatchera l
b m;
a
private
h r
a nc ransf
A nthe
3. Outside -t search loop, create and initialize your pattern object.
n o
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 9
CETPA Infotech Pvt Ltd

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.)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

pattern = Pattern.compile("\\bto\\b");
 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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 8: String Processing


Chapter 8 - Page 10
CETPA Infotech Pvt Ltd

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© 2014, 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
fathers brought forth on this continent a new nation, conceived
s a
in liberty, and dedicated to the proposition that all men are
) h a
created equal.</span>
o m
c uideฺ
i l ฺ
14 <span class="sentence">Now we are engaged in a great civil
g ma nt G
war, testing whether that nation, or any nation, so conceived
and so dedicated, can long endure.</span>
0 8 @ tude
i
ur his S
15 <span class="sentence">We are met on a great battle-field of
t p
sa se t
that war.</span>
a l
ch to u
16 <span class="sentence">We have come to dedicate a portion of
a n
that field, as a final resting place for those who here gave
i (a ense
their lives that that nation might live.</span>
r
tpu le lic
17 <span class="sentence">It is altogether fitting and proper
a
h a l S erab
that we should do this.</span>

nc ransf
21 <span class="sentence">But, in a larger sense, we can not
a dedicate, we can not consecrate, we can not hallow this
A n-t
ground.</span>
no …

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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 11
CETPA Infotech Pvt Ltd

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© 2014, 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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 8: String Processing


Chapter 8 - Page 12
CETPA Infotech Pvt Ltd

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© 2014, 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
fathers brought forth on this continent a new nation, conceived
s a
in liberty, and dedicated to the proposition that all men are
) h a
created equal.</span>
o m
c uideฺ
i l ฺ
14 <span class="sentence">Now we are engaged in a great civil
ma nt G
war, testing whether that nation, or any nation, so conceived
g
and so dedicated, can long endure.</span>
0 8 @ tude
i
ur his S
15 <span class="sentence">We are met on a great battle-field of
that war.</span> t p
a l sa se t
16 <span class="sentence">We have come to dedicate a portion of
n ch to u
that field, as a final resting place for those who here gave
a
r i (a ense
their lives that that nation might live.</span>

tpu le lic
17 <span class="sentence">It is altogether fitting and proper
a
h a l S erab
that we should do this.</span>

nc ransf
21 <span class="sentence">But, in a larger sense, we can not
a dedicate, we can not consecrate, we can not hallow this
A n-t
ground.</span>
no …

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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 13
CETPA Infotech Pvt Ltd

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© 2014, 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 start and
end tags. Replace the attribute
a
)h ฺ
o m
a ilฺc Guide
if (m.find()) {
@ gm ent
String newStart = replaceTag(m.group(1),
r i 0 ud
8 StargetTag,
t
replaceTag);
a t pu thiattribute,
s
l s
newStart = replaceAttribute(newStart,
a s e value);

a n ch to u
String newEnd = replaceTag(m.group(3), targetTag, replaceTag);

r i ( a nse
t p
String newLineu = newStart
l i ce + m.group(2) + newEnd;
S a ble
System.out.printf("%3d
l %s\n", c, newLine);
} ha f er a
n c s
Aa n-tran
4.
noa method that will replace the contents of any tag.
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: String Processing


Chapter 8 - Page 14
CETPA Infotech Pvt Ltd

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© 2014, 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.

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 8: String Processing


Chapter 8 - Page 15
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 8: String Processing


Chapter 8 - Page 16
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson o m
c uideฺ
9:
i l ฺ
Exceptions and
g maAssertions
n t G
Chapter 9ri08
@ tude
t p u his S
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 1
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 2
CETPA Infotech Pvt Ltd

Practice 9-1: Summary Level: Catching Exceptions

Overview
In this practice, you will create a new project and catch checked and unchecked exceptions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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.
b. s
Select Java under Categories and Java Application under Projects. Click the Next a
button. )h ฺa
o m
i ฺc Guide
c. Enter the following information in the “Name and Location” dialoglbox:
a
 Project Name: ExceptionPractice
@ gm ent
0
 Project Location: D:\labs\09-Exceptions\practices.
r i 8 Stud
t pu this
 (checked) Create Main Class: com.example.ExceptionMain
a
 (checked) Set as Main Project ha
ls use
d. Click the Finish button. (aa
nc e to
r i e n s
2. u licmethod.
tpto thelmain
Add the following line
a
l S erab e
c h a
System.out.println("Reading
f from file:" + args[0]);

A a
Note:
t r a ns argument will be used to specify the file that will be read. Currently
nA command-line
- will be supplied, do not correct this oversight yet.
no arguments
3. non
Run the project. You should see an error message similar to:
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

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 3
CETPA Infotech Pvt Ltd

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:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
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:
s a
Reading from ) h a
file:D:\labs\resources\DeclarationOfIndependence.txt
c m
o ideฺ
i l ฺ
argument will only be passed to the main method if you run the g m
project. nt
Gu
a command-line
Warning: Running the project is not the same as running the file. The

8. i 0
Add the following lines of code to the main method rbelow 8@yourS t ude added lines:
previously
a t pu this
BufferedReader b =
h a ls FileReader(args[0]));
u se
new BufferedReader(newc
n e to
String s = null; aa
r i ( e n s null) {
u
tp le lic
while((s = b.readLine()) !=
a
l S erab
System.out.println(s);
} ha
a a n sf wizard by right-clicking in the source-code window.
ncFix rImports
9. A n-t
Run the
10. o now see compiler errors in some of the lines that you just added. These lines
Younshould
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
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.

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 4
CETPA Infotech Pvt Ltd

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]
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

 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
 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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 5
CETPA Infotech Pvt Ltd

Practice 9-1: Detailed Level: Catching Exceptions

Overview
In this practice, you will create a new project and catch checked and unchecked exceptions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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.
b. Select Java under Categories and Java Application under Projects. Click the Nexts a
button. )h ฺa
o m
i ฺc Guide
c. Enter the following information in the “Name and Location” dialoglbox:
a
 Project Name: ExceptionPractice
@ gm ent
0
 Project Location: D:\labs\09-Exceptions\practices.
r i 8 Stud
t pu this
 (checked) Create Main Class: com.example.ExceptionMain
a
 (checked) Set as Main Project ha
ls use
d. Click the Finish button. (aa
nc e to
r i e n s
2. u licmethod.
tpto thelmain
Add the following line
a
l S erab e
c h a
System.out.println("Reading
f from file:" + args[0]);

A a
Note:
t r a ns argument will be used to specify the file that will be read. Currently
nA command-line
- will be supplied; do not correct this oversight yet.
no arguments
3. non
Run the project. You should see an error message similar to:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at com.example.ExceptionMain.main(ExceptionMain.java:7)
Java Result: 1

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 6
CETPA Infotech Pvt Ltd

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!"
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

 Exit the application with an exit status of 1 by using the System.exit(1) method
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.
Checking the length of the args array is an alternate way to ensure that a command
s a
line argument was supplied.
) h a
5. Run the project. You should see an error message similar to: o m
c uideฺ
i l ฺ
No file specified, quitting!
g ma nt G
Java Result: 1
0 8 @ tude
6. Add a command-line argument to the project. i
ur his S
t p
a ande clickt Properties.
a. Right-click the ExceptionPracticelsproject
a
h select
cbox, u s
b. In the Project Properties dialog
a n t o the Run category.
c. In the Arguments field,r i (a value
enter a e n seof:
a tpu le lic
D:\labs\resources\DeclarationOfIndependence.txt
a
d. Click the
h lOKS button.
e r a b
7. ncproject.
Runathe a n sf should see a message similar to:
You
A n-tr
o
nReading 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:
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.

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 7
CETPA Infotech Pvt Ltd

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
11. Modify the project properties to support the try-with-resources statement.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
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] s a
) h a
 Exit the application.
o m
c uideฺ
i
a tG
 Add a catch clause for an IOException. Within the catch clause: l ฺ
g m
 Print " Error reading file:" along with the message
8 @ u d en in the
available
IOException object
p u ri0 is St
 Exit the application.
l s at e th
try (BufferedReader b =cha us
n t o
a se FileReader(args[0]));) {
( a
new BufferedReader(new
i
String s =ur null; cen
a p l e li
t = b.readLine())
l S
while((s
a b != null) {

n c ha System.out.println(s);
s f er
} an
Aa} catch(FileNotFoundException
n - tr
o
n System.out.println("File not e) {
found:" + args[0]);
System.exit(1);
} catch(IOException e) {
System.out.println("Error reading file:" + e.getMessage());
System.exit(1);
}
13. Run the project. You should see the content of the
D:\labs\resources\DeclarationOfIndependence.txt file displayed in the output
window.

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 8
CETPA Infotech Pvt Ltd

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© 2014, 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
ArrayIndexOutOfBoundsException.
s a
) h a
Future DAO implementations should not require any rewriting of the application logic
m
(EmployeeTestInteractive). However, some DAO implementations will generate checked
c uideฺ
o
i l ฺ
exceptions that must be dealt with. By creating a custom checked exception class that will be
ma nt G
used to wrap any DAO generated exceptions, all DAO implementations can appear to generate
g
0 8 @ tude
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.
i
ur his S
t p
Tasks
a l sa se t
1. Open the DAOException projectnas
a chthe maintoproject.
u
r i (a ense
a. Select File > Open Project.
a tpu le lic
b. Browse to D:\labs\09-Exceptions\practices.
h a l S erab and select the "Open as Main Project" check box.
a n c nsf
c. Select DAOException

traOpen Project button.


A Clickn-the
d.
no the project directories.
2. Expand
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 public 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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 9
CETPA Infotech Pvt Ltd

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.
The DAOException should contain a message String indicating what went wrong and
why.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

 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.
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. s a
 Use an if statement to validate that an existing employee is being updated. If) one
a
h would
not be, generate a DAOException and deliver it to the caller of the method. c m
o The eฺ
DAOException should contain a message String indicating what i l ฺ
a went twrong i d
u and why.
g m G
8 @
 Use a try-catch block to catch the ArrayIndexOutOfBoundsException
u d en
unchecked exception that could possibly be generated.
p u ri0 is St
 Within the catch block that you just created,
l s atgenerate
e tha DAOException and deliver it to
the caller of the method. The DAOException
c h a u s contain a message String
should
indicating what went wrong and
( a anwhy.se to
9. Modify the delete method
p u ri within
l i cthe
e nEmployeeDAOMemoryImpl class to:
 Declare thatS aa t le may be produced during execution of this method.
l a b
DAOException
 Use c anhifastatement
f erto validate that an existing employee is being deleted. If one would
n
a be, generate s
an should
Anot - t r a DAOException and deliver it to the caller of the method. The

non
DAOException 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.
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.

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 10
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
b. Modify the executeMenu method to declare that it throws an additional exception of
type DAOException.
s a
c. Remove the throws statement from the main method.
) h a
public static void main(String[] args) throws Exception m
co uideฺ
i l ฺ
ma nt G
d. Modify the main method to use a try-with-resources statement.
g
 Surround the do-while loop with a try block. 8@
i 0 t u de
 Convert the EmployeeDAO and BufferedReader
t p ur hreferences
i s S into auto-closed
resources.
a l sa se t
n ch to touthe end of the try block to handle both
 Add a catch clause for an IOException
a
r i e n se method and when auto-closing the
a executeMenu
I/O errors thrown from(the
BufferedReader.
a tpu le lic
a l S erab e) {
catch (IOException
h
a a sf
nc System.out.println("Error
n " + e.getClass().getName() +
tr
A " ,n-quitting.");
o
n System.out.println("Message: " + e.getMessage());
}
 Add a second catch clause for an Exception to the end of the try block to handle
errors when auto-closing the EmployeeDAO.
catch (Exception e) {
System.out.println("Error closing resource " +
e.getClass().getName());
System.out.println("Message: " + 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.

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 11
CETPA Infotech Pvt Ltd

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) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

System.out.println("Error " + e.getClass().getName());


System.out.println("Message: " + e.getMessage());
}
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

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 12
CETPA Infotech Pvt Ltd

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© 2014, 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
ArrayIndexOutOfBoundsException.
s a
) h a
Future DAO implementations should not require any rewriting of the application logic
m
(EmployeeTestInteractive). However, some DAO implementations will generate checked
c uideฺ
o
i l ฺ
exceptions that must be dealt with. By creating a custom-checked exception class that will be
ma nt G
used to wrap any DAO generated exceptions, all DAO implementations can appear to generate
g
0 8 @ tude
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.
i
ur his S
t p
Tasks
a l sa se t
1. Open the DAOException projectnas
a chthe maintoproject.
u
r i (a ense
a. Select File > Open Project.
a tpu le lic
b. Browse to D:\labs\09-Exceptions\practices.
h a l S erab and select the "Open as Main Project" check box.
a n c nsf
c. Select DAOException

traOpen Project button.


A Clickn-the
d.
no the project directories.
2. Expand
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 public 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() {

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 13
CETPA Infotech Pvt Ltd

super();
}

public DAOException(String message) {


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

public DAOException(Throwable cause) {


super(cause);
}

public DAOException(String message, Throwable cause) {


super(message, cause);
}
}
6. Modify all the methods in the EmployeeDAO interface. s a
) h a
 All methods should declare that a DAOException may be thrown duringm execution.
 Extend the AutoCloseable interface. i l ฺ c uideฺ
o
m a tG
@ g en{
public interface EmployeeDAO extends AutoCloseable
8 u d
p u ri0 is St
public void add(Employee emp)
l s at throws
e th DAOException;
n c ha to us
( a a se emp) throws DAOException;
public void update(Employee

u i
r licen
p
t delete(int
publicavoid l e id) throws DAOException;
S
al fera b
c h
n publics Employee findById(int id) throws DAOException;
Aa n-tran
no public Employee[] getAllEmployees() throws DAOException;
}
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.
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.

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 14
CETPA Infotech Pvt Ltd

 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) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

throw new DAOException("Error adding employee in DAO,


employee id already exists " + emp.getId());
}
try {
employeeArray[emp.getId()] = emp;
} catch (ArrayIndexOutOfBoundsException e) {
throw new DAOException("Error adding employee in DAO, id
must be less than " + employeeArray.length);
}
}
Note: Checking the length of the employeeArray could be used to determine whether the a
DAOException should be thrown however the use of a try-catch block will be typical of a s
the structure used when create a database enabled DAO.
m )h ฺ
o
8. Modify the update method within the EmployeeDAOMemoryImpl class
a ilฺcto: Guide
 Declare that a DAOException may be produced during execution
@ gm eofnthis t method.
r i
 Use an if statement to validate that an existing employee 0 8 is Sbeingt udupdated. If one would
not be, generate a DAOException and deliver
a t puit to the
t h s of the method. The
icaller
DAOException should contain a message
a s
l use String indicating what went wrong and why.
 Use a try-catch block to catch n h
cthe ArrayIndexOutOfBoundsException
to
unchecked exception that ( a a
could s e
possibly be generated.
u r i e n
p thatleyou
 Within the catch tblock
a licjust created, generate a DAOException and deliver it to
h a lS
the caller of the method.
e r a b The DAOException should contain a message String
a nc ransf
indicating what went wrong and why.
A public
n -t void update(Employee emp) throws DAOException {
o
n if(employeeArray[emp.getId()] == null) {
throw new DAOException("Error updating employee in DAO,
no such employee " + emp.getId());
}
try {
employeeArray[emp.getId()] = emp;
} catch (ArrayIndexOutOfBoundsException e) {
throw new DAOException("Error updating employee in DAO,
id must 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.

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 15
CETPA Infotech Pvt Ltd

 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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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) {
throw new DAOException("Error deleting employee in DAO,
no such employee " + id);
}
try {
employeeArray[id] = null;
} catch (ArrayIndexOutOfBoundsException e) {
s a
throw new DAOException("Error deleting employee in DAO,
)h ฺa
id must be less than " + employeeArray.length);
o m
}
a ilฺc Guide
}
@ gm ent
10. Modify the findById method within the EmployeeDAOMemoryImpl
r i 0 8 Stud class to:
 Declare that a DAOException may be produced
a t pu during
t h isexecution of this method.
 Use a try-catch block to catch the
s
l use
aArrayIndexOutOfBoundsException
c h tbeogenerated.
unchecked exception that could
( a anpossibly
s e
i youcjust
 Within the catch blockrthat
u e ncreated, generate a DAOException and deliver it to
t p
the caller of the method.
a l i
The DAOException should contain a message String
e and why.
l S
indicating what went a b l
wrong
n c ha Employee
s f er findById(int id) throws DAOException {
Aa n-try tran{
public

no return employeeArray[id];
} catch (ArrayIndexOutOfBoundsException e) {
throw new DAOException("Error finding employee in DAO",
e);
}
}
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 16
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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 {
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.
s a
 Surround the do-while loop with a try block.
)h ฺ a
 Convert the EmployeeDAO and BufferedReader references into auto-closed
o m
resources.
a ilฺc Guide
 Add a catch clause for an IOException to the end of the
@ gmtry block
e n t to handle both
I/O errors thrown from the executeMenu method
i 0 8and when
t d
uauto-closing the
u r S
BufferedReader.
s a tp this
 Add a second catch clause for ana
h l useto the end of the try block to handle
Exception
errors when auto-closing the c
an se to
EmployeeDAO.
( a
ri daoli=cefactory.createEmployeeDAO();
n
try (EmployeeDAO
t p u
a
BufferedReader
S b l e in =

h al fera
new BufferedReader(new
c
InputStreamReader(System.in))) {
n do { s
Aa n-tran timeToQuit = executeMenu(in, dao);
no } while (!timeToQuit);
} catch (IOException e) {
System.out.println("Error " + e.getClass().getName() +
" , quitting.");
System.out.println("Message: " + e.getMessage());
} catch (Exception e) {
System.out.println("Error closing resource " +
e.getClass().getName());
System.out.println("Message: " + 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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 17
CETPA Infotech Pvt Ltd

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) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

System.out.println("Error " + e.getClass().getName());


System.out.println("Message: " + e.getMessage());
}
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

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 9: Exceptions and Assertions


Chapter 9 - Page 18
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
)h ฺa
Practices for Lesson m
co 10:uiJava
a i l ฺ de
I/O Fundamentals m nt G
g
@ tude
i 0 8
t p ur his S
Chapter 10

a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 1
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 2
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, 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\
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
the file is exhausted, it returns the value of instanceCount. Note that the class rethrows
s a
any IOException encountered, so you will need to be sure to use this method inside a
)h ฺ a
try-catch block. m
o ide
3. Code the main method to check the number of arguments passed. a ilฺcapplication
The G u expects
at least one argument (a string representing the file to open). g m number
If the n t of arguments is
@ d e
u r i08 s Stu
less than one, exit the application with an error code (-1).
a. The main method is passed an array of Strings.
whether the array contains less than lones tp Useththei length attribute to determine
aargument.
c h a u se
b. Print a message if there is a
a n than one
less
e toargument, and use System.exit to return
r i (
an error code. (-1 typically is used
e n s
to indicate an error.)
u
tp passed ic the application as a String.
linto
4. a
Save the first argument
l e
l S ofertheabFileScanInteractive class. You will need this instance to
5. a
Create anhinstance
callathe
a n sf method.
nccountTokens
6. Openo
tr console for input using a buffered reader.
A then-system
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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 3
CETPA Infotech Pvt Ltd

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.
a. Right-click the project and select Properties.
b. Click Run.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
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.
) h a
Enter the search string or q to exit: free o m
c uideฺ
i l ฺ
The word "free" appears 4 times in the file.
g ma nt G
Enter the search string or q to exit: q
0 8 @ tude
i
ur his S
BUILD SUCCESSFUL (total time: 16 seconds)
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 4
CETPA Infotech Pvt Ltd

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© 2014, 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.
2. Open the file FileScanInteractive. s a
a
) hThis ฺ
Notice that the class has a method called countTokens already written for you.
m
method takes a String file and String search as parameters. The method
a i l ฺco willuopen
i de the
file name passed in and use an instance of a Scanner to look for the searchG
minstanceCount.token. For
each token encountered, the method increments the integer g
field e n t When
0 8 @ u d
t that the class rethrows
p u ribe
the file is exhausted, it returns the value of instanceCount.
i s
Note
Suse
any IOException encountered, so you will need
s a t to
tsure
h to this method inside a
try-catch block.
c h al use
3. Code the main method to checkathe
a n numbere tofoarguments passed. The application expects
i
at least one argument (a string
r ( n s
representing
e the file to open). If the number of arguments is
less than one, exit the u
tp le lic
application with an error code (-1).
a. The mainl method
a
S risapassed
b an array of Strings. Use the length attribute to determine
h a e
a nc ransf
whether the array contains less than one argument.
A Printn-atmessage if there is less than one argument, and use System.exit to return
b.
nano 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 5
CETPA Infotech Pvt Ltd

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© 2014, 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
break statement. Inside the 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 s a
)h ฺ
lowercase “Q.” Also the trim() method is a good choice to remove any whitespace
a
m
characters from the input.
a i lฺco uide
m callnthe
d. If the string read from the console is not the terminate character, t G
the g
countTokens method, passing in the file name and @
i 0 8 t u de
search string.

t p ur token
e. Print a string indicating how many times the search
h i s S
appeared in the file.
sa something
f. Your code inside the try block shouldllook e t like this:
a
h to u s
String search = ""; nc
a se through the file: " + file);
(a("Searching
System.out.println
u r i e n
while (true)tp{
a l e lic
h a l S erab
System.out.print("Enter the search string or q to exit: ");
n c search
ns f
= in.readLine().trim();
Aa n-iftra(search.equalsIgnoreCase("q")) break;
o
n 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 6
CETPA Infotech Pvt Ltd

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,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

D:\labs\resources\DeclarationOfIndependence.txt).
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
The word "rights" appears 3 times in the file.
s a
Enter the search string or q to exit: free
) h a
The word "free" appears 4 times in the file. o m
c uideฺ
i l ฺ
ma nt G
Enter the search string or q to exit: q
BUILD SUCCESSFUL (total time: 16 seconds) g
@ tude
i 0 8
t p ur his S
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 7
CETPA Infotech Pvt Ltd

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© 2014, 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.
3. Open the SerializeTest class. You will write the methods in this class to write several s a
ShoppingCart objects to the file system.
)h ฺ a
m
o ID and
a. Read through the code. You will note that the class prompts for theฺc
a l cart
iconstructor.
u ide
constructs an instance of ShoppingCart with the cart ID in the
g m nt G
b. The code then adds three Item objects to the ShoppingCart.
0 8 @ tude
c. The code then prints out the number of items
i
uinrthe cart,
s S the total cost of the items
and
t p
a ande Item h i
t classes in the
a
com.example.domain packagehfor detailsu
s
in the cart. Look through the ShoppingCart
l s
on how these classes work.
a n c t o
(a to open
d. You will be writing the code
i n e ObjectOutputStream and write the
san
r
ShoppingCart asua serialized e
a tp le lic object on the file system.
4.
a S toropen
Create the tryl block a b a FileOutputStream chained to an
h e
nc ransf The file name is already constructed for you.
ObjectOutputStream.
a.
a
A Yourn-code
t will go where the comment line is at the bottom of the file.
o
b. nOpen 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.

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

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 8
CETPA Infotech Pvt Ltd

6. Your code will go where the comment line is at the bottom of the file.
a. Open a FileInputStream with the cartFile string in a try-with-resources block.
b. Pass the file input stream instance to an ObjectInputStream to read the serialized
object instance from the file.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

c. Read the cart object from the object input 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:
System.out.println ("Shopping Cart contains: ");
List<Item> cartContents = cart.getItems();
for (Item item : cartContents) {
System.out.println (item); s a
} )h ฺ a
o m
ilฺc Guide
System.out.println ("Shopping cart total: " +
NumberFormat.getCurrencyInstance().format(cart.getCartTotal())); a
f. Save the file. @ gm ent
7. Open the ShoppingCart class. You will customize r i 0
the S t udand deserialization of
8serialization
this class by adding the two methods called a t puserialization/deserialization.
during t h is
s
al duringuserialization.
se
a. Add a writeObject method invoked
n c h t o This method should
serialize the current object
( a a
fields and
s e
then add a timestamp (Date object instance) to
i
ur lice
end of the object stream. n
t p
a ShoppingCart
le
8. Add a method to
l S the
a b class that is invoked during deserialization.
a fer method with the appropriate signature. This method will
a. Add c ha readObject
n
Aarecalculate
t r a nthes total cost of the shopping cart and print the timestamp that was added
n n-stream.
toothe
b. Save the file.
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.
b. The output will look like this:
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.

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

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 9
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Successfully deserialized shopping cart with ID: 101


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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 10
CETPA Infotech Pvt Ltd

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© 2014, 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
d. Click the Open Project button.
) h a
2. Expand the com.example.test package. Notice there are two Java main
c m
o classes einฺthis
i l ฺ i d
u in these
ma nt G
package, SerializeTest and DeserializeTest. You will be writing the code
main classes to serialize and deserialize ShoppingCart objects. g e
3. Open the SerializeTest class. You will write thermethods i 0 8@ inSthis
t udclass to write several
p u i s
ShoppingCart objects to the file system.
l s at e th
a. Read through the code. You will note
n c ha thattothe
usclass prompts for the cart ID and

( a a se
constructs an instance of ShoppingCart with the cart ID in the constructor.
b. The code then adds u i Item
rthree c e n to the ShoppingCart.
objects
a p l i
t outlethe number of items in the cart, and the total cost of the items
c. The code then S prints b
al Lookfethrough
ra the ShoppingCart and Item classes in the
in thehcart.
c
n rans
Aacom.example.domain
- t
package for details on how these classes work.

onwill be writing the code to open an ObjectOutputStream and write the


d. You
nShoppingCart 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 11
CETPA Infotech Pvt Ltd

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© 2014, 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.
5. Open the DeserializeTest class. The main method in this class reads from the console
s a
for the ID of the customer shopping cart to deserialize.
)h ฺa
6. Your code will go where the comment line is at the bottom of the file. o m
a
a. Open a FileInputStream with the cartFile string in a try-with-resources ilฺc Guideblock.
@ gm toeread n t
b. Pass the file input stream instance to an ObjectInputStream
i 0 8 t u d the serialized
object instance from the file.
t p ur his S
c. Read the cart object from the object s
l a stream
input
e tusing the readObject method. Be
a
ch to u
sure to cast the result to the appropriate objectstype.
a n
d. You will need to catch both
r i e n se
(a ClassNotFoundException and IOException, so use a

a t pu le lic
multi-catch expression.
e. Your code S should look blike this:
a l r a
a nch(FileInputStream
try
r a n s fe fis = new FileInputStream (cartFile);
A n-tObjectInputStream in = new ObjectInputStream (fis)) {
o
n cart = (ShoppingCart)in.readObject();
} catch (final ClassNotFoundException | IOException e) {
System.out.println ("Exception deserializing " + cartFile +
": " + e);
System.exit (-1);
}
System.out.println ("Successfully deserialized shopping cart
with ID: " + cart.getCartId());

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

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 12
CETPA Infotech Pvt Ltd

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© 2014, 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
private void writeObject(ObjectOutputStream oos) throws
)h ฺa
IOException { m
co thenuwrite
c. Make sure that the method serializes the current object fields first,
a ilฺand idethe
Date object instance: g m nt G
0 8 @ tude
oos.defaultWriteObject(); i
ur his S
oos.writeObject(new Date()); t p
} a l sa se t
8. Add a method to the ShoppingCart a n chclass that
t o u
is invoked during deserialization. This
method will recalculate the
r i (a costeofnsthee shopping cart and print the timestamp that was
total
added to the stream.tpu lic
a
l S with l e
bsignature:
h a
a. Add a method
e r a
the

a nc ranvoid
private sf readObject(ObjectInputStream ois) throws
A IOException,
n -t ClassNotFoundException {
n o
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 13
CETPA Infotech Pvt Ltd

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© 2014, 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
o m
c uideฺ
Shopping cart contains:
i l ฺ
g ma nt G
Item ID: 101 Description: Duke Plastic Circular Flying Disc
Cost: 10.95
0 8 @ tude
i
ur his S
Item ID: 123 Description: Duke Soccer Pro Soccer ball Cost:
t p
sa se t
29.95
a l
ch to u
Item ID: 45 Description: Duke "The Edge" Tennis Balls - 12-Ball
Bag Cost: 17.49
a n
r i (a ense
Shopping cart total: $58.39

a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 10: Java I/O Fundamentals


Chapter 10 - Page 14
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
a
)h ฺ
Practices for Lesson m
co 11:uiJava
a i l ฺ de
File I/O (NIO.2)m t G
g
@ tude n
i 0 8
t p ur his S
Chapter 11

a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

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


Chapter 11 - Page 1
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

the second practice, you will use the walkFileTree method to copy all the files and directories
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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

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


Chapter 11 - Page 2
CETPA Infotech Pvt Ltd

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© 2014, 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.
Note that this is a form letter with a string <NAME> that will be replaced by a name from the
s a
name list file.
) h a
2. Open the file NamesList.txt in the resources directory. m
co uideฺ
i l ฺ
a. This file contains the names to send the form letters to.
g ma nt G
b. Add your name to the end of the list.
0 8 @ tude
c. Save the file.
i
ur his S
t p t directory.
3. Open the project FormLetterWriter a sapractices
inlthe s e
4. Expand the FormLetterWriter a n ch tothat
class. Notice
u
this class contains the main method, and
i ( a n s e One is the
p u r file lcontaining
that the application requires two parameters:
i c e path to the form letter template, and
the second is the path
a t to the
l e the list of names to substitute in the form letter.

a l S foreraavalid
a. After checking
h
b number of arguments, the main method then checks to see
a nc rathenPath
whether sf objects point to valid files.
A Thenmain
b. -t method creates an instance of the FileMerge class with the form letter
o
nPath 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.
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.

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

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


Chapter 11 - Page 3
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
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 a
the name with underscores for readability of the file name. Create a new Path object a s
relative to the form template path.
m )h ฺ
o ofidthee form
e. Create another for loop, nested in the first loop, to iterate through
a ilฺcthe lines
u
G name
template and look for the token string ("<NAME>") to replace
g mwith thentString
from the nameList. Use the hasToken method to look
8 @for the u e that contains the
dString
i 0
urString.
token string and replace that string with one containing t
theSname from the nameList.
Use the mergeName method to create the t p
new h i s
t customLetter
a to theenew Add the modified String and all
of the other Strings from the formLetter a l s s
c h u List.
to List of Strings that represents the
f. Still inside the first for loop,
( a anwrite the s e modified
customized form letter
p u ri to thelicfileensystem by using the Files.write method. Print a
message thatathe t file write
l e was successful and close the outer for loop.
g. Savehthe
S
alFileMerge b
ra class.
c f e
7. A
Modify r a ns
anthe tFormLetterWriter project to pass the form letter file and the name list file to
the main
o n -
method.
n
a. Right-click the project and select Properties.
b. Select Run.
c. In the Arguments text field, enter: D:\labs\resources\FormTemplate.txt
D:\labs\resources\NamesList.txt
d. Click OK.

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

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


Chapter 11 - Page 4
CETPA Infotech Pvt Ltd

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© 2014, 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.

Good Luck!

s a
Oracle University
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

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


Chapter 11 - Page 5
CETPA Infotech Pvt Ltd

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© 2014, 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. Select File > Open File
s a
b. Navigate to the resources directory in D:\labs a
)h ฺ
c. Select the file FormTemplate.txt and click the Open button. ฺco
m
a il Guide
g
Note that this is a form letter with a string placeholder token <NAME> m thatnwill
t be replaced
by a name from the name list file. @
8 Stud e
r i 0
2. Open the file NamesList.txt in the resources
a t pudirectory.
t h is
a. This file contains the names to send athes
l formuletters
se to.
c h
b. Add your name to the end of
( a anthe list.se to
c. Save the file.
p u ri licen
a t le
3. Open the project
a l S b
FormLetterWriter
r a in the practices directory.

nch File
a. Select
a >s
n fe Project.
Open
A Browse
b.
n - trtoaD:\labs\11-NIO.2\practices.
o
c. nSelect FormLetterWriter.
d. 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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

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


Chapter 11 - Page 6
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
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.
s a
a. Create an instance of the default Charset. This argument is required for the
Files.readAllLines method. )h ฺ a
o m
Charset cs = Charset.defaultCharset();
a ilฺc Guide
b. Read in all of the lines of the form letter into the formLetter
@ gm field,enandt all of the lines
from the name list into the nameList field.
r i 0 8 Stud
Note: Because writeMergedForms throws
a t puIOException,
t h is you do not need to put
these statements into a try block. Thels e
caller of this method is responsible for handling
any exceptions thrown. c h a u s
a a n e to
r i ( n
formLetter = Files.readAllLines(form,
e s cs);
u
tp le lic
nameList = Files.readAllLines(list, cs);
a
S looprtoabiterate through the list of names (nameList) strings.
c. Createa alfor
h
nc this s fe create a new List object to hold the strings of the form letter. You
d. aInside nfor loop,
trathis new List to hold the modified form template strings to write out.
A willnneed
o -
nfor (int j = 0; j < nameList.size(); j++) {
customLetter = new ArrayList<>();
e. Still inside the for loop, you 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.
String formName = nameList.get(j).replace(' ',
'_').concat(".txt");
Path formOut = form.getParent().resolve(formName);
f.

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

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


Chapter 11 - Page 7
CETPA Infotech Pvt Ltd

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© 2014, 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));
}
}
g. Finally, still inside the first for loop, write the modified List of Strings that
represents the customized form letter to the file system by using the Files.write s a
)h ฺa
method. Print a message that the file write was successful and close the outer for loop.
o m
Files.write(formOut, customLetter, cs);
a ilฺc Guide
System.out.println ("Wrote form lettergto: m " +nt
nameList.get(j));
i 0 8 @ t u de
} // closing brace for the outer u
p r loopis S
for
h. Reformat the code to ensure that youls
t
a everythingth in the right place. Press the Ctrl-
have
hain thetoeditor
Alt-F key combination or right-click
e
uspane and choose Format.
n
a sec
i. Save the FileMerge class.
i ( a
r licproject n
7. t p u
Modify the FormLetterWriter
e to pass the form letter file and the name list file to
a
l S erab
the main method. l e
h a
nc ranthesfproject and select Properties.
a. Right-click
a
A Select
b. n -tRun.
o
c. nIn the Arguments text field, enter: D:\labs\resources\FormTemplate.txt
D:\labs\resources\NamesList.txt
d. Click OK.

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

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


Chapter 11 - Page 8
CETPA Infotech Pvt Ltd

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© 2014, 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.

Good Luck!
s a
Oracle University
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

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


Chapter 11 - Page 9
CETPA Infotech Pvt Ltd

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© 2014, 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
c. If the target file or directory exists, the user is prompted whether to overwrite.h
) a
d. If the answer is yes (or the letter y), the method continues. o m
c uideฺ
i l
a and ฺ
e. An instance of the CopyFileTree class is created with them
g source
n t Gtarget.
f. This instance is then passed to the walkFileTree
i 0 8 @ t(with
method u dethe source Path
object).
t p ur his S
You will need to provide method bodiesa l
for
a methods
sthe e t in the CopyFileTree.java
class. ch to u s
a n
3. Open the CopyFileTree.java r i (a class.
e n se
a tpu the
a. This class implements l e lic
l S rand
genericainterface, a bthis interface is boxedinterface.
FileVisitor Note that FileVisitor is a
with the Path class. This allows the
a nch ratondefine
interface sfe the type of the arguments passed to its methods.
A ThenCopyFileTree
b. -t implements all the methods defined by FileVisitor.
n o
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.
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.

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

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


Chapter 11 - Page 10
CETPA Infotech Pvt Ltd

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.
5. Write the method body for the visitFile method. This method is called when the node
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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));
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.
s a
e. Save your class.
) h a
6. m
c uideฺ
Test your application by copying a directory (ideally with subdirectories) tooanother location

on the disk. For example, copy the D:\labs\11-NIO.2 directory toilD:\Temp.
a tG
g m
a. Right-click the project and select Properties.
8 @ u d en
b. Click Run.
p u ri0 is St
c. Enter the following as Arguments:
l s at e th
D:\labs\11-NIO.2 D:\Temp
n c ha to us
d. Click OK. ( a a se
i
r lsee
ushould n
cethe
7.
a p
Run the project andtyou
e i following message:
l S ecopied
a l
b D:\labs\11-NIO.2 to D:\Temp
a
Successfully
h r
a. Run
a a sf again, and you should be prompted:
nc therproject
n
A Target
n -t directory exists. Overwrite existing files? (yes/no):
n o

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

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


Chapter 11 - Page 11
CETPA Infotech Pvt Ltd

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© 2014, 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. a
)h ฺ
m
e. Click the Open Project button.
a i l ฺco uide
2. Expand the Source Packages folder and subfolders and look at m
g the Copy.java
n t G class.
a. Note that the Copy.java class contains the main 8
0 @ tude
method.
i
ur andhtarget
s S paths.
b. The application takes two arguments, a source t
a etp i
c. If the target file or directory exists, a l suser s
n c h to isuprompted
the whether to overwrite.
d. If the answer is yes (or the
( a aletter y),sthe
e method continues.
e. An instance of the
i n
r lice class is created with the source and target.
uCopyFileTree
t p
ais then bpassed
le to the walkFileTree method (with the source Path
l
f. This instanceS a
c ha sfer
object).
n
You - tratonprovide method bodies for the methods in the CopyFileTree.java
Aawillnneed
no
class.
3. Open 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 © 2012, Oracle and/or its affiliates. All rights reserved.

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


Chapter 11 - Page 12
CETPA Infotech Pvt Ltd

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© 2014, 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) {
// ignore
s a
d. Do catch any other IOExceptions, and use the SKIP_SUBTREE return to avoid
)h ฺa
repeated errors.
o m
} catch (IOException x) { a ilฺc Guide
System.err.format("Unable to create: %s:
@ gm%s%n", e n t
newdir, x); i08
r S t ud
return SKIP_SUBTREE;
a t pu this
}
h a ls use
5. a
Write the method body for the visitFile n c method.to This method is called when the node
( a s e
reached is a file. The file risi passed asnan argument to the method.
t p u l i c e
l Sathat ryou
a. As with the preVisitDirectory,
with theapath a le for theyou
bwanted must rationalize the file reached (source path)
target. Use the same method call as above (only
a nchfile
using
n s fe of dir):
instead
ra = target.resolve(source.relativize(file));
A Path n - tnewdir
o
b. nAs 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);
}

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

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


Chapter 11 - Page 13
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

b. Click Run.
c. Enter the following as Arguments:
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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

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


Chapter 11 - Page 14
CETPA Infotech Pvt Ltd

(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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

FileVisitor to recursively delete a file or directory pattern.

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
4. You must code the remainder of this class. Look at the comments for hints as to what h a
) to do.ฺ
m
o in asithe
a. Start by creating a PathMatcher object from the search string passed
second argument. To obtain a PathMatcher instance, you will a i l ฺ c
need to use u de
the
FileSystems class to get a path matcher instance fromg mdefaultnfile
the t Gsystem.
@ d e
b. Create a Path object from the first argument. ri08 S tu
u
tpthe pattern
h s the PathMatcher
iusing
c. If the starting path is a file, check it against
s a
l udelete t
instance that you created. If therehisaa match,
c se the file, and then terminate the
application.
( a an se to
d. If the starting path uisrai directory,
c e ncreate an instance of the DeleteFileTree with the
a
starting directory p l i
t and thelePathMatcher object as initial arguments in the constructor.
a
Pass the
S r a b and the file tree to a Files.walkFileTree method to
lstartingedirectory
h
nc ranlook
recursively sf for the pattern to delete.
a
A Fixnany
e.
o -t missing imports.
f. nSave 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.
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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

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


Chapter 11 - Page 15
CETPA Infotech Pvt Ltd

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.
b. Right-click the project and select Properties.
c. Click Run and enter the following in the Arguments text field:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

D:\Temp\examples *.class
d. Run the project.

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

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


Chapter 11 - Page 16
CETPA Infotech Pvt Ltd

(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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

FileVisitor to recursively delete a file or directory pattern.

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
d. Click the Open Project button.
a
)h ฺ
o m
2. Expand the Source Packages folders.
a ilฺc Guide
3. Open the Delete.java class file. This is the class that contains
@ gmthe maine n t method. The
main class accepts two arguments: the first is the starting
i 0 8 pathSand
t d other the pattern to
uthe
delete.
p r
u his
a t
sLook atsthe t
4. You must code the remainder of this class.
h a l u e comments for hints as to what to do.
a. Start by creating a PathMatcher
a n c objecttofrom the search string passed in as the
second argument. To obtain
r i n se
(a a ePathMatcher instance, you will need to use the
FileSystems class u
tp le lic
to get a path matcher instance from the default file system.
a
l S ematcherb =
a
PathMatcher
h r a
a n c nsf
FileSystems.getDefault().getPathMatcher("glob:" + args[1]);
A Create
b.
n - traaPath object from the first argument.
o root = Paths.get(args[0]);
nPath

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

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


Chapter 11 - Page 17
CETPA Infotech Pvt Ltd

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© 2014, 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);
System.exit(-1);
}
s a
}
)h ฺa
} m
co uide
a i l ฺ
g m ninttheGconstructor.
d. If the starting path is a directory, create an instance of the DeleteFileTree with the
starting directory and the PathMatcher object as initial
0 8 @ tude method to
arguments
i
Pass the starting directory and the file tree to a Files.walkFileTree
r is S
recursively look for the pattern to delete. tpu
l s a e th
DeleteFileTree deleter = hnew
c a DeleteFileTree(root,
us matcher);
try { n
a se t o
i ( a
r licen deleter);
t p u
Files.walkFileTree(root,
a
} catch (IOException
S b l e e) {

c h al fera
System.out.println("Exception: " + e);

A a}n trans
e. Fixn
o any- missing imports.
n
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 © 2012, Oracle and/or its affiliates. All rights reserved.

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


Chapter 11 - Page 18
CETPA Infotech Pvt Ltd

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© 2014, 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.
a. For example, if you completed the first practice, you can delete all the Java class files
s a
from the D:\Temp directory.
) h a
b. Right-click the project and select Properties. o m
c uideฺ
i l ฺ
ma nt G
c. Click Run and enter the following in the Arguments text field:
g
D:\Temp\examples *.class
0 8 @ tude
d. Run the project.
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

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


Chapter 11 - Page 19
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

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


Chapter 11 - Page 20
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson o m
c uideฺ
12:
i l ฺ
Threading
g ma nt G
0 8 @ tude
i
ur his S
Chapter 12
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 12: Threading


Chapter 12 - Page 1
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 12: Threading


Chapter 12 - Page 2
CETPA Infotech Pvt Ltd

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© 2014, 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
b. Browse to D:\labs\12-Threading\practices. m
co uideฺ
i l ฺ
c. Select Synchronized and select the "Open as Main Project"
g machecknbox.
t G
d. Click the Open Project button.
0 8 @ tude
i
ur review s Sprovided classes at this
2. Expand the project directories but avoid opening
t pand
a application
point. You will attempt to discover whetherlsthis h i the
t is multithreaded by observing the
behavior of code that you provide. ch a u s e
a n t o
3. Create a PurchasingAgent
r i secom.example package.
(aclasseinnthe
4. tpu le licclass.
Complete the PurchasingAgent
a
a l S ermethod.
a. Add a purchase
h a b
a nc ravoid
public n sf purchase() {}
A n-t
no
b. Complete the purchase method. The purchase() method should:
 Obtain a Store reference. Note that the Store class implements the Singleton
design pattern.
Store store = Store.getInstance();

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

Practices for Lesson 12: Threading


Chapter 12 - Page 3
CETPA Infotech Pvt Ltd

 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© 2014, 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 m
co uideฺ
i l ฺ
a behavior,
 One success message, one shirt, and one failure message (desired
g m n t G but least
likely)
0 8 @ tude
6. Discover how the PurchasingAgent class is being i
ur his S
used.
t p thow many instances of the
a. Use a constructor and a print statement
a l sato discover
s e
PurchasingAgent class are being
n c h to u running the application.
created when
a
Reminder: Sometimes (objects a arescreated
e per-request and sometimes an object may
u
be shared by multiple r irequests.e n
c variations in the model affect which code must be
The
thread-safe. atp l i
l S a b le
b. Within
n c hathe purchase
s f erthread
method use the Thread.currentThread() method to obtain

tran to print the name and ID of the executing thread.


a reference to the currently executing the purchase() method. Use a single
Aaprintn-statement
o
c. nRun the project and observe the output.
7. 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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 4
CETPA Infotech Pvt Ltd

9. Use a synchronized code block to create predictable behavior.


 Modify the purchase method in the PurchasingAgent class to contain a
synchronized code block.
Note: Adding synchronized to the method signature or using a synchronized
block that uses the this object’s monitor will not work.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 12: Threading


Chapter 12 - Page 5
CETPA Infotech Pvt Ltd

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© 2014, 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
b. Browse to D:\labs\12-Threading\practices. m
co uideฺ
i l ฺ
c. Select Synchronized and select the "Open as Main Project"
g machecknbox.
t G
d. Click the Open Project button.
0 8 @ tude
i
ur review s Sprovided classes at this
2. Expand the project directories but avoid opening
t pand
a application
point. You will attempt to discover whetherlsthis h i the
t is multithreaded by observing the
behavior of code that you provide. ch a u s e
a n t o
3. Create a PurchasingAgent
r i secom.example package.
(aclasseinnthe
4. tpu le licclass.
Complete the PurchasingAgent
a
a l S ermethod.
a. Add a purchase
h a b The purchase() method should:
an
c nsf reference. Note that the Store class implements the Singleton
Obtain a Store
A design
n - trapattern.
o
n Buy a Shirt.
 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 6
CETPA Infotech Pvt Ltd

public class PurchasingAgent {

public void purchase() {


Store store = Store.getInstance();
if (store.getShirtCount() > 0 &&
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, 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");
}
}
}
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:
s a
 Two success messages and two shirts (output may appear in varying order)) ha
c o m eฺ
Adding a shirt to the store.
a il Guid

Total shirts in stock: 1
@ gm ent
The shirt is ours!
r i 0 8 Stud
The shirt is ours!
a t pu this
Shirt ID: 1
h a ls use
Description: Polo
a n c to
Color: Rainbow
( a s e
Size: Large uri c e n
a t p l i
l S a b le
c
Shirt
n haID: s1fer
- t r an Polo
AaDescription:
on Rainbow
nColor:
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

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

Practices for Lesson 12: Threading


Chapter 12 - Page 7
CETPA Infotech Pvt Ltd

Adding a shirt to the store.


Total shirts in stock: 1
The shirt is ours!
Shirt ID: 1
Description: Polo
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Color: Rainbow
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
m
a i lฺco uide
No shirt for you
g m nt G
6. Discover how the PurchasingAgent class is being used.
0 8 @ tude
i
ur and s S
a. In the PurchasingAgent class, use a constructor
t p h i a print statement to discover
t are being created when running
how many instance of the PurchasingAgent
a l sa sclasse
the application.
a n ch to u
public PurchasingAgent()
r i (a en{se
a tpu le lic
System.out.println("Creating a purchasing agent");
}
h a l S erab
a ncshared
Reminder:
a n sf
Sometimes objects are created per-request and sometimes an object may
A n-tr
be by multiple requests. The variations in the model affect which code must be
o
nthread-safe.
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 8
CETPA Infotech Pvt Ltd

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");
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

try {
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
PurchasingAgent.purchase methods calls will both believe that a shirt can be taken
but take the shirt at a different time. Taking the shirt at the near the same time typically
s a
results in some of the other errors shown in step 5.
) h a
9. Use a synchronized code block to create predictable behavior. o m
c uideฺ
i l ฺ
a to contain
 Modify the purchase method in the PurchasingAgent class
g m n t Ga
synchronized code block.
0 8 @ tude
synchronized (store) {
ur i sS
if (store.getShirtCount() a>tp 0 && thi
h
store.authorizeCreditCard("1234",a ls us15.00))
e {
c to
Shirt shirt = nstore.takeShirt();
a
( a s e
p u ri licen
System.out.println("The shirt is ours!");

a t
System.out.println(shirt);
le
l S
} else { a b
n c ha System.out.println("No
s f er shirt for you");
a
A n-}tra n
n}o
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 9
CETPA Infotech Pvt Ltd

Practice 12-2: Summary Level: Implementing a Multithreaded Program

Overview
In this practice, you will create a new project and start a new thread.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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. Select File > New Project.
s a
b. Select Java under Categories and Java Application under Projects. Click the ) h a
Next
button. o m
c uideฺ
i l ฺ
g ma box:
c. Enter the following information in the “Name and Location” dialog
n t G
 Project Name: ThreadInterrupted
0 8 @ tude
i
ur his S
p
 Project Location: D:\labs\12-Threading\practices.
t
a l sa se t
 (checked) Create Main Class: com.example.ThreadInterruptedMain
a
 (checked) Set as Main Projectn ch to u
r i (a ense
a t pu le lic
d. Click the Finish button.
2.
a l S class
Create a Counter
r a bthe com.example package.
in
3.
nchtheraCounter
Complete
a n sfe class. The Counter class should:
AImplement
-t the Runnable interface.
o n
n the run method:
 Within
 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.

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

Practices for Lesson 12: Threading


Chapter 12 - Page 10
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

b. Click Stop Build/Run.


Note: You can also stop a build/run by clicking the red square along the left side of the
output window.
7. Modify the project properties to support the try-with-resources statement.
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();
s a
} catch (IOException e) {}
) h a
Note: You may need to fix your imports and update the project properties m eฺ
co tousupport
JDK 7 features. i
a tG l ฺ i d
g m
 Print out a message indicating whether or not the thread is alive. en
0 8 @ tud
 Interrupt the thread. i
ur his S
t p t
 Delay for one second (to allow the thread
message indicating whether or noth a satimeistosalive.
lthread complete)
e and then print out a

n c the
t o u
9. Run the project. You should(seea sewhile thesequence
a an incrementing of numbers with a one second
u
delay between each number.r i Pressc e n
Enter output window is selected to gracefully
t p
a ble
terminate the application. l i
l S
a fera
n c h s
Aa n-tran
no

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

Practices for Lesson 12: Threading


Chapter 12 - Page 11
CETPA Infotech Pvt Ltd

Practice 12-2: Detailed Level: Implementing a Multithreaded Program

Overview
In this practice, you will create a new project and start a new thread.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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. Select File > New Project.
s a
b. Select Java under Categories and Java Application under Projects. Click the ) h a
Next
button. o m
c uideฺ
i l ฺ
g ma box:
c. Enter the following information in the “Name and Location” dialog
n t G
 Project Name: ThreadInterrupted
0 8 @ tude
i
ur his S
p
 Project Location: D:\labs\12-Threading\practices.
t
a l sa se t
 (checked) Create Main Class: com.example.ThreadInterruptedMain
a
 (checked) Set as Main Projectn ch to u
r i (a ense
a t pu le lic
d. Click the Finish button.
2.
a l S class
Create a Counter
r a bthe com.example package.
in
3.
nchtheraCounter
Complete
a n sfe class. The Counter class should:
AImplement
-t the Runnable interface.
o n
n the run method:
 Within
 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.

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

Practices for Lesson 12: Threading


Chapter 12 - Page 12
CETPA Infotech Pvt Ltd

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© 2014, 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();
Thread t = new Thread(r); s a
t.start(); )h ฺa
m
o a oneidsecond
e
5. Run the project. You should see an incrementing sequence of numbers
a i l ฺcwith u
delay between each number. Notice that while the main methodm
g has completed
n t G the
application continues to run.
0 8 @ tude
6. Stop the project. i
ur his S
t p
a. Open the Run menu.
a l sa se t
b. Click Stop Build/Run.
a n ch to u
e the red square along the left side of the
(a ebynsclicking
Note: You can also stop raibuild/run
output window.
a tpu le lic
7. l S properties
Modify the project
h a e r a b to support the try-with-resources statement.
nc ranthesfThreadInterrupted project and click Properties.
a. aRight-click
A n-Project
b. Inothe
t Properties dialog box select the Sources category.
n
c. 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Threading


Chapter 12 - Page 13
CETPA Infotech Pvt Ltd

 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© 2014, 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
System.out.println("Thread is alive:" + t.isAlive());
) h a
9. Run the project. You should see an incrementing sequence of numbers with m
co a toone eฺ
second
l ฺ
delay between each number. Press Enter while the output window is iselected u i d
gracefully
terminate the application. g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 12: Threading


Chapter 12 - Page 14
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson o m
c uideฺ
13:
i l ฺ
Concurrency ma t G
g
@ tude n
i 0 8
t p ur his S
Chapter 13

a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 13: Concurrency


Chapter 13 - Page 1
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 13: Concurrency


Chapter 13 - Page 2
CETPA Infotech Pvt Ltd

(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© 2014, 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
a. Select File > Open Project.
)h ฺa
m
b. Browse to D:\labs\13-Concurrency\practices.
a i l ฺco uide
c. Select ExecutorService and select the "Open as Main Project"
g m check n t Gbox.
d. Click the Open Project button.
0 8 @ tude
i
ur his S
2. Expand the project directories. t p t
3. Run the NetworkServerMain class inathe l sacom.example.server
s e package by
c h u
( a an RunseFile.to
right-clicking the class and selecting
4. Open the NetworkClientMain
p u ri licclass e n in the com.example.client package.
5. a t
Run the NetworkClientMain le itclass package by right-clicking the class and selecting Run
File. Noticea l
the
S
amount r a
ofbtime takes to query all the servers sequentially.
c h f e
6.
Aa n
Create
t r a ns
n a NetworkClientCallable class in the com.example.client package.
 o
-
n Add a constructor and a field to receive and store a RequestResponse reference.
 Implement the Callable interface with a generic type of RequestResponse.
public 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.

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

Practices for Lesson 13: Concurrency


Chapter 13 - Page 3
CETPA Infotech Pvt Ltd

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.
 The servers should be running on localhost, ports 10000–10009.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

 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
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
s a
terminate the server application.
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 13: Concurrency


Chapter 13 - Page 4
CETPA Infotech Pvt Ltd

(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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Assumptions
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
b. Browse to D:\labs\13-Concurrency\practices. m
co uideฺ
i l ฺ
c. Select ForkJoinFindMax and select the "Open as Main Project"
g ma check n t Gbox.
d. Click the Open Project button.
0 8 @ tude
i
ur his S
2. Expand the project directories.
t
a et p
a l spackage.
3. Open the Main class in the com.example
n c h to us
( a a method.
 Review the code within the main
s Take note of how the compute method splits
eto process
u i
r lice
the data array if the count of n
elements is too great.
4. a
Open the FindMaxTask
p
t class le in the com.example package.
l S a
a codefewithin b
r the class. Take note of the for loop used to initialize the data
 Review
n c hthe s
n numbers.
a withtrarandom
Aarray -
5.
non
Create a RandomArrayAction class in the com.example package.
a. Add four fields.
private 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.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Concurrency


Chapter 13 - Page 5
CETPA Infotech Pvt Ltd

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() { }
e. Begin the compute method. If the number of elements to process is below the
threshold, you should initialize the array.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

for (int i = start; i <= end; i++) {


myArray[i] = ThreadLocalRandom.current().nextInt();
}
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 s a
instead of the fork/join/compute combination typically seen with a )h ฺa
o m
RecursiveTask.
a ilฺc Guide
RandomArrayAction r1 = new RandomArrayAction(myArray,
@ gm ent start,
midway, threshold);
r i 0 8 Stud
t p u his
RandomArrayAction r2 = new RandomArrayAction(myArray, midway +
1, end, threshold);
a l sa se t
invokeAll(r1, r2);
a n chclass totouseuthe RandomArrayAction class.
6. Modify the main method of the
r i (a ense
Main
a. Comment out the
t p u looplwithin
for ic the main method that initializes the data array with
a
S rabl
random values.
l e
a
nchtheralinensthat
b. After
a
fecreates the ForkJoinPool, create a new RandomArrayAction.
A Usenthe
c. -t ForkJoinPool to invoke the ForkJoinPool.
7. n o
Run the ForkJoinFindMax project by right-clicking the project and choosing Run.
Note: If you have a multi-CPU system you can use System.currentTimeMillis() to
benchmark the sequential and Fork-Join solutions.

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

Practices for Lesson 13: Concurrency


Chapter 13 - Page 6
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson o m
c uideฺ
14:
i l ฺ
Building Database
g ma nt G
Applications
i 0 8 @ with
t u deJDBC
t p u14r his S
a l sa se t
Chapter

a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 1
CETPA Infotech Pvt Ltd

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© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 2
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

script, and write an application to read the contents of an employee database table and print the
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
Window/Page Description Choices or Values
a
)h ฺ
o m
Database Name EmployeeDB
a ilฺc Guide
User Name public
@ gm ent
Password tiger
r i 0 8 Stud
tiger atp
u his
Confirm Password
l s e t
f. Click OK a
ch to u s
a n e
g. Right-click the connection
r i (athat eyounscreated:
pu le lic
jdbc:derby://localhost:1527/EmployeeDB[public
Connect. Sat
on PUBLIC]and select

a l > Openr a b
h. Select h
nc ransf
File e File.
a
i.A Browse
o
willn -t to D:\labs\resources and open the EmployeeTable.sql script. The file
open in a SQL Execute window.
n
j. 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 3
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

b. The syntax for adding a row in a SQL database is:


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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 4
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

script, and write an application to read the contents of an employee database table and print the
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
Window/Page Description Choices or Values
a
)h ฺ
o m
Database Name EmployeeDB
a ilฺc Guide
User Name public
@ gm ent
Password tiger
r i 0 8 Stud
tiger atp
u his
Confirm Password
l s e t
f. Click OK. a
ch to u s
a n e
g. Right-click the connection
r i (athat eyounscreated:
pu le lic
jdbc:derby://localhost:1527/EmployeeDB[public
Connect. Sat
on PUBLIC]and select

a l > Openr a b
h. Select h
nc ransf
File e File.
a
i.A Browse
o
willn -t to D:\labs\resources and open the EmployeeTable.sql script. The file
open in a SQL Execute window.
n
j. 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 5
CETPA Infotech Pvt Ltd

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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

d. Select “Open as Main Project.”


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>, o m
c <column e2ฺ
value>, ...) i l
a t Guฺ i d
g m
c. Use the Statement executeUpdate method to execute the query.
8 @ u d etonWhat is the return
type for this method? What value should the return
u r i0 s St
type be? Test make sure that the
value of the return is correct.
s a tp thi
d. Your code may look like this:
c h al use
query = "INSERT INTOaEmployee
a n e toVALUES (200, 'Bill',
'Murray','1950-09-21',r i ( e n s
150000)";
u
tp le lic
S a
if (stmt.executeUpdate(query)
b
!= 1) {

c h al fera
System.out.println ("Failed to add a new employee record");

A a}n trans
Note: Ifn - run the application again, it will throw an exception, because this key already
you
noin the database.
exists

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 6
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

renamed to EmployeeDAOJDBC. You will need to create an EmployeeDAOJDBCImpl class to


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
EmployeeTestInteractive. This class contains the main method and provides a
s a
console-based user interface. Through this UI, you will be able to create new records,
)h ฺa
read all the records, update a record, and delete a record from the Employee
o m
(DAO). a ilฺc Guide
database. Note how the main method creates an instance of a Data Access Object

@ gm class. e n t
b. In the com.example.model package, look at the Employee
i 0 8 t u d a single
This class is a
Plain Old Java Object (POJO) that encapsulates
p u r there iare
all of the
s Sno set methods in this
data from employee
record and row in the Employee table. Note
s a t that
t h class,
only get methods. Once an Employee
c h al objectuisscreated,
e it cannot be changed. It is
immutable.
a a n e to
i
c. Expand the com.example.dao
r ( e n s
package. Look at the EmployeeDAO class and you
see the methodst p u
that an l i c
implementation of this interface is expected to implement.
l a
S rab
Each of these methods l e
throws a DAOException. Note that this interface extends
a
nch rawithnsAutoCloseable.
feTherefore, you will need to provide a close() method to satisfy the
AutoCloseable.
a contract
A n-t
o at the EmployeeDAOFactory. You see that this class has one method,
d. Look
ngetFactory(), 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 7
CETPA Infotech Pvt Ltd

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© 2014, 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
provided all the method signatures based on the EmployeeDAO interface declarations.
s a
e. Your next task is to add a constructor and fill in the bodies of the methods.
) h a
4. Add a private instance variable, con, to hold a Connection object instance. m
co uideฺ
i l ฺ
5. Write a package-level constructor for the class. The constructorm fora
this classG will create an
instance of a Connection object that the methods of this@ g e
class can reuse n tduring the
8 u d
p u ri0 is St
lifetime of the application. Be sure to catch a SQLException.
6. Write a method body for the add method. The
l s atadd methode th creates a new record in the
database from the Employee object passed
command to create a new record n
inc hadatabase
the t o uis:sa parameter.
in as Recall that the SQL

( a a s e INSERT INTO <table> VALUES


(...).
p u ri licen
Note: Use single a t forlthe
quotes e strings and the date.
S b
alany SQLException
ra
a. Rethrow
n c h s f e caught as a DAOException.
7. Aa a nmethod
Write
- t ranbody for the findById method. This method is used by the update and
no methods and is used to locate a single record to display. Recall that the SQL
delete
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>.

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 8
CETPA Infotech Pvt Ltd

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>.
a. Rethrow any SQLException caught as a DAOException.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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
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
s a
the Libraries for the project.
)h ฺ a
m
a. Right-click the Libraries folder in the project and select Add Jar/Folder.
a i l ฺco uide
b. Browse to D:\Program Files\Java\jdk1.7.0\db\lib.
g m nt G
c. Select derbyclient.jar.
0 8 @ tude
i
ur his S
d. Absolute Path should be checked. t p
e. Click Open. a l sa se t
a ch no errors,
nhave t o u
15. Save the updated class, and a
i ( if you
n s eallows youcompile and run the project. This

p u r lice
application has an interactive feature that to query the database and read one or
a t an employee
all of the records, find
l e by ID, and update and delete an employee record.
S
al fera b
n c h s
Aa n-tran
no

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 9
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

renamed to EmployeeDAOJDBC. You will need to create an EmployeeDAOJDBCImpl class to


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
EmployeeTestInteractive. This class contains the main method and provides a
s a
a
console-based user interface. Through this UI, you will be able to create new records,
)h ฺ
read all the records, update a record, and delete a record from the Employee
o m
(DAO). a ilฺc Guide
database. Note how the main method creates an instance of a Data Access Object

@ gm class. e n t
b. In the com.example.model package, look at the Employee
i 0 8 t u d a singleclass
This is a
Plain Old Java Object (POJO) that encapsulates
record and row in the Employee table. Note t p ur therehiare
that
all the
s Sno set methods in this class,
data from employee

l a is created,
sobject e t it cannot be changed. It is
only get methods. Once an Employee
immutable.
a
ch to u s
a n
i
c. Expand the com.example.dao
r se Look at the EmployeeDAO class and you
(a enpackage.
see the methodst u an implementation
pthat lic of this interface is expected to implement.
l a
S rab
Each of these methods l e
throws a DAOException. Note that this interface extends
a
nch rawithnsAutoCloseable.
fetherefore, you will need to provide a close() method to satisfy the
AutoCloseable;
a contract
A n-t
o at the EmployeeDAOFactory. You see that this class has one method,
d. Look
ngetFactory(), 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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 10
CETPA Infotech Pvt Ltd

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© 2014, 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.
e. Your next task is to add a constructor and fill in the bodies of the methods. s a
4. Add a private instance variable, con, to hold a Connection object instance. ) h
a
c o m eฺ
private Connection con = null;
a il Guid

5. mcreatenant instance of a
Write a constructor for the class. The constructor for this classgwill
Connection object that the methods of this class can reuse
i 0 8 @ during
t u dthee lifetime of the
application.
t p ur his S
l sa access.
a. Write the constructor to use package-level e tThis will enable only classes within
the package to create an instance a
chof thistoclasss
u (like the EmployeeDAOFactory).
a n
EmployeeDAOJDBCImpl()
r i (a {ense
b. Open the connection
t p u usinglthe
ic JDBC URL, name, and password from the
a e
S rablapplication:
SimpleJDBCExample
l
a
ch url f=e"jdbc:derby://localhost:1527/EmployeeDB";
a n
String
n s
A Stringn - trausername = "public";
o
nString 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);
}

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 11
CETPA Infotech Pvt Ltd

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
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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:
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()) + "'," a
)h ฺ
o m
ilฺc Guide
+ emp.getSalary() + ")";
Note the use of single quotes for the strings and the date. a
d. Since you are not expecting a result from the query, the @ gm enStatement
appropriate
t
method to use is updateQuery. Make sure to rtest i 0 ud the statement class
8to seeSwhether
t
executed properly by looking at the integertp u of htheismethod. For example:
result
a l s != 1)se{ t
a
if (stmt.executeUpdate(query)
a n ch to u adding employee");
r i (a ense
throw new DAOException("Error

tptryublock, lic
}
of a
e. At the end S the l e catch any SQLException thrown, and wrap them in the
h a l etorabebhandled by the calling application. For example:
sf
DAOException
a nc r(SQLException
a n
A n-t
catch se) {

n}o throw new DAOException("Error adding employee in DAO", se);


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.

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 12
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

as a new Employee object:


if (!rs.next()) {
return null;
}
return (new Employee(rs.getInt("ID"),
rs.getString("FIRSTNAME"),
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
s a
DAOException to be handled by the calling application. For example
) h a
catch (SQLException se) {
c m
o ideฺ
i
a inl ฺ u se);
throw new DAOException("Error finding employee
g m t GDAO",
}
8 @ u d en
8. Write a method body for the update method. The update
p u St updates an existing
ri0 ismethod
record in the database from the Employee object
s t passed
adatabase th"UPDATE
in as a parameter. Recall that the
SQL command to create a new record in
h a l
the
u s e is: <table> SET
COLUMNNAME=<value>, COLUMNNAME=<value>, c
an se to ... WHERE <pk>=<value>".
( a
ri quotes n string and date values.
Note: Be sure to add single
t p u l i c e
around
a. Delete the S
l a
boiler-plate
b le created by NetBeans for the update method.
code
haan instance
f a
er of a Statement object in a try-with-resources block:
n c
b. Create
s
tran
Aatryn-(Statement stmt = con.createStatement()) {
n o
}
c. Inside the try block, create the SQL UPDATE query from the Employee object passed
in:
String query = "UPDATE EMPLOYEE "
+ "SET FIRSTNAME='" + emp.getFirstName() + "',"
+ "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:

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 13
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

catch (SQLException se) {


throw new DAOException("Error updating employee in DAO",
se);
}
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.
b. Call the findById method with the id passed in as a parameter and if the record
s a
returned is null, throw a new DAOException.
) h a
Employee emp = findById(id); o m
c uideฺ
if (emp == null) { i
a tGl ฺ
throw new DAOException("Employee id: "g+mid + n
@ d e " does not
exist to delete.");
u r i08 s Stu
}
s a tp thi
c. Create an instance of a Statement
h l inusa etry-with-resources block:
aobject
try (Statement stmt a
c to
= ncon.createStatement())
i ( a n s e {

p u r lice
} t
a ble
l S
a try block, racreate the SQL DELETE query and test the result returned to
c h
d. Inside the f e
n sure
Aamake t r a na ssingle record was altered – throw a new DAOException if not:
on- query = "DELETE FROM EMPLOYEE WHERE ID=" + id;
nString
if (stmt.executeUpdate(query) != 1) {
throw new DAOException("Error deleting 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 deleting employee in DAO",
se);
}

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 14
CETPA Infotech Pvt Ltd

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© 2014, 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
ResultSet and add each record to the ArrayList. In the return statement, use the
toArray method to convert the collection to an array:
s a
ArrayList<Employee> emps = new ArrayList<>();
)h ฺa
while (rs.next()) {
o m
emps.add(new Employee(rs.getInt("ID"),
a ilฺc Guide
rs.getString("FIRSTNAME"),
@ gm ent
rs.getString("LASTNAME"),
r i 0 8 Stud
rs.getDate("BIRTHDATE"),
a t pu this
h a ls use
rs.getFloat("SALARY")));
}
a n c to
a
return emps.toArray(new Employee[0]);
(
i catch s e
nany SQLException thrown, and wrap them in the
e. At the end of the try
p u rblock, l i c e
a t to be handled
le by the calling application. For example:
DAOException
l S a b
c
catch
n ha(SQLException
s f er se) {
a
A se); r
throw
t a n new DAOException("Error getting all employees in DAO",
-
n}on
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);
}

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 15
CETPA Infotech Pvt Ltd

12. Save the class. Fix any missing imports and compilation errors if you have not already.
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

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.
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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 14: Building Database Applications with JDBC


Chapter 14 - Page 16
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
Practices for Lesson o m
c uideฺ
15:
i l ฺ
Localization ma t G
g
@ tude n
i 0 8
t p ur his S
Chapter 15

a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 15: Localization


Chapter 15 - Page 1
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

indicated in the instructions.

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 15: Localization


Chapter 15 - Page 2
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Chinese, and Russian.

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
• Short date s a
)h ฺa
• Full date
o m
• Full time a ilฺc Guide
• Day of the week @ gm ent
r i 0 8 Stud
• And a custom day and time that displays: day of
t p u his long date, era, time, and time
the week,
zone
a l sa se t
a nchthis
Localize the application so that it displays u in Simplified Chinese and Russian.
information
t o
The user should be able to switcha
r i ( ense
between the languages.

pu leis shown
The application output in English
a t lic here.
=== Date
a l SApp ===
r a b
n h
c nsf
Default Datee is: Aug 1, 2011
a
A Long ra is: August 1, 2011
tDate
n -
o Date is: 8/1/11
nShort
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 3
CETPA Infotech Pvt Ltd

Tasks
Open the Localized-Practice01 project in NetBeans and make the following changes:
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

practices directory.
3. Add code to display the specified date formats (indicated with comments) and localized
text.
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
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 15: Localization


Chapter 15 - Page 4
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

Chinese, and Russian.

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
• Short date s a
)h ฺa
• Full date
o m
• Full time a ilฺc Guide
• Day of the week @ gm ent
r i 0 8 Stud
• And a custom day and time that displays: day of
t p u his long date, era, time, and time
the week,
zone
a l sa se t
a nchthis
Localize the application so that it displays u in Simplified Chinese and Russian.
information
t o
The user should be able to switcha
r i ( ense
between languages.

pu leis shown
The application output in English
a t lic here.
=== Date
a l SApp ===
r a b
n h
c nsf
Default Datee is: Aug 1, 2011
a
A Long ra is: August 1, 2011
tDate
n -
o Date is: 8/1/11
nShort
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 © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 5
CETPA Infotech Pvt Ltd

Tasks
Open the Localized-Practice01 project in NetBeans and make the following changes:
1. Edit the DateApplication.java file.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

2. Open the MessagesText.txt file found in the practices directory for this practice in a
text editor.
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.
s a
 Click Select Folder.
) h a
 Click Finish. o m
c uideฺ
i l ฺ
 Paste the localized Russian text into the file and save it.
g ma nt G
4. @ tude
Create a message bundle file for Simplified Chinese text8named
0
MessagesBundle_zh_CN.properties. i
ur his S
t p
a > Other t > Properties File.
 Right-click the project and select New >
a l sOther s e
 Click Next.
a n ch to u
 Enter MessagesBundle_zh_CN i (a eninsthe e File Name field.
u r lic
 Click Finish. atp l e
 Paste h a
the
l S erSimplified
localized a b Chinese text into the file and save it.
a ncthe code
a n sthatf sets the locale based on user input.
5. A n-tr
Update

no public void setEnglish(){


currentLocale = Locale.US;
messages = ResourceBundle.getBundle("MessagesBundle",
currentLocale);
}

public void setFrench(){


currentLocale = Locale.FRANCE;
messages = ResourceBundle.getBundle("MessagesBundle",
currentLocale);
}

public void setChinese(){


currentLocale = Locale.SIMPLIFIED_CHINESE;
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Localization


Chapter 15 - Page 6
CETPA Infotech Pvt Ltd

messages = ResourceBundle.getBundle("MessagesBundle",
currentLocale);
}

public void setRussian(){


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

currentLocale = ruLocale;
this.messages =
ResourceBundle.getBundle("MessagesBundle", currentLocale);
}
6. Add the code that displays the date information to the printMenu method.
df = DateFormat.getDateInstance(DateFormat.DEFAULT,
currentLocale);
pw.println(messages.getString("date1") + " " +
df.format(today));
df = DateFormat.getDateInstance(DateFormat.LONG,
currentLocale);
s a
pw.println(messages.getString("date2") + " " +
) h a
df.format(today));
o m
c uideฺ
i l ฺ
df = DateFormat.getDateInstance(DateFormat.SHORT,
currentLocale);
g ma nt G
8 @ tude
pw.println(messages.getString("date3") + " " +
0
df.format(today)); i
ur his S
t p
currentLocale); a l sa se t
df = DateFormat.getDateInstance(DateFormat.FULL,

a n ch to u
pw.println(messages.getString("date4") + " " +
i (a ense
df.format(today));
r
tpu le lic
df = DateFormat.getTimeInstance(DateFormat.FULL,
a
h a l S erab
currentLocale);

a nc ransf pw.println(messages.getString("date5") + " " +


df.format(today));
A n-t
no
sdf = new SimpleDateFormat("EEEE", currentLocale);
pw.println(messages.getString("date6") + " " +
sdf.format(today));
sdf = new SimpleDateFormat("EEEE MMMM d, y G kk:mm:ss
zzzz", currentLocale);
pw.println(messages.getString("date7") + " " +
sdf.format(today));
7. Run the DateApplication.java file and verify that it operates as described.

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

Practices for Lesson 15: Localization


Chapter 15 - Page 7
CETPA Infotech Pvt Ltd

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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

“Building Database Applications with JDBC” lesson.

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 a
user should be able to switch between languages. a s
m )h ฺ
Tasks
a i lฺco uide
You have a couple of project choices in this lab. First you can use the
g m t
project files
n Gfrom Lesson
14, Practice 2, “Using the Data Access Object Pattern,” and just
8 @continue u e that project.
with
dfollowing
Alternatively, open the Practice02 project for this lesson.
u i 0Perform
r is S t
the steps:
1. Open the EmployeeTestInteractive.java
p
at file.eExamine
th the source code and
determine which messages printed toh
l s
a consoleushould
s be converted into resource
bundles. Notice that not all text a n
outputc the t o
is included in this class file.
(a ensmessages e
Note: You do not haveu toriinclude error
t p l i cincluded. in the bundle. Only prompt and
l S a ble
informational messages should be
a to the
2. A slight change
h f e a interface is required.
ruser
c
n ramain s
Aa n-the
Currently
t n interface looks like this:
n o
[C]reate | [R]ead | [U]pdate | [D]elete | [L]ist | [Q]uit:
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.

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

Practices for Lesson 15: Localization


Chapter 15 - Page 8
CETPA Infotech Pvt Ltd

5. Examine all the date-related source code. Make sure that date information will print in the
appropriate localized format.
6. When you have finished, run EmployeeTestInteractive.java and make sure that all
the menus have been localized.
7. Additional improvements you could make:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

• Localize all the error messages in the application.


• Localize the single character options for the main menu.

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 15: Localization


Chapter 15 - Page 9
CETPA Infotech Pvt Ltd
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
m
c uideฺ
o
i l ฺ
g ma nt G
0 8 @ tude
i
ur his S
t p
a l sa se t
a n ch to u
r i (a ense
a tpu le lic
h a l S erab
a nc ransf
A n-t
no

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

Practices for Lesson 15: Localization


Chapter 15 - Page 10

You might also like