Java SE 7 Programming Practice
Java SE 7 Programming Practice
Java SE 7 Programming Practice
s a
) h a
c o m e ฺ
ฺ i d
Java SE 7 Programming r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis Guide
e t his
x a nd us
Activity
a l e e to
t e ( ns
a
tr le li c e
I s
n d ra erab
x a n s f
e
Al n-tra
no
D67238GC20
Edition 2.0
November 2011
D74998
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Disclaimer
This document contains proprietary information and is protected by copyright and other intellectual property laws. You may copy and
print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way.
Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization
of Oracle.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
The information contained in this document is subject to change without notice. If you find any problems in the document, please
report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.
If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United
States Government, the following notice is applicable:
Trademark Notice s a
) h a
owners.
c o m
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
e ฺ
ฺ i d
r a cle t Gu
Authors
@ o e n
t e tu d
Michael Williams, Tom McGinn, Matt Heimer
t r a S
Technical Contributors and Reviewers dra
ฺis this
n u s e
a
Lee Klement, Steve Watts, Brian Earl,xVasily Strelnikov
to Goetz,, Andy Smith, Nancy K.A.N, Chris
Lamb, Todd Lowry, Ionut Radu (, a leDarcy,seBrian
Joe Alan Bateman, David Holmes
t r a te licen
r a Is rusing:
This book wasdpublished a bleOracle Tutor
e x an nsfe
Al n-tra
no
Table of Contents
Practices for Lesson 1 .............................................................................................................................. 1-1
Practices for Lesson 1: Overview............................................................................................................. 1-3
Practice 1-1: Verifying Software Installation ............................................................................................. 1-4
Practice 1-2: Software Installation............................................................................................................ 1-6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
r a t e Stud
Practices for Lesson 5: Advanced Class Design ..................................................................................... 5-1
t is
ฺis..................................................................
Practices for Lesson 5: Overview............................................................................................................. 5-3
Practice 5-1: Summary Level: Applying the Abstract Keyword r a t h 5-4
Practice 5-1: Detailed Level: Applying the Abstract a n se
dKeywordu.................................................................... 5-8
e x
l Singleton t o
Practice 5-2: Summary Level: Applying
( athethe n s eDesign
Design Pattern ....................................................... 5-13
r e
t Enumerations
Practice 5-2: Detailed Level: Applying
aJava i ce ....................................................................................
Singleton Pattern ......................................................... 5-15
(Optional) Practice 5-3:s
I t
Using
l e l 5-17
n dra5-4:
(Optional) Practice
(Optional)aSolution f e rab Nested
Recognizing Classes ............................................................................... 5-19
l e xfor Lesson a n s
5-4: Recognizing Nested Classes ............................................................................... 5-20
A
Practices
n - t r 6: Inheritance with Java Interfaces ........................................................................ 6-1
Practice 8-3: Summary Level: Transforming HTML by Using Regular Expressions .................................... 8-12
Practice 8-3: Detailed Level: Transforming HTML by Using Regular Expressions ...................................... 8-14
Practices for Lesson 9: Exceptions and Assertions ................................................................................ 9-1
Practices for Lesson 9: Overview............................................................................................................. 9-3
Practice 9-1: Summary Level: Catching Exceptions.................................................................................. 9-4
Practice 9-1: Detailed Level: Catching Exceptions .................................................................................... 9-7
Practice 9-2: Summary Level: Extending Exception.................................................................................. 9-10
Practice 9-2: Detailed Level: Extending Exception .................................................................................... 9-14
Practices for Lesson 10: Java I/O Fundamentals ..................................................................................... 10-1
Practices for Lesson 10: Overview ........................................................................................................... 10-3
s a
Practice 10-1: Summary Level: Writing a Simple Console I/O Application.................................................. 10-4
)h a
m
o ideฺ
Practice 10-1: Detailed Level: Writing a Simple Console I/O Application.................................................... 10-6
c
ฺ
cle t Gu
Practice 10-2: Summary Level: Serializing and Deserializing a ShoppingCart ........................................... 10-9
r a
Practice 10-2: Detailed Level: Serializing and Deserializing a ShoppingCart.............................................. 10-12
o n
@ d e
Practices for Lesson 11: Java File I/O (NIO.2) ..........................................................................................
e u 11-1
a t S t
tr...............................................................
Practices for Lesson 11: Overview ........................................................................................................... 11-3
ฺ i s t h i s
Practice 11-1: Summary Level: Writing a File Merge Application
Practice 11-1: Detail Level: Writing a File Merge n d ra .....................................................................
Application s e
11-4
11-7
Practice 11-2: Summary Level: RecursiveeCopy x t o u
a....................................................................................... 11-11
( a
Practice 11-2: Detailed Level: Recursive
lCopy .........................................................................................
s e
a t e c e nPathMatcher to Recursively Delete ................................. 11-13
I
(Optional) Practice 11-3:s tr le liUsing PathMatcher to Recursively Delete ................................... 11-18
(Optional) Practice 11-3: Summary Level:
Detailed Level:
Using 11-16
Practices for n d
Lesson f e rab ......................................................................................................... 12-1
ra12: Threading
l e xafor Lesson
Practices
r a n s
12: Overview ........................................................................................................... 12-3
A 12-1:
Practice
o n -tSummary Level: Synchronizing Access to Shared Data...................................................... 12-4
n 12-1: Detailed Level: Synchronizing Access to Shared Data........................................................ 12-7
Practice
Practice 12-2: Summary Level: Implementing a Multithreaded Program .................................................... 12-11
Practice 12-2: Detailed Level: Implementing a Multithreaded Program ...................................................... 12-13
Practices for Lesson 13: Concurrency ..................................................................................................... 13-1
Practices for Lesson 13: Overview ........................................................................................................... 13-3
(Optional) Practice 13-1: Using the java.util.concurrent Package .............................................................. 13-4
(Optional) Practice 13-2: Using the Fork-Join Framework ......................................................................... 13-6
Practices for Lesson 14: Building Database Applications with JDBC ..................................................... 14-1
Practices for Lesson 14: Overview ........................................................................................................... 14-3
Practice 14-1: Summary Level: Working with the Derby Database and JDBC............................................ 14-4
Practice 14-1: Detailed Level: Working with the Derby Database and JDBC.............................................. 14-6
Practice 14-2: Summary Level: Using the Data Access Object Pattern...................................................... 14-8
Practice 14-2: Detailed Level: Using the Data Access Object Pattern........................................................ 14-11
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G1u
Lesson
@ o e n
t e tu d
t
Chapter r a
1 S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
These practices cover configuring a development environment for Java SE 7. These practices
should not be performed unless directed to do so by your instructor.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will verify the installation of the necessary software to perform Java 7
software development. If verification fails, you will proceed with the remaining practices.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
Your instructor has instructed you to perform these steps.
Summary
You have been given a computer system that will be used for Java SE 7 software development.
You must validate that the Java 7 SE Development Kit is installed, the NetBeans 7.0.1 IDE is
installed, and the NetBeans IDE is correctly configured to use JDK 7.
Tasks
1. Open a command or terminal window. s a
Note: If you are using Windows, you can open a command window by performing the)h a
following steps: c m
o ideฺ
ฺ
a. Click the Start button.
r a cle t Gu
b. Click Run.
@ o e n
t e tu d
t r a
c. Type cmd in the Run dialog box and click the OK button. S
2. ฺis this
Execute the java -version command. This verifies that a JRE is installed; this does not
r a
verify that the JDK is installed.
a n d use
l e x to
a. Verify that the output of the java -version command matches the following
( a ns e
example output. For 64-bit machines, the output should be:
a t e c e
I
java version s tr "1.7.0"
l e li
d
Java(TM)
n f ab Environment (build 1.7.0-b147)
ra SEerRuntime
e a HotSpot(TM)
xJava n s 64-Bit Server VM (build 21.0-b17, mixed mode)
l
A For r a
t machines, the output should be:
-32-bit
o n
n java version "1.7.0"
Java(TM) SE Runtime Environment (build 1.7.0-b147)
Java HotSpot(TM) Client VM (build 21.0-b17, mixed mode, sharing)
b. If a different version number or an error message is displayed, you may have one of
the following possible problems:
The JRE/JDK is not installed.
The java command is not in your path.
The wrong JRE/JDK version is installed.
Multiple JREs/JDKs are installed.
Note: To exclude an incorrect PATH environment variable as the reason for an
incorrect or unrecognized Java version, you may attempt to locate the path to your JDK
and execute java -version by using a fully qualified path. For example:
"C:\Program Files\Java\jdk1.7.0\bin\java.exe" -version
3. Execute the javac -version command. This verifies that a JDK is installed.
Overview
In this practice, you will install the software needed to perform Java 7 SE development.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Summary
You have been given a computer system that will be used for Java SE 7 software development.
You will use the information obtained in the previous practice to determine the software to be
installed, and then you will install the software.
A JDK and NetBeans cobundle is available that will reduce the number of files to download.
Downloading the JDK and NetBeans separately provides greater flexibility for selecting the JDK
to be used (32-bit or 64-bit) and reduces the required amount of data to download if either the
JDK or NetBeans is already installed. s a
For more information about Oracle JDK 7 supported operating systems, go to )h a
m
o ideฺ
http://www.oracle.com/technetwork/java/javase/config-417990.html. Java 7 support for
c
ฺ
additional operating systems may be available from other channels.
r a cle t Gu
Tasks @ o e n
t e tu d
1. Obtain the required software. t r a S
a. If you require both the JDK and NetBeans,r a e hismethod is to download the “JDK
ฺisthe easiest
t
7 with NetBeans 7.0.1” cobundle.
x a nd us
1) Using a web browser, a l go to e t
e o
t e ( ns
http://www.oracle.com/technetwork/java/javase/downloads/index.html.
a
trJava SE li c e
2) LocateIthe
a s b l e Development Kit (JDK) Cobundles table.
3) Click
n r e ra button for “JDK 7 with NetBeans 7.0.1.”
d thefDownload
a
x4) You s
tran the software.
must accept the JDK 7 and NetBeans 7.0.1 Cobundle License Agreement to
Ale n-download
no5) Download the file for your operating system. As of this writing, Linux, Solaris, and
Windows downloads are available.
b. If you require just the JDK, download the Java SE 7 JDK.
1) Using a web browser, go to
http://www.oracle.com/technetwork/java/javase/downloads/index.html.
2) Locate the Java Platform, Standard Edition table.
3) Click the Download button for Java SE 7 JDK.
Note: Be sure to download the JDK and not the JRE.
4) You must accept the JDK 7 and NetBeans 7.0.1 Cobundle License Agreement to
download the software.
5) Download the file for your operating system. As of this writing, Linux, Solaris, and
Windows downloads are available.
c. If you require just the NetBeans IDE, download “NetBeans IDE 7.0.1 for Java SE.”
1) Using a web browser, go to http://download.netbeans.org/netbeans/7.0.1/final/.
2) Click the Download button for Java SE.
3) If the download does not start automatically, click the “download it here” link.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
If you have multiple JDK versions installed, be sure to select the Java SE 7 JDK if
prompted while installing NetBeans.
If NetBeans 7.0.1 was installed before JDK 7 or an older version of the JDK was
selected during NetBeans installation, perform practice 1-3 to reconfigure NetBeans
to use JDK 7.
3. Verify the software installation.
Repeat practice 1-1 to verify software installation.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will configure NetBeans 7.0.1 to use a locally installed instance of JDK 7.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Summary
These steps are required only if both NetBeans 7.0.1 and JDK 7 are installed but NetBeans is
running with the wrong JDK. You can verify the JDK being used by NetBeans with the steps
outlined in practice 1-1, step 4. Failure to correct the NetBeans configuration to use JDK 7 will
result in an inability to create Java projects that use Java 7 language features.
Tasks
1. Configure NetBeans to be aware of the Java 7 Platform. s a
a. In the NetBeans IDE, select Tools, and then Java Platforms from the Main menu.)h a
c m
o ideฺ
b. Click the Add Platform button and specify the directory that contains your JDK 7
ฺ
installation.
r a cle t Gu
o n
c. In the Platform Name step, verify that the default locations of the Platform Sources zip
@ e
file and API documentation are valid. t e tu d
t r a S
r a ฺis this
d. Click the Finish button to close the Add Java Platform dialog box.
a n d use
e. Ensure that JDK 1.7 is selected in the Platforms list and click Close.
2. e x to
Configure NetBeans to start with Java SE 7 JDK.
l
( a ns e
a. Open the directory containing the NetBeans configuration files, typically: C:\Program
a t e c e
I s tr le li
Files\NetBeans 7.0.1\etc\.
n d ra erab
b. Use a text editor to edit the netbeans.conf file.
c. Modify
x f
a thensnetbeans_jdkhome property to have a value of the JDK 7 installation
l e -t r
location,a for example:
A Files\Java\jdk1.7.0". netbeans_jdkhome="C:\Program
n o n
3. Restart NetBeans and verify the JDK being used by NetBeans with the steps outlined in
practice 1-1, step 4.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G2:u Java
Lesson
@ o e n
Syntax e
t and S
Class d
tu Review
t r a
r a ฺis 2 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you will use the NetBeans IDE and create a project, create packages, and a
Java main class, and then add classes and subclasses. You will also run your project from
within the IDE and learn how to pass command-line arguments to your main class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Note: There are two levels of practice for most of the practices in this course. Practices that are
marked “Detailed Level” provide more instructions and, as the name implies, at a more detailed
level. Practices that are marked “Summary Level” provide less detail, and likely will require
additional review of the student guide materials to complete. The end state of the “Detailed” and
“Summary” level practices is the same, so you can also use the solution end state as a tool to
guide your experience.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, using the NetBeans IDE, you will create an Employee class, create a class with
a main method to test the Employee class, compile and run your application, and print the
results to the command line output.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Tasks
1. Start the NetBeans IDE by using the icon from Desktop.
2. Create a new project EmployeePractice in the D:\labs\02-Review\practices
directory with an EmployeeTest main class in the com.example package.
3. Set the Source/Binary format to JDK 7.
a. Right-click the project and select Properties.
b. Select JDK 7 from the drop-down list for Source/Binary Format.
c. Click OK. s a
4. Create another package called com.example.domain. )h a
c m
o ideฺ
5. Add a Java Class called Employee in the com.example.domain package. ฺ
6. Code the Employee class. r a cle t Gu
@ o e n
t e tu d
a. Add the following data fields to the Employee class—use your judgment as to what
r a S
you want to call these fields in the class. Refer to the lesson materials for ideas on the
t
r a ฺis this
field names and the syntax if you are not sure. Use public as the access modifier.
n e
d usRecommended
Field use
e x a t o field type
Employee id
e ( al nseint
Employee name tra
t lice String
s
a I Security b e
lNumber
r
EmployeedSocial
n e r a String
a s f
A lex -trsalary
Employee an double
c. In the body of the main method, use the System.out.println method to write the
value of the employee fields to the console output.
d. Resolve any missing import statements.
e. Save the EmployeeTest class.
s a
10. Run the EmployeePractice project. ) h a
11. (Optional) Add some additional employee instances to your test class. com e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, using the NetBeans IDE, you will create an Employee class, create a class with
a main method to test the Employee class, compile and run your application, and print the
results to the command-line output.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Tasks
1. Start the NetBeans IDE by using the icon from Desktop.
2. Create a new Project called EmployeePractice in NetBeans with an EmployeeTest
class and a main method.
a. Click File > New Project.
b. Select Java from Categories, and Java Application from Projects.
c. Click Next.
d. On the New Application screen, enter the following values: s a
) h a
Window/Page Description Choices or Values
c o m e ฺ
Project Name: EmployeePractice ฺ
le Gu i d
r a c t
Project Location o
D:\labs\02-Review\practices
@ e n
Use Dedicated Folder for Storing Deselected
r a t e Stud
Libraries
r a ฺist this
Create Main Class
a n dSelecteduse
l e x Changeto the name to
( a e
ns com.example.EmployeeTest –
a t e c e
I s tr le li com.example is the package name.
d
Set as Main
n raProjecterab Selected
a s f
lexClick-tFinish.
Ae.You r an
n notice that NetBeans has saved you a great deal of typing by creating a class
nowill
called EmployeeTest, including the package name of com.example, and writing the
skeleton of the main method for you.
3. Set the Source/Binary format to JDK 7.
a. Right-click the project and select Properties.
b. Select JDK 7 from the drop-down list for Source/Binary Format.
c. Click OK.
4. Create another package called com.example.domain.
a. Right-click the current package com.example under Source Packages.
b. Select New > Java Package. The New Java Package dialog box highlights the new
subpackage name.
c. Enter com.example.domain in the Package Name field, and click Finish.
You will notice that the icon beside the package name is gray in the Project—this is
because the package has no classes in it yet.
5. Create a new Java Class called Employee in the com.example.domain package.
a. Right-click the com.example.domain package and select New > Java Class.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
t r a t S tu
is the class the Java interpreter will execute. The next field is Arguments, which is used
r a ฺis this
for passing arguments to the main method. You will use arguments in a future lesson.
a n d use
d. Click Cancel to close the Project Properties.
9. Run the EmployeePractice project.
l e x to
( a ns e
a. To run your EmployeePractice project, right-click the project and select Run, or click
a t e c e
I s tr le li
the Run Main Project icon (the green triangle), or press F6.
n d ra erab
b. If your classes have no errors, your should see the following output in the Output
x awindow:
n s f
e
Al run: - tra
n
noEmployee id: 101
Employee name: Jane Smith
Employee Soc Sec #: 012-34-5678
Employee salary: 120345.27
BUILD SUCCESSFUL (total time: 1 second)
10. (Optional) Add some additional employee instances to your test class.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G3:u
Lesson
@ o e n
Encapsulation
t e d
tuand
t r a S
r a ฺis this
Subclassing
a n d use
l e x to 3
Chapter
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you will extend your existing Employee class to create new classes for
Engineers, Admins, Managers, and Directors.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will create subclasses of Employee, including Manager, Engineer, and
Administrative assistant (Admin). You will create a subclass of Manager called Director, and
create a test class with a main method to test your new classes.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
Use this Java class diagram to help guide this practice.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Tasks
1. Open the project EmployeePractice in the practices directory.
2. Apply encapsulation to the Employee class.
a. Make the fields of the Employee class private.
b. Replace the no-arg constructor in Employee with a constructor that takes empId,
name, ssn, and salary.
c. Remove all the setter methods except setName.
d. Add a method named raiseSalary with a parameter of type double called
increase to increment the salary.
e. Save Employee.java.
- t r an
AInletheNumberFormat.getCurrencyInstance().format((double)emp.getSalary()));
nonlesson on abstract classes, you will see how to use an abstract factory, such as
NumberFormat.getCurrencyInstance().
12. (Optional) Add additional business logic (data validation) to your Employee class.
a. Prevent a negative value for the raiseSalary method.
b. Prevent a null or empty value for the setName method.
Overview
In this practice, you will create subclasses of Employee, including Manager, Engineer, and
Administrative assistant (Admin). You will create a subclass of Manager called Director, and
create a test class with a main method to test your new classes
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
Use this Java class diagram to help guide this practice.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Tasks
1. Open the project EmployeePractice in the practices directory.
a. Select File > Open Project
b. Browse to D:\labs\03-Encapsulation\practices.
c. Select EmployeePractice.
d. Click Open Project.
2. Apply encapsulation to the Employee class.
a. Open the Employee class in the editor.
b. Make the fields of the Employee class private.
c. Replace the no-arg constructor in Employee with a constructor that takes empId,
name, ssn, and salary.
public Employee(int empId, String name, String ssn, double
salary) {
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Salary 120_567.36
Department Global Marketing
Budget 1_000_000.00
f. Save EmployeeTest and correct any syntax errors.
8. Add a printEmployee method to EmployeeTest.
a. Adding System.out.println methods after each of the instances you created is
going to create a lot of redundant code. Instead, you will use a method that takes an
s a
Employee object as the parameter:
)h a
public static void printEmployee (Employee emp) {
c m
o ideฺ
ฺ
System.out.println(); // Print a blank line as a
r a cle t Gu
separator
// Print out the data in this Employee object
@ o" + emp.getEmpId());
e n
System.out.println ("Employee id:
t e u d
System.out.println ("Employee name: t r a S" t+ emp.getName());
a ฺisSoc Secth#:is " + emp.getSsn());
System.out.println ("Employee
r
nd salary: e
System.out.println ("Employee
x a t o us " + emp.getSalary());
}
( e
al nse
r a e
Note that all the object tinstances e
i cthat you are creating are Employee objects, so
s
regardless of which t subclass
I cannot l e l
you create, the printEmployee method will work. However,
the Employee
d r a class r a b know about the specialization of its subclasses. You will see
n
a work around
howxto f e
s this in the next lesson.
l e t r a n
9. AUse the-printEmployee method to print out information about your classes. For example:
o n
n printEmployee (eng);
printEmployee(man);
printEmployee(adm);
printEmployee(dir);
10. (Optional) Use the raiseSalary and setName methods on some of your objects to make
sure those methods work. For example:
mgr.setName ("Barbara Johnson-Smythe");
mgr.raiseSalary(10_000.00);
printEmployee(mgr);
11. Save the EmployeeTest class and test your work.
NumberFormat.getCurrencyInstance().
13. (Optional) Add additional business logic (data validation) to your Employee class.
a. Prevent a negative value for the raiseSalary method.
b. Prevent a null or empty value for the setName method.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice you modify the Manager class to add an array of Employee objects (a staff) to
the manager class, and create methods to add and remove employees from the Manager.
Finally, add a method to Manager to print the staff names and IDs.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
Start with the completed project from Practice 3-1 (Summary or Detailed) or the solution from
the solutions\practice1 directory.
Tasks
1. Add fields to the Manager class to keep the employee objects.
a. Declare a private field called staff that is declared as an array of Employee objects .
b. You will need to keep track of the number of employees in staff, so create a private
s a
) h a
integer field employeeCount to keep a count of the number of employees. Initialize
the employee count with 0. m
ฺ c o d e ฺ
i
c. In the constructor, initialize the staff array with a maximum of 20 employees.
cle t Gu
2. r a
Add a method called findEmployee. This method scans the current staff Employee array
o n
@ d e
to see whether there is a match between the any member of staff and the Employee
e
passed in. t r a t S tu
a ฺis this
a. Return -1 if there is no match, and the index number of the Employee if there is a
r
match.
a n d use
3. l e x to
Add a method called addEmployee. This method adds the Employee passed in as a
( a ns e
a e
parameter to the end of the array.
t c e
s tr le li
a. This method should return a boolean value and take an Employee object as a
I
n d ra erab
parameter. The method should return true if the employee was successfully added and
x a n s f
false if the employee already exists as a member of staff.
e
Al n-tra
b. Call the findEmployee method to determine whether the Employee is a member of
no staff already. Return false if there is match.
c. Add the employee object to the staff array. (Hint: Use the employeeCount as the
index of the array element to assign the employee parameter to.)
d. Increment the employeeCount and return true.
4. Add a method called removeEmployee. This method is a bit more complicated. When you
remove an element from the array, you must shift the other elements of the array so there
are no empty elements. The easiest way to do this is to create a new array and assign a
copy of each of the staff elements to it except for the match. This effectively removes the
match from the array.
a. Declare a local boolean variable initialized to false to return as the status for the
method.
b. Declare a temporary array of Employee objects to copy the revised staff array to.
c. Declare an integer counter of the number of employees copied to the temporary array.
d. Use a for loop to go through the staff array and attempt to match the employee ID of
each element of the staff array with the employee ID of the Employee passed into the
method as a parameter.
temporary array, and the count of employees with the temporary counter from step c.
h. Return the local boolean variable.
5. Add a method called printStaffDetails. This method prints the name of the manager
and then each of the elements of staff in turn.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G4:u Java
Lesson
@ o e n
Class e
Design
t tu d
t r a S
r a ฺis 4 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you will override methods, including the toString method in the Object
class. You will also create a method in a class that uses the instanceof operator to determine
which object was passed to the method.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will override the toString method of the Object class in the Employee
class and in the Manager class. You will create an EmployeeStockPlan class with a
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
grantStock method that uses the instanceof operator to determine how much stock to
grant based on the employee type.
Assumptions
Tasks
1. Open the EmployeePractice project in the practices directory.
2. Edit the Employee class to override the toString() method from the Object class.
Object’s toString method returns a String.
s a
h a
a. Add a return statement that returns a string that includes the employee ID, name,
)
c o m
Social Security number, and a salary as a formatted string, with each line separated
e ฺ
with a newline character ("\n"). ฺ i d
b. To format the double salary, use the following: r a cle t Gu
@ o e n
t e
NumberFormat.getCurrencyInstance().format(getSalary())
tu d
c. Fix any missing import statements. t r a S
d. Save the class. r a ฺis this
a n d use
3.
l e x
Override the toString() method in the Manager class to include the deptName field
to
a e
value. Separate this string from the Employee string with a newline character.
( ns
a t e c e
Note the Green circle icon with the “o” in the center beside the method signature in the
I s tr le li
Manager class. This indicates that NetBeans is aware that this method overrides the
d ra erab
method from the parent class, Employee. Hold the cursor over the icon to read what this
n
x a s f
icon represents:
n
e
Al n-tra
no
Click the icon, and NetBeans will open the Employee class and position the view to the
toString() method.
4. (Optional) Override the toString() method in the Director class as well, to display all
the fields of a Director and the available budget.
Director 1000
Manager 100
All other Employees 10
a. Add a grantStock method that takes an Employee object reference as a parameter
and returns an integer
b. In the method body, determine what employee type was passed in using the
instanceof keyword and return the appropriate number of stock options based on
that type.
c. Resolve any missing import statements. s a
d. Save the EmployeeStockPlan class. )h a
6. Modify the EmployeeTest class. Replace the four print statements in the c m
o ideฺ
ฺ
r a cle t Gu
printEmployee method with a single print statement that uses the toString method
that you created.
@ o e n
7. t e
Overload the printEmployee method to take a second parameter, tu d
t r a S
r a ฺis this
EmployeeStockPlan, and print out the number of stock options that this employee will
receive.
a n d use
x to
a. Above the printEmployee method calls in the main method, create an instance of
l e
( a ns e
the EmployeeStockPlan and pass that instance to each of the printEmployee
methods. a t e c e
I s tr le li
b. The new printEmployee method should call the first printEmployee method and
n d ra erab
the number of stocks granted to this employee:
x a n s f
e - t a
Al System.out.println("Stock
r
printEmployee (emp);
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will override the toString method of the Object class in the Employee
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
class and in the Manager class. You will create an EmployeeStockPlan class with a
grantStock method that uses the instanceof operator to determine how much stock to
grant based on the employee type.
Assumptions
Tasks
1. Open the EmployeePractice project in the practices directory.
a. Select File > Open Project.
b. Browse to D:\labs\04-Class_Design\practices. s a
c. Select EmployeePractice and click Open Project. )h a
2. Edit the Employee class to override the toString() method from the c m
o idclass.
e ฺ
ฺ Object
Object's toString method returns a String.
r a cle t Gu
a. Add the toString method to the Employee class withothe following e n signature:
t e @ tu d
public String toString() {
t r a S
b. Add a return statement that returns a astring is the employee information:
ฺis thatthincludes
ID, name, Social Security number,
r e
ndand a formatted
s salary like this:
x a o u
return "Employee ID:
( a le s"e+t getEmpId() + "\n" +
"Employee
t r a te Name:
l i c en " + getName() + "\n" +
r a Is bleSSN: " + getSsn() + "\n" +
"Employee
n d "Employee
f e ra Salary: " +
a
x ran s
NumberFormat.getCurrencyInstance().format(getSalary());
Ac.le Save
n -t the Employee class.
o
n the toString method in the Manager class to include the deptName field value.
3. Override
a. Open the Manager class.
b. Add a toString method with the same signature as the Employee toString
method:
public String toString() {
The toString method in the Manager class overrides the toString method inherited
from the Employee class.
icon represents:
Click the icon, and NetBeans will open the Employee class and position the view to the
toString() method.
d. Save the Manager class. s a
4. (Optional) Override the toString method in the Director class as well, to display
a
) h all the
fields of a director and the available budget.
c m
o ideฺ
5. Create a new class called EmployeeStockPlan in the packagecle
ฺ u
com.example.business. This class will include a single method, o r a n t G which
e @ d e
grantStock,
takes an Employee object as a parameter and returns
based on the employee type: t r a t an
S tu
integer number of stock options
r a ฺis this
Employee Type
n d usNumber e of Stock Options
e x a to
Director
( a l s e 1000
Manager
t r a te licen 100
All other
a s
I Employees
b le 10
d r r a
an thensnew
a. Create
x fepackage and class in one step by right-clicking Source Package, and
e
Al then - ra New > Java Class.
tselecting
b. o n
n Enter EmployeeStockPlan as the Class Name and com.example.business as
the Package and click Finish.
c. In the new class, add fields to the class to define the stock levels, like this:
private final int employeeShares = 10;
private final int managerShares = 100;
private final int directorShares = 1000;
d. Add a grantStock method that takes an Employee object reference as a parameter
and returns an integer:
public int grantStock(Employee emp) {
return directorShares;
} else {
if (emp instanceof Manager) {
return managerShares;
} else {
return employeeShares;
}
}
f. Resolve any missing import statements.
s a
g. Save the EmployeeStockPlan class.
)h a
6. Modify the EmployeeTest class. Replace the four print statements in the
c m
o ideฺ
ฺ
that you created. r a cle t Gu
printEmployee method with a single print statement that uses the toString method
@ o e n
a. Replace these lines: t e tu d
t r a S
System.out.println("Employee id:
r a ฺis this + emp.getEmpId());
"
System.out.println("Employee
n d name:u s e " + emp.getName());
e x a toSoc Sec #: " + emp.getSsn());
( a l
System.out.println("Employee
e
a t e
System.out.println("Employee
c e ns salary: " +
I s tr le li
NumberFormat.getCurrencyInstance().format((double)
raline that
emp.getSalary()));
d b
rauses
b. With
x a n one
s f e the toString() method:
e tra n
Al System.out.println(emp);
n -
no the printEmployee method to take a second parameter,
7. Overload
EmployeeStockPlan, and print out the number of stock options that this employee will
receive.
a. Create another printEmployee method that takes an instance of the
EmployeeStockPlan class:
public static void printEmployee(Employee emp, EmployeeStockPlan
esp) {
b. This method first calls the original printEmployee method:
printEmployee(emp);
c. Add a print statement to print out the number of stock options that the employee is
entitled to:
System.out.println("Stock Options: " +
esp.grantStock(emp));
d. Above the printEmployee method calls in the main method, create an instance of
the EmployeeStockPlan and pass that instance to each of the printEmployee
methods:
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G5:u
Lesson
@ o e n
Advanced e
t Class d
tu Design
t r a S
r a ฺis 5 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you will use the abstract, final, and static Java keywords. You will also learn
to recognize nested classes.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will take an existing application and refactor the code to use the abstract
keyword.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the abstract class section of this lesson.
Summary
You have been given a project that implements the logic for a bank. The banking software
supports only the creation of time deposit accounts. Time deposit accounts allow withdraw only
after a maturity date. Time deposit accounts are also known as term deposit, certificate of
deposit (CD), or fixed deposit accounts. You will enhance the software to support checking
accounts.
A checking account and a time deposit account have some similarities and some differences. s a
)h a
Your class design should reflect this. Additional types of accounts might be added in the future.
c m
o ideฺ
ฺ
Tasks
1. Open the AbstractBanking project as the main project. ora
cle t Gu
@ d e n
a. Select File > Open Project.
r a t e S tu
t
ฺis this
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
r a
c. Select AbstractBanking and select
a n d u“Open
the se as Main Project” check box.
d. Click the Open Project button. l e x to
(
2. Expand the project directories.
a ns e
a t e c e
3. Run the project. s
I tr should
You
l e li a report of all customers and their accounts.
see
d a rab
4. Review therTimeDepositAccount class.
n f e
a thenTimeDepositAccount.java
a. xOpen s file (under the com.example package).
l e r a
-t the fields and method implementations of TimeDepositAccount that are
Ab. Identify
o n
n related to time or are in some other way specific to TimeDepositAccount. Add a
code comment if desired.
c. Identify the fields and method implementations of TimeDepositAccount that could
be used by any type of account. Add a code comment if desired.
5. Create a new Java class, Account, in the com.example package.
6. Code the Account class.
a. This class should be declared as abstract.
b. Move any fields and method implementations from TimeDepositAccount that could
be used by any type of account to the Account class.
Note: The fields and methods should be removed from TimeDepositAccount.
c. Add abstract methods to the Account class for any methods in
TimeDepositAccount that are time related but have a method signature that would
make sense in any type of account.
Hint: Would all accounts have a description?
d. Add an Account class constructor that has a double balance parameter.
c. Make sure that you are overriding the abstract withdraw and getDescription
methods inherited from the Account class.
Note: It is a good practice to add @Override to any method that should be overriding
a parent class method.
8. Modify the Customer and CustomerReport classes to use Account references.
a. Open the Customer.java file (under the com.example package).
b. Change all TimeDepositAccount references to Account type references.
c. Open the CustomerReport.java file (under the com.example package).
s a
d. Change all TimeDepositAccount references to Account type references.
) h a
9. Run the project. You should see a report of all customers and their accounts.
c o m e ฺ
ฺ i d
10. Create a new Java class, CheckingAccount, in the com.example package.
a. CheckingAccount should be a subclass of Account. r a cle t Gu
@ o e n
b. Add an overDraftLimit field to the CheckingAccount class.t e tu d
t r a S
private final double overDraftLimit;
r a ฺis this
c. Add a CheckingAccount constructor
a n d thatuhas setwo parameters.
double balance: Passle x value totothe parent class constructor.
this
double overDraftLimit:
t e ( a
e n se this value in the overDraftLimit field.
Store
I s tra le licconstructor that has one parameter. This constructor
d. Add a CheckingAccount
shouldrset
n d f e r ab
a the overDraftLimit field to zero.
adouble s
l e x ranbalance: Pass this value to the parent class constructor.
A n-t
no
Note: It is a good practice to add @Override to any method that should be overriding
a parent class method.
f. Override the abstract withdraw method inherited from the Account class.
The withdraw method should allow an account balance to go negative up to the
amount specified in the overDraftLimit field.
The withdraw method should return false if the withdraw cannot be performed,
and true if it can.
11. Modify the AbstractBankingMain class to create checking accounts for the customers.
// Create several customers and their accounts
s a
bank.addCustomer("Jane", "Simms");
) h a
customer = bank.getCustomer(0);
c o m e ฺ
ฺ i d
customer.addAccount(new TimeDepositAccount(500.00,
cal.getTime())); r a cle t Gu
@ o e n
e
customer.addAccount(new CheckingAccount(200.00, 400.00));
t tu d
t r a S
r a ฺis this
bank.addCustomer("Owen", "Bryant");
a n d use
customer = bank.getCustomer(1);
l e x CheckingAccount(200.00));
to
customer.addAccount(new ( a ns e
a t e c e
I s tr le li "Soley");
rab
ra = ebank.getCustomer(2);
bank.addCustomer("Tim",
n d
customer
a f
l e a s
xcustomer.addAccount(new
n
t r
A cal.getTime()));
n -
TimeDepositAccount(1500.00,
nocustomer.addAccount(new CheckingAccount(200.00));
bank.addCustomer("Maria", "Soley");
customer = bank.getCustomer(3);
// Maria and Tim have a shared checking account
customer.addAccount(bank.getCustomer(2).getAccount(1));
customer.addAccount(new TimeDepositAccount(150.00,
cal.getTime()));
Note: Both Customer and CustomerReport can utilize CheckingAccount
instances, because you previously modified them to use Account type references.
Overview
In this practice, you will take an existing application and refactor the code to use the abstract
keyword.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the abstract class section of this lesson.
Summary
You have been given a project that implements the logic for a bank. The banking software
supports only the creation of time deposit accounts. Time deposit accounts allow withdraw only
after a maturity date. Time deposit accounts are also known as term deposit, certificate of
deposit (CD), or fixed deposit accounts. You will enhance the software to support checking
accounts.
A checking account and a time deposit account have some similarities and some differences.s a
) h a
Your class design should reflect this. Additional types of accounts might be added in the future.
c o m e ฺ
ฺ i d
Tasks
r a cle t Gu
1. Open the AbstractBanking project as the main project. o n
e @ d e
a. Select File > Open Project.
t r a t S tu
r a ฺis this
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
c. Select AbstractBanking and select
a n se as Main Project” check box.
d theu“Open
l
d. Click the Open Project button. e x to
( a ns e
a t e
2. Expand the project directories.
c e
3. Run the project.Is tr should
You
l e li a report of all customers and their accounts.
see
n d ra erabCUSTOMERS REPORT
x a n s f
e
Al n-tra
================
@Override
public String getDescription() {
return "Time Deposit Account " + maturityDate;
}
Note: It is a good practice to add @Override to any method that should be overriding
a parent class method.
8. Modify the Customer and CustomerReport classes to use Account references.
a. Open the Customer.java file (under the com.example package).
b. Change all TimeDepositAccount references to Account type references. s a
c. Open the CustomerReport.java file (under the com.example package). )h a
c
d. Change all TimeDepositAccount references to Account type ฺreferences.
m
o ideฺ
e Gu
claccounts.
o a
9. Run the project. You should see a report of all customers andrtheir
n t
@
10. Create a new Java class, CheckingAccount, in the com.example epackage.
a
a. CheckingAccount should be a subclass oftrAccount.
te Stud
a ฺis
extends th
is
public class CheckingAccount r
nd us e Account
b. Add an overDraftLimit field
e x ato the CheckingAccount
to class.
a l e
( overDraftLimit;
private final double
a t e c e ns
I s tr le li constructor.
c. Add a CheckingAccount
n d
public
f e rab
raCheckingAccount(double balance, double overDraftLimit) {
a
x ran s
Ale n-tthis.overDraftLimit
super(balance);
= overDraftLimit;
o
n}
d. Add a CheckingAccount constructor that has one parameter.
public CheckingAccount(double balance) {
this(balance, 0);
}
e. Override the abstract getDescription method inherited from the Account class.
@Override
public String getDescription() {
return "Checking Account";
}
Note: It is a good practice to add @Override to any method that should be overriding
a parent class method.
balance -= amount;
return true;
} else {
return false;
}
}
11. Modify the AbstractBankingMain class to create checking accounts for the customers.
// Create several customers and their accounts
s a
bank.addCustomer("Jane", "Simms");
) h a
customer = bank.getCustomer(0);
c o m e ฺ
ฺ i d
customer.addAccount(new TimeDepositAccount(500.00,
r a cle t Gu
cal.getTime()));
@ o e n
t e
customer.addAccount(new CheckingAccount(200.00, 400.00));
tu d
t r a S
r a ฺis this
bank.addCustomer("Owen", "Bryant");
a n d use
customer = bank.getCustomer(1);
l e x to
customer.addAccount(new ( a ns e
CheckingAccount(200.00));
a t e c e
I s tr le li "Soley");
rab
ra = ebank.getCustomer(2);
bank.addCustomer("Tim",
a n d f
l e
customer
a n s
xcustomer.addAccount(new
n - t r
A cal.getTime())); TimeDepositAccount(1500.00,
nocustomer.addAccount(new CheckingAccount(200.00));
bank.addCustomer("Maria", "Soley");
customer = bank.getCustomer(3);
// Maria and Tim have a shared checking account
customer.addAccount(bank.getCustomer(2).getAccount(1));
customer.addAccount(new TimeDepositAccount(150.00,
cal.getTime()));
Note: Both Customer and CustomerReport can utilize CheckingAccount
instances, because you previously modified them to use Account type references.
Overview
In this practice, you will take an existing application and refactor the code to implement the
Singleton design pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the static and final keyword sections of this lesson.
Summary
You have been given a project that implements the logic for a bank. The application currently
allows the creation of an unlimited number of Bank instances.
Bank bank = new Bank();
Bank bank2 = new Bank();
Bank bank3 = new Bank(); s a
a
) hper Java
Using the static and final keywords you will limit the number of Bank instances to one
virtual machine (JVM). c m
o ideฺ
ฺ
Tasks r a cle t Gu
@ o e n
1. Open the SingletonBanking project as the main project. t e tu d
t r a S
a. Select File > Open Project.
r a ฺis this
a n d use
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
c. Select SingletonBankingx tothe “Open as Main Project” check box.
and select
a l e
d. Click the Open Project(button. s e
2. Expand the projecttr a te licen
directories.
a
3. Run the project.
r IsYou should
b lesee a report of all customers and their accounts.
a
nd sfer CUSTOMERS REPORT
x a n
Ale n-tra ================
no
Customer: Simms, Jane
Time Deposit Account Fri Mar 09 12:04:28 CST 2012: current
balance is 500.0
n d ra erab
CustomerReport
x a s f
report.setBank(bank);
n
e
Al n-tra
report.generateReport();
nothe project. You should see a report of all customers and their accounts.
6. Run
Overview
In this practice, you will take an existing application and refactor the code to implement the
Singleton design pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the static and final keyword sections of this lesson.
Summary
You have been given a project that implements the logic for a bank. The application currently
allows the creation of an unlimited number of Bank instances.
Bank bank = new Bank();
Bank bank2 = new Bank();
Bank bank3 = new Bank();
s a
Using the static and final keywords you will limit the number of Bank instances to one a
) hper Java
Virtual Machine (JVM).
c m
o ideฺ
ฺ
Tasks r a cle t Gu
@ o e n
1. Open the SingletonBanking project as the main project.
t e tu d
a. Select File > Open Project. t r a S
r a ฺis this
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
a d use
nselect
c. Select SingletonBankingx and othe “Open as Main Project” check box.
l
a nse
d. Click the Open Project(button.
e t
2. Expand the projecttr a t e i ce
s
IYou should l
directories.
lesee a report of all customers and their accounts.
3. Run the project.r a a b
4. Modify
x a er to implement the Singleton design pattern.
nthedBanksclass
f
Aa.le Open - t r anBank.java file (under the com.example package).
the
b.no
n
Change the constructor’s access level to private.
private Bank() {
customers = new Customer[10];
numberOfCustomers = 0;
}
c. Add a new field named instance. The field should be:
private
Marked static
Marked final
Type of Bank
Initialized to a new Bank instance
private static final Bank instance = new Bank();
d. Create a static method named getInstance that returns the value stored in the
instance field.
public static Bank getInstance() {
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
getInstance method.
Bank bank = Bank.getInstance();
c. In the main method, create a second local Bank reference named bank2 and initialize
it using the getInstance method.
Bank bank2 = Bank.getInstance();
d. Use reference equality checking to determine whether bank and bank2 reference the
same object.
if(bank == bank2) {
s a
}
System.out.println("bank and bank2 are the same object");
) h a
c o m e ฺ
ฺ
e. Initialize only the second Bank, but run the report on the first Bank. i d
initializeCustomers(bank2); r a cle t Gu
@ o e n
t e tu d
t r a S
ฺis this
// run the customer report
CustomerReport report = newra
report.setBank(bank); xan
d use
CustomerReport();
a l e e to
report.generateReport();
t e ( ns of all customers and their accounts.
6. Run the project. You a
tr le li
should see caereport
I s
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will take an existing application and refactor the code to use an enum.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Summary
You have been given a project that implements the logic for a bank. The application currently
allows the creation of TimeDepositAccount instances with any maturity date.
//180 day term
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 180);
new TimeDepositAccount(500.00, cal.getTime()) s a
By creating a new Java enum you will modify the application to only allow for the creation
a
) h of
TimeDepositAccount instances with a maturity date that is 90 or 180 in the c m
ofuture.ideฺ
ฺ
Tasks r a cle t Gu
o en
1. Open the EnumBanking project as the main project.te@ tud
a. Select File > Open Project. i s t ra is S
d r aฺ e th
b. Browse to D:\labs\05-Advanced_Class_Design\practices. s
c. Select EnumBanking andle xanthe “Open
select t o uas Main Project” check box.
( a n s e
d. Click the Open Project
t r a te button.
l i c e
2. Expand the project
r a Is directories.
b lesee a report of all customers and their accounts.
3. Run the project.
na dnew JavaYou
f r a
should
eenum,
x
4. Create
e a n s DepositLength, in the com.example package.
A l
5. Code n t r a
- DepositLength enum.
the
n o
a. Declare a days field along with a corresponding constructor and getter method.
private int days;
cal.add(Calendar.DAY_OF_YEAR, duration.getDays());
this.maturityDate = cal.getTime();
}
7. Modify the EnumBankingMain class to create TimeDepositAccount instances using the
two DepositLength instances available.
a. Open the EnumBankingMain.java file (under the com.example package).
b. Within the initializeCustomers method, remove the code to create calendars.
c. Within the initializeCustomers method, modify the creation of all
TimeDepositAccount instances to use the DepositLength enum.
s a
customer.addAccount(new TimeDepositAccount(500.00,
)h a
DepositLength.SIX_MONTHS));
c m
o ideฺ
Note: Try using both the SIX_MONTHS and THREE_MONTHS c
ฺ
le You
values. ucan also use
a static import to reduce the length of the statement. ora n t G
e @ u d e
r a t
8. Run the project. You should see a report of all customers and
S their
t accounts. It is now
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will take an existing application and attempt to recognize the declaration
and use of various types of nested classes.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the nested class section of this lesson.
Summary
You have been given a small project that contains only two .java files. Although there are only
two .java files, there may be multiple Java classes being created.
Attempt to determine the number of classes being created.
Tasks
1. Open the NestedClasses project as the main project. s a
) h a
a. Select File > Open Project. m
ฺ c o d e ฺ
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
cle t Gu i
r a
c. Select NestedClasses and select the “Open as Main Project” check box.
o n
d. Click the Open Project button. e @ d e
t r a t S tu
2.
3.
Expand the project directories.
r a ฺis this
Run the project. You should see the output in the output window.
a n d use
4.
l e x
Count the number of classes created in the OuterClass.java file.
to
( a ns e
a. Open the OuterClass.java file (under the com.example package).
a t e c e
I s tr le li
b. Determine the total number of classes created in this file.
n d ra erab
c. Determine the total number of top-level classes created in this file.
x a n s f
d. Determine the total number of nested classes created in this file.
e
Al n-tra
e. Determine the total number of inner classes.
no
f. Determine the total number of member classes.
g. Determine the total number of local classes.
h. Determine the total number of anonymous classes.
i. Determine the total number of static nested classes.
Hint: Using the Files tab in NetBeans, you can see how many .class files are created by
looking in the build\classes folder for a project.
Overview
In this solution, you will take an existing application and review the number and types of nested
classes created within a single .java file.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the nested class section of this lesson.
Summary
You have been given a small project that contains only two .java files. Although there are only
two .java files, there may be multiple Java classes being created.
Review the number of classes being created.
Tasks
1. Open the NestedClasses project as the main project. s a
) h a
a. Select File > Open Project. m
ฺ c o d e ฺ
b. Browse to D:\labs\05-Advanced_Class_Design\practices.
cle t Gu i
r a
c. Select NestedClasses and select the “Open as Main Project” check box.
o n
d. Click the Open Project button. e @ d e
t r a t S tu
2.
3.
Expand the project directories.
r a ฺis this
Run the project. You should see the output in the output window.
a n d use
4.
l e x
Open the OuterClass.java file (under the com.example package).
to
( a ns e
Within the OuterClass.java file there are:
a t e c e
10 classes
I s tr le li
n d ra erab
1 top-level class
x a n s f
9 nested classes
e
Al n-tra 8 inner classes
no 3 member classes
2 local classes
3 anonymous classes
1 static nested class
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G6:u
Lesson
@ o e n
Inheritance t e with d
tu Java
t r a S
r a ฺis this
Interfaces
a n d use
l e x to 6
Chapter
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you will use Java interfaces and apply design patterns.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will create an interface and implement that interface.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Summary
You have been given a project that contains an abstract class named Animal. You create a
hierarchy of animals that is rooted in the Animal class. Several of the animal classes
implement an interface named Pet, which you will create.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Tasks
1. Open the Pet project as the main project.
a. Select File > Open Project.
b. Browse to D:\labs\06-Interfaces\practices.
c. Select Pet and select the “Open as Main Project” check box.
d. Click the Open Project button.
2. Expand the project directories.
3. Run the project. You should see text displayed in the output window.
a n d use
An eat() method that prints out "Fish eat pond scum."
e x to
A walk() method that overrides the Animal class walk method. It should first call
l
( a ns e
the super class walk method, and then print "Fish, of course, can't walk;
a t e c e
they swim."
I s tr le li
9. Create a new Java class: Cat in the com.example package.
n d ra erab
x n s f
10. Code the Cat class.
a
e
Al n-tra
a. This class should:
no
Extend the Animal class
Implement the Pet interface
b. Complete this class by creating:
A String field called name
Getter and setter methods for the name field
A constructor that receives a name String and passes a value of 4 to the parent
constructor
A no-argument constructor that passes a value of "Fluffy" to the other constructor
in this class
A play() method that prints out name + " likes to play with string."
An eat() method that prints out "Cats like to eat spiders and fish."
Overview
In this practice, you will create an interface and implement that interface.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Summary
You have been given a project that contains an abstract class named Animal. You create a
hierarchy of animals that is rooted in the Animal class. Several of the animal classes
implement an interface named Pet, which you will create.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Tasks
1. Open the Pet project as the main project.
a. Select File > Open Project.
b. Browse to D:\labs\06-Interfaces\practices.
c. Select Pet and select the "Open as Main Project" check box.
d. Click the Open Project button.
2. Expand the project directories.
3. Run the project. You should see text displayed in the output window.
n d ra era=b name;
this.name
x}a n s f
e tra
Al nA -no-argument constructor that passes a value of 0 to the parent constructor.
nopublic Fish() {
super(0);
}
A play() method that prints out "Just keep swimming."
@Override
public void play() {
System.out.println("Just keep swimming.");
}
A walk() method that overrides the Animal class walk method. It should first call
the super class walk method, and then print " Fish, of course, can't walk;
they swim."
@Override
public void walk() {
super.walk();
System.out.println("Fish, of course, can't walk; they
swim.");
}
s a
9. Create a new Java class: Cat in the com.example package.
)h a
10. Code the Cat class.
c m
o ideฺ
ฺ
e interface.
a. This class should extend the Animal class and implement the
r a clPet t G u
public class Cat extends Animal implements
@ o Pet en
b. Complete this class by creating: r a t e S t ud
A String field called name.
r a ฺist this
Getter and setter methods forathe n u se
dname field.
A constructor that receivesl e xa name String
to and passes a value of 4 to the parent
( a ns e
constructor.
a t e c e
I s tr le name)
public Cat(String li {
n d ra erab
super(4);
x a this.name
n s f = name;
e
Al }n-tra
no 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."
s.walk();
//test a spider with an animal reference
a = new Spider();
a.eat();
a.walk();
c. Add additional lines of code to test the Fish and Cat classes that you created.
Try using every constructor
Experiment with using every reference type possible and determine which methods
can be called with each type of reference. Use a Pet reference while testing the
s a
Fish and Cat classes.
) h a
Pet p;
c o m e ฺ
ฺ i d
r a cle t Gu
Cat c = new Cat("Tom");
@ o e n
c.eat(); t e tu d
t r a S
c.walk();
r a ฺis this
c.play();
a n d use
a = new Cat();
l e x t o
a e
a.eat();
a.walk(); tra
te ( licens
r a Is ble
a n d fera Whiskers");
p = new Cat();
l e a n s
p.setName("Mr.
xp.play();
A n-t r
no
Fish f = new Fish();
f.setName("Guppy");
f.eat();
f.walk();
f.play();
a = new Fish();
a.eat();
a.walk();
Overview
In this practice, you will take an existing application and refactor the code to implement the data
access object (DAO) design pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the DAO sections of this lesson.
Summary
You have been given a project that implements the logic for a human resources application. The
application allows for creating, retrieving, updating, deleting, and listing Employee objects.
Employee objects are currently stored in-memory using an array. You must move any code
related to the persistence of Employee objects out of the Employee class. In later practices,
you will supply alternative persistence implementations. In the future, this application should
require no modification when substituting the persistence implementation. s a
) h a
Tasks
c o m e ฺ
ฺ i d
1. Open the EmployeeMemoryDAO project as the main project.
r a cle t Gu
a. Select File > Open Project.
@ o e n
b. Browse to D:\labs\06-Interfaces\practices. t e tu d
t r a S
c. Select EmployeeMemoryDAO and selectฺithe
r a s "Open
e t hiass Main Project" check box.
d. Click the Open Project button. nd
2. Expand the project directories.lex
a to us
t e
3. Run the project. You should e se Test all the menu choices.
(asee a menu.
n
[C]reate Is
ra e |lic[U]pdate | [D]elete | [L]ist | [Q]uit:
| t[R]ead
r a a b l
x
Note:
a er dates, they should be in the form of: Nov 26, 1976
ndWhensfentering
A le Employee
- t r anIDs should be in the range of 0 through 9.
on the Employee class.
4. Review
n
a. Open the Employee.java file (under the com.example.model package).
b. Find the array used to store employees.
private static Employee[] employeeArray = new Employee[10];
Note: The employee’s id is used as the array index.
c. Locate any methods that utilize the employeeArray field. These methods are used to
persist employee objects.
5. Create a new com.example.dao package.
6. Create an EmployeeDAO interface in the com.example.dao package.
a n d use
EmployeeDAO dao = new EmployeeDAOMemoryImpl();
l e xthis tighttocoupling from the
( classnsbyecreating a DAO factory.
In the following steps, you remove
t e a
EmployeeTestInteractive
s t r a l i ce interface.
r a I no-argument
12. Modify the EmployeDAOMemoryImpl
a b le
Add a d
n protected,
f e r constructor.
a s
A lex an
13. Create
t r a n
EmployeeDAOFactory class in the com.example.dao package.
Overview
In this practice, you will take an existing application and refactor the code to implement the data
access object (DAO) design pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the DAO sections of this lesson.
Summary
You have been given a project that implements the logic for a human resources application. The
application allows for creating, retrieving, updating, deleting, and listing Employee objects.
Employee objects are currently stored in-memory using an array. You must move any code
related to the persistence of Employee objects out of the Employee class. In later practices,
you will supply alternative persistence implementations. In the future, this application should
require no modification when substituting the persistence implementation. s a
) h a
Tasks
c o m e ฺ
ฺ i d
1. Open the EmployeeMemoryDAO project as the main project.
r a cle t Gu
a. Select File > Open Project.
@ o e n
b. Browse to D:\labs\06-Interfaces\practices. t e tu d
t r a S
c. Select EmployeeMemoryDAO and selectฺithe
r a s "Open
e t hiass Main Project" check box.
d. Click the Open Project button. nd
2. Expand the project directories.lex
a to us
t e
3. Run the project. You should e se Test all the menu choices.
(asee a menu.
n
[C]reate Is
ra e |lic[U]pdate | [D]elete | [L]ist | [Q]uit:
| t[R]ead
r a a b l
x
Note:
a er dates, they should be in the form of: Nov 26, 1976
ndWhensfentering
A le Employee
- t r anIDs should be in the range of 0 through 9.
on the Employee class.
4. Review
n
a. Open the Employee.java file (under the com.example.model package).
b. Find the array used to store employees. You will relocate this field in a subsequent
step.
private static Employee[] employeeArray = new Employee[10];
Note: The employee’s id is used as the array index.
c. Locate the save, delete, findById, and getAllEmployees methods that utilize
the employeeArray field. These methods are used to persist employee objects. You
will relocate these methods in a subsequent step.
5. Create a new com.example.dao package.
6. Create an EmployeeDAO interface in the com.example.dao package.
7. Complete the EmployeeDAO interface with the following method signatures. Add import
statements as needed.
public void add(Employee emp);
public void update(Employee emp);
public void delete(int id);
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
EmployeeDAOMemoryImpl class:
s a
)h a
c m
o ideฺ
ฺ
r a cle t Gu
@ o e n
b. Implement the EmployeeDAO interface. Modifyathe e
t methods d
tuthat you moved in the
t r S
previous step to become the methods required
r a ฺis this
by the EmployeeDAO interface.
The save method becomes the add
n d methodu s eand is modified to have an Employee
parameter.
e x a to
The save method is ( a l
duplicated s e
a t e c e n to become the update method and is modified to
I s tr le li
have an Employee parameter.
The delete
d r a methodr a b is modified to have an id parameter.
x n findById
aThe
n s fe method is no longer static.
e
Al nThe
- a
trgetAllEmployees method is no longer static.
no
x a n}s f
e
Al n-tra return emps.toArray(new Employee[0]);
no }
}
10. Update the EmployeeTestInteractive class.
a. The EmployeeTestInteractive class no longer compiles, review the errors.
b. Create an EmployeeDAO instance in the main method. Use the EmployeeDAO
interface as the reference type. Replace the line:
//TODO create dao
With:
EmployeeDAO dao = new EmployeeDAOMemoryImpl();
emp.getId());
System.out.println("\n\nCreated " + emp);
break;
Note: You can also remove the now unnecessary finding of employee object that is
present when deleting an employee.
// Find this Employee record
emp = null;
emp = Employee.findById(id);
if (emp == null) {
s a
System.out.println("\n\nEmployee " + id + " not found");
)h a
break;
c m
o ideฺ
ฺ
}
r a cle t Gu
11. Run the project. You should see a menu. Test all the menu o choices. en
t e @ t uisdstill tied to a specific
Note: While functional, the EmployeeTestInteractive
r a class
S
type of DAO because it references the EmployeeDAO
r a ฺist thimplementing
is class by name.
nd us
EmployeeDAO dao = new EmployeeDAOMemoryImpl(); e
e x a tocoupling from the
In the following steps, you remove
a l this tight
e
( classnsby creating a DAO factory.
EmployeeTestInteractive
r a t e i ce interface.
s t
12. Modify the EmployeDAOMemoryImpl l
a. Add d r
a protected, ble
a I rano-argument constructor.
a n s f e
xEmployeeDAOMemoryImpl()
n
Ale }n-tra
{
b. Obtain an EmployeeDAO instance using the factory created in the previous step.
Replace the line:
EmployeeDAO dao = new EmployeeDAOMemoryImpl();
With:
EmployeeDAO dao = factory.createEmployeeDAO();
c. Fix any imports.
16. Run the project. You should see a menu. Test all the menu choices.
In the future, you will be able to change the persistence mechanism to use a database
s a
without changing the reference types or method calls used in the
) h a
EmployeeTestInteractive class. Notice that none of the *MemoryImpl classes are
m
used by name from within the EmployeeTestInteractive class. ฺ c o d e ฺ
cle t Gu i
o r a n
e @ d e
t r a t S tu
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will take an existing application and refactor it to make use of composition.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
You have reviewed the interface and composition sections of this lesson.
Summary
You have been given a small project that represents a hierarchy of animals that is rooted in the
Animal class. Several of the animal classes implement an interface named Pet. This project is
a completed implementation of the “Implementing an Interface” practice.
There are some potential problems with the design of the existing project. If you wanted to
restrict a pet’s name to less than 20 characters how many classes would you have to modify?
Would this problem become worse with the addition of new animals?
If some types of animals, such as Fish, cannot walk, should they have a walk method? s a
)h a
Tasks c m
o ideฺ
ฺ
1. Open the PetComposition project as the main project.
r a cle t Gu
a. Select File > Open Project.
@ o e n
t e tu d
b. Browse to D:\labs\06-Interfaces\practices.
t r a S
c. Select PetComposition and select the a s asthMain
ฺi"Open is Project" check box.
r
d us e
d. Click the Open Project button. an
2. Expand the project directories. l e x to
a
( see output e
ns in the output window.
3. Run the project. Youa t e
should
c e
I s
4. Centralize all “name” l e li
tr functionality.
d
All petsncan
a named,
rbe b you may want to give names to objects that cannot play. For
rabut
xa you f e
s name a volleyball “Wilson.” Your design should reflect this.
instance,
l e r a n
could
Aa. Create
o n -t a Nameable interface (under the com.example package).
b.n Complete the Nameable interface with setName and getName method signatures.
public interface Nameable {
}
c. Create a NameableImpl class (under the com.example package).
d. Complete the NameableImpl class. It should:
Implement the Nameable interface
Contain a private String field called name
Only accept names less than 20 characters in length
Print "Name too long" if a name is too long
e. Modify the Pet interface.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G7:u
Lesson
@ o e n
Generics e
t and d
tuCollections
t r a S
r a ฺis 7 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, use generics and collections to practice the concepts covered in the lecture.
For each practice, a NetBeans project is provided for you. Complete the project as indicated in
the instructions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, use the HashMap collection to count a list of part numbers.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the collections section of this lesson.
Summary
You have been asked to create a simple program to count a list of part numbers that are of an
arbitrary length. Given the following mapping of part numbers to descriptions, count the number
of each part. Produce a report that shows the count of each part sorted by the part’s product
description. The part-number-to-description mapping is as follows:
Part Number
s Description a
1S01 Blue Polo Shirt ) h a
c o m e ฺ
1S02 Black Polo Shirt ฺ
le Gu i d
1H01 Red Ball Cap rac t
@ o e n
1M02 Duke Mug
r a t e Stud
r a ฺist this
Once complete, your report should look like
a n dthis: use
=== Product Report l=== e x to
a e
(Shirt ns Count: 6
Name: Black Polo
r a t e i ce Count: 7
Name: Blue
I s tPolo
le l
Shirt
Name:ra
d Duke Mug r a b Count: 3
n
a Red
xName: f e
s Ball Cap
l e r a n Count: 5
A n-t
no
Tasks
Open the Generics-Practice01 project and make the following changes.
1. For the ProductCounter class, add two private map fields. The first map counts part
numbers. The order of the keys does not matter. The second map stores the mapping of
product description to part number. The keys should be sorted alphabetically by description
for the second map.
2. Create a one argument constructor that accepts a Map as a parameter. The map that stores
the description-to-part-number mapping should be passed in here.
3. Create a processList() method to process a list of String part numbers. Use a HashMap
to store the current count based on the part number.
public void processList(String[] list){ }
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, use the HashMap collection to count a list of part numbers.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the collections section of this lesson.
Summary
You have been asked to create a simple program to count a list of part numbers that are of an
arbitrary length. Given the following mapping of part numbers to descriptions, count the number
of each part. Produce a report that shows the count of each part sorted by the part’s product
description. The part number to description mapping is as follows:
Part Number
s Description a
1S01 Blue Polo Shirt ) h a
c o m e ฺ
1S02 Black Polo Shirt ฺ
le Gu i d
1H01 Red Ball Cap rac t
@ o e n
1M02 Duke Mug
r a t e Stud
r a ฺist this
Once complete, your report should look like
a n dthis: use
=== Product Report l=== e x to
a e
(Shirt ns Count: 6
Name: Black Polo
r a t e i ce Count: 7
Name: Blue
I s tPolo
le l
Shirt
Name:ra
d Duke Mug r a b Count: 3
n
a Red
xName: f e
s Ball Cap
l e r a n Count: 5
A n-t
no
Tasks
Open the Generics-Practice01 project and make the following changes.
1. For the ProductCounter class, add two private map fields. The first map counts part
numbers. The order of the keys does not matter. The second map stores the mapping of
product description to part number. The keys should be sorted alphabetically by description
for the second map.
private Map<String, Long> productCountMap = new HashMap<>();
private Map<String, String> productNames = new TreeMap<>();
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.
Overview
In this practice, you use the Deque object to match parentheses in a programming statement.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the collections section of this lesson.
Summary
Use the Deque data structure as a stack to match parentheses in a programming statement.
You will be given several sample lines containing logical statements. Test the lines to ensure
that the parentheses match, return true if they do, false if they do not.
For example, the output from the program might look like the following.
s a
Line 0 is valid
)h a
Line 1 is invalid
c m
o ideฺ
ฺ
Line 2 is invalid
r a cle t Gu
Line 3 is valid
@ o e n
t e tu d
t r a S
Tasks r a ฺis this
a n d use
Open the Generics-Practice02 project
l e x andtomake the following changes.
1. Modify the processLine()
t e (amethodnsineParenMatcher.java to read a line in and convert
the string into a character
s t r a array.
l i ce
2. Loop throughathe
r a le “(“ onto the stack. When a “)” is encountered, pop a “(“ from
I array. bPush
the stack.
x a s f er should return false.
ndTwo conditions
Aa.le Ifdonyou
- an to call a pop operation and the stack is empty, the number of parentheses
trneed
not match, return false.
n o
b. If after completing the loop a “(“ is left on the stack return false. The number of
parentheses does not match.
3. Run the ParanMatcher.java class to ensure that your program produces the desired
output.
Overview
In this practice, you use the Deque object to match parentheses in a programming statement.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Summary
Use the Deque data structure as a stack to match parentheses in a programming statement.
You will be given several sample lines containing logical statements. Test the lines to ensure
that the parentheses match, return true if they do, false if they do not.
For example, the output from the program might look like the following.
Line 0 is valid
s a
Line 1 is invalid
)h a
Line 2 is invalid
c m
o ideฺ
ฺ
Line 3 is valid
r a cle t Gu
@ o e n
t e tu d
Tasks t r a S
Open the Generics-Practice02 project d r
and e his changes.
ฺis the tfollowing
amake
1. Modify the processLine() method x t o us
anin ParenMatcher.java to read a line in and convert
( a l e
the string into an array of characters. e
Clear the stack and convert the line to a character
array. t e e n s
I s tra le lic
ra curLinerab = line.toCharArray();
stack.clear();
n d f e
l e xa rans
A n-t
no
switch (c){
case '(':stack.push(c);break;
case ')':{
if (stack.size() > 0){
stack.pop();
} else {
return false;
}
s a
break;
)h a
}
c m
o ideฺ
ฺ
cle t Gu
}
}
o r a n
e @ d e
if (stack.size()> 0){
t r a t S tu
ฺis this
return false; // Missing match invalid expression
} else { r a
d use
x a
return true; // n
a l e e to
}
t e ( nsto ensure that your program produces the desired
a
tr le li
3. Run the ParanMatcher.java c e
class
output. I s
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you process shirt-related transactions for a Duke’s Choice store. Compute the
inventory level for a number of shirts. Then print out the shirt data sorted by description and by
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
inventory count.
Assumptions
You have reviewed all the content in this lesson.
Summary
Any Duke’s Choice stores carry a number of products including shirts. In this practice, process
the shirt-related transactions and calculate the inventory levels. After the levels have been
calculated, print a report sorted by description and a report sorted by inventory count. You will
s
create two classes that implement the Comperator interface to allow sorting shirts by count and a
by description. ) h a
For example, the output from the program might look like the following. c o m e ฺ
ฺ i d
=== Inventory Report - Description ===
r a cle t Gu
Shirt ID: P002
@ o e n
t e tu d
Description: Black Polo Shirt
t r a S
Color: Black
r a ฺis this
Size: M
a n d use
Inventory: 15 l e x to
( a ns e
a t e c e
Shirt ID:sP001
I tr le li
d ra eraBlue
Description: b Polo Shirt
a n
xColor: s f
l e r a n
Blue
A Size:
o n -t L
n Inventory: 24
Shirt ID: P003
Description: Maroon Polo Shirt
Color: Maroon
Size: XL
Inventory: 20
- t an
Ale Description:
r Blue Polo Shirt
n
noColor: Blue
Size: L
Inventory: 24
Tasks
Open the Generics-Practice03 project and make the following changes.
1. Review the Shirt class and InventoryCount interface to see how the Shirt class has
changed to support inventory features.
2. Review the DukeTransaction class to see how transactions are defined for this program.
3. Update the SortShirtByCount Comparator class to sort shirts by count.
4. Update the SortShirtByDesc Comparator class to sort shirts by description.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you process shirt-related transactions for a Duke’s Choice store. Compute the
inventory level for a number of shirts. Then print out the shirt data sorted by description and by
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
inventory count.
Assumptions
You have reviewed all the content in this lesson.
Summary
Any Duke’s Choice stores carry a number of products including shirts. In this practice, process
the shirt-related transactions and calculate the inventory levels. Once the levels have been
calculated print a report sorted by description and a report sorted by inventory count. You will
s
create two classes that implement the Comperator interface to allow sorting shirts by count and a
by description. ) h a
For example, the output from the program might look like the following. c o m e ฺ
ฺ i d
=== Inventory Report - Description ===
r a cle t Gu
Shirt ID: P002
@ o e n
t e tu d
Description: Black Polo Shirt
t r a S
Color: Black
r a ฺis this
Size: M
a n d use
Inventory: 15 l e x to
( a ns e
a t e c e
Shirt ID:sP001
I tr le li
d ra eraBlue
Description: b Polo Shirt
a n
xColor: s f
l e r a n
Blue
A Size:
o n -t L
n Inventory: 24
Shirt ID: P003
Description: Maroon Polo Shirt
Color: Maroon
Size: XL
Inventory: 20
- t an
Ale Description:
r Blue Polo Shirt
n
noColor: Blue
Size: L
Inventory: 24
Tasks
Open the Generics-Practice03 project and make the following changes.
1. Review the Shirt class and InventoryCount interface to see how the Shirt class has
changed to support inventory features.
2. Review the DukeTransaction class to see how transactions are defined for this program.
return c1.compareTo(c2);
}
}
x a n s f
currentShirt = polos.get(transaction.getProductID());
e
Al n-t}raelse {
no } System.out.println("Error: Invalid part number");
switch (transaction.getTransactionType()) {
case "Purchase":currentShirt.
addItems(transaction.getCount()); break;
case "Sale":currentShirt.
removeItems(transaction.getCount()); break;
// Init Comparators
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
for(Shirt shirt:poloList){
System.out.println(shirt.toString());
s a
}
)h a
c m
o ideฺ
ฺ
r a cle t Gu
Print the list of shirts by count.
@ o e n
// Print Results - Sort by Count at e tu d
t r S
Collections.sort(poloList, sortCount);
r a ฺis this
System.out.println("=== n
a d useReport - Count ===");
Inventory
l e x to
( a ns e
t e
for(Shirt shirt:poloList){
a c e
I s tr le li
System.out.println(shirt.toString());
} dra
n f e rab
6. Run
e a TestItemCounter.java
xthe n s class to ensure that your program produces the desired
l
Aoutput.n-t r a
no
s a
)h a
c m
o ideฺ
ฺ
Practices for r a cle t G8:u String
Lesson
@ o e n
Processing t e tu d
t r a S
r a ฺis 8 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you use regular expressions and String.split() to manipulate strings in
Java. For each practice, a NetBeans project is provided for you. Complete the project as
indicated in the instructions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, parse comma-delimited text and convert the data into Shirt objects.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
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.
Overview
In this practice, parse comma-delimited text and convert the data into Shirt objects.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
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.
4. Run the StringSplitTest.java file and verify that your output is similar to that shown
in the “Summary” section of this practice.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, create a program that searches a text file by using regular expressions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have participated in the lecture for this lesson.
Summary
Create a simple application that will loop through a text file (gettys.html) and search for text
by using regular expressions. If the desired text is found on a line, print out the line number and
the line text. For example, if you performed a search for “<h4>” the output would be:
9 <h4>Abraham Lincoln</h4>
10 <h4>Thursday, November 19, 1863</h4>
s a
)h a
c m
o ideฺ
Tasks ฺ
le Gu
Open the StringsPractice02 project and make the followingochanges. rac nPleaset note that the
code to read a file has been supplied for you. @
e Stud e
r a t
Note: The gettys.html file is located in the rootis
the project open, click the Files tab. Double-click r a ฺtheoftfile h is folder.
the project
totopen
To examine the file, with
it and examine its contents.
1. Edit the FindText.java file. xan
d use
a l e e to
2. Create a Pattern and a Matcher
t e ( s
field.
nsupplied
3. Generate a Matcher a
tr le li
based on c e
the Pattern object.
4. Search each
I s
aline for rthe bpattern supplied.
d r a
5. Print a
x nline number
the
n s fe and the line that has matching text.
e tra
l the-FindText.java
6. ARun file and search for these patterns.
n
o lines that contain: <h4>
nAll
All the lines that contain the word “to” (For example, line 17 should not be selected.)
All the lines that contain ‘class=”line”’
All the lines that contain a pair of brackets “{ }”
Lines that begin with “<p” or “<d”
Lines that only contain HTML closing tags (for example, “</div>”)
7. (Optional) Modify the program to accept the file name and regular expression pattern on the
command line.
Overview
In this practice, create a program that searches a text file by using regular expressions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have participated in the lecture for this lesson.
Summary
Create a simple application that will loop through a text file and search for text by using regular
expressions. If the desired text is found on a line, print out the line number and the line text. For
example, if you performed a search for “<h4>” the output would be:
9 <h4>Abraham Lincoln</h4>
10 <h4>Thursday, November 19, 1863</h4>
s a
)h a
c m
o ideฺ
Tasks ฺ
le Gu
Open the StringsPractice02 project and make the followingochanges. rac nPleaset note that the
code to read a file has been supplied for you. @
e Stud e
r a t
Note: The gettys.html file is located in the root s
r a
the project open, click the Files tab. Double-click
ioftfile
ฺthe the project
h is folder.
totopen
To examine the file, with
it and examine its contents.
1. Edit the FindText.java file. xan
d use
2. Create fields for a Pattern(a lea Matcher
and e toobject.
privatetra
te pattern;
Patternlic ens
r a Is Matcher
b le m;
private
nd sfer a
x a n loop, create and initialize your pattern object.
le -the
3. AOutside t r asearch
non pattern = Pattern.compile("<h4>");
4. Inside the search loop, generate a Matcher based on the supplied Pattern object.
m = pattern.matcher(line);
5. Inside the search loop, search each line for the pattern supplied. Print the line number and
the line that has matching text.
if (m.find()) {
System.out.println(" " + c + " "+ line);
}
Assumptions
You have participated in the lecture for this lesson.
Summary
You have decided that you want to change the formatting of the gettys.html file. Instead of
using <p> tags, <span> tags should be used. In addition, you think that the value for class
should be “sentence” instead of “line.” Use regular expressions to find the lines that you want to
change. Then use regular expressions to transform the tags and the attributes as described.
The transformed lines should be output to the console. The output should look like the following:
13 <span class="sentence">Four score and seven years ago our
s a
fathers brought forth on this continent a new nation, conceived
) h a
in liberty, and dedicated to the proposition that all men are
c o m e ฺ
ฺ i d
cle t Gu
created equal.</span>
r a
14 <span class="sentence">Now we are engaged in a great civil
o n
@
war, testing whether that nation, or any nation, so conceived
e d e
and so dedicated, can long endure.</span>
t r a t S tu
r a ฺis this
15 <span class="sentence">We are met on a great battle-field of
that war.</span>
a n d use
e x to
16 <span class="sentence">We have come to dedicate a portion of
l
( a ns e
that field, as a final resting place for those who here gave
a t e c e
I s tr le li
their lives that that nation might live.</span>
ra erab
17 <span class="sentence">It is altogether fitting and proper
a n d
that we should do this.</span>
f
e x n s
21 <span class="sentence">But, in a larger sense, we can not
Al n-tradedicate, we can not consecrate, we can not hallow this
no ground.</span>
…
One approach to the problem could be to break the algorithm into three steps.
1. Break the line into three parts: the start tag, the content, and the end tag.
2. Replace the current tags with a new tag.
3. Replace the attribute value with a new attribute value.
Then return the newly formatted line.
The method signatures to replace the tag and attributes might look like this:
public String replaceTag(String tag, String targetTag,
String replaceTag){ }
public String replaceAttribute(String tag, String attribute,
String value){
Assumptions
You have participated in the lecture for this lesson.
Summary
You have decided that you want to change the formatting of the gettys.html file. Instead of
using <p> tags, <span> tags should be used. In addition, you think that the value for class
should be “sentence” instead of “line.” Use regular expressions to find the lines that you want to
change. Then use regular expressions to transform the tags and the attributes as described.
The transformed lines should be output to the console. The output should look like the following:
13 <span class="sentence">Four score and seven years ago our
s a
fathers brought forth on this continent a new nation, conceived
) h a
in liberty, and dedicated to the proposition that all men are
c o m e ฺ
created equal.</span> ฺ i d
r a cle t Gu
14 <span class="sentence">Now we are engaged in a great civil
o
war, testing whether that nation, or any nation, so conceived
@ e n
t e tu d
and so dedicated, can long endure.</span>
t r a S
r a ฺis this
15 <span class="sentence">We are met on a great battle-field of
that war.</span>
a n d use
x to
16 <span class="sentence">We have come to dedicate a portion of
l e
( a ns e
that field, as a final resting place for those who here gave
a t e c e
their lives that that nation might live.</span>
I s tr le li
17 <span class="sentence">It is altogether fitting and proper
d ra erab
that we should do this.</span>
n
x a n s f
21 <span class="sentence">But, in a larger sense, we can not
e
Al n-tradedicate, we can not consecrate, we can not hallow this
no ground.</span>
…
One approach to the problem could be to break the algorithm into three steps.
1. Break the line into three parts: the start tag, the content, and the end tag.
2. Replace the current tags with a new tag.
3. Replace the attribute value with a new attribute value.
Then return the newly formatted line.
The method signatures to replace the tag and attributes might look like this:
public String replaceTag(String tag, String targetTag,
String replaceTag){ }
public String replaceAttribute(String tag, String attribute,
String value){
Matcher m = pattern1.matcher(line);
s a
Execute the find() method to find a match. If there is a match, replace the
a
h and
) start
end tags. Replace the attribute c m
o ideฺ
ฺ
r a cle t Gu
if (m.find()) {
@ o e n
t e u d
ttargetTag,
String newStart = replaceTag(m.group(1),
t r a S
replaceTag);
r a ฺis this
n d use
newStart = replaceAttribute(newStart,
a
attribute, value);
l e x to
String newEnd = replaceTag(m.group(3), targetTag, replaceTag);
( a ns e
a t e i c e
s tr le= lnewStart
String newLine
I + m.group(2) + newEnd;
d ra erab
System.out.printf("%3d
n
%s\n", c, newLine);
x}a rans f
l e
A n-t
no a method that will replace the contents of any tag.
4. Create
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G9:u
Lesson
@ o e n
Exceptions t e and d
tu Assertions
t r a S
r a ฺis 9 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you will use try-catch statements, extend the Exception class, and use
the throw and throws keywords.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will create a new project and catch checked and unchecked exceptions.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Summary
You will create a project that reads from a file. The file-reading code will be provided to you.
Your task is to add the appropriate exception-handling code.
Tasks
1. Create a new ExceptionPractice project as the main project.
a. Select File > New Project. a
b. Select Java under Categories and Java Application under Projects. Click the Next a s
button. m )h
c. Enter the following information in the “Name and Location” dialog box: ฺ c o ideฺ
Project Name: ExceptionPractice r a cle t Gu
@ o e n
Project Location: D:\labs\09-Exceptions\practices.
t e tu d
t r a S
(checked) Set as Main Project r a ฺis this
(checked) Create Main Class: com.example.ExceptionMain
a n d use
d. Click the Finish button.
l e x to
2. ( a ns
Add the following line to the main method. e
a t e c e
s tr le li
System.out.println("Reading
I from file:" + args[0]);
ra eraargument
Note: A command-line
d b will be used to specify the file that will be read. Currently
a n
no arguments
x f
s be supplied, do not correct this oversight yet.
will
l e t r a n
3. ARun the-project. You should see an error message similar to:
o n
n Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at com.example.ExceptionMain.main(ExceptionMain.java:7)
Java Result: 1
4. Surround the println line of code you added with a try-catch statement.
The catch clause should:
Accept a parameter of type ArrayIndexOutOfBoundsException
Print the message: "No file specified, quitting!"
Exit the application with an exit status of 1 by using the appropriate static method
within the System class
Note: Because the compiler did not force you to handle or declare the
ArrayIndexOutOfBoundsException, it is an unchecked exception. Typically, you
should not need to use a try-catch block to deal with an unchecked exception.
Checking the length of the args array is an alternate way to ensure that a
command-line argument was supplied.
5. Run the project. You should see an error message similar to:
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will create a new project and catch checked and unchecked exceptions.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Summary
You will create a project that reads from a file. The file-reading code will be provided to you.
Your task is to add the appropriate exception-handling code.
Tasks
1. Create a new ExceptionPractice project as the main project.
a. Select File > New Project. a
b. Select Java under Categories and Java Application under Projects. Click the Next a s
button. m )h
c. Enter the following information in the “Name and Location” dialog box: ฺ c o ideฺ
Project Name: ExceptionPractice r a cle t Gu
@ o e n
Project Location: D:\labs\09-Exceptions\practices.
t e tu d
t r a S
(checked) Set as Main Project r a ฺis this
(checked) Create Main Class: com.example.ExceptionMain
a n d use
d. Click the Finish button.
l e x t o
2. ( a ns
Add the following line to the main method. e
a t e c e
s tr le li
System.out.println("Reading
I from file:" + args[0]);
ra eraargument
Note: A command-line
d b will be used to specify the file that will be read. Currently
a n
no arguments
x f
s be supplied; do not correct this oversight yet.
will
l e t r a n
3. ARun the-project. You should see an error message similar to:
o n
n Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at com.example.ExceptionMain.main(ExceptionMain.java:7)
Java Result: 1
try {
System.out.println("Reading from file:" + args[0]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No file specified, quitting!");
System.exit(1);
}
Note: Since the compiler did not force you to handle or declare the
ArrayIndexOutOfBoundsException it is an unchecked exception. Typically you
should not need to use a try-catch block to deal with an unchecked exception.
s a
Checking the length of the args array is an alternate way to ensure that a command
) h a
line argument was supplied.
c o m e ฺ
ฺ i d
5. Run the project. You should see an error message similar to:
r a cle t Gu
No file specified, quitting!
@ o e n
e d
rat is Stu
Java Result: 1
6. Add a command-line argument to the project.ฺist
a. Right-click the ExceptionPractice d r aproject and
e thclick Properties.
x n selectuthes Run category.
abox,
b. In the Project Properties dialog
a l e e to
c. In the Arguments field,
t e (enter a nvalue
s of:
a
tr le li c e
D:\labs\resources\DeclarationOfIndependence.txt
d. Click theaOK I sbutton.
7. Run the n d r You
project. f e ab see a message similar to:
rshould
e a
xReading n s
l -t r a
A file:D:\labs\resources\DeclarationOfIndependence.txt
from
n o n
Warning: Running the project is not the same as running the file. The command-line
argument will only be passed to the main method if you run the project.
8. Add the following lines of code to the main method below your previously added lines:
BufferedReader b =
new BufferedReader(new FileReader(args[0]));
String s = null;
while((s = b.readLine()) != null) {
System.out.println(s);
}
9. Run the Fix Imports wizard by right-clicking in the source-code window.
10. You should now see compiler errors in some of the lines that you just added. These lines
potentially generate checked exceptions. By manually building the project or holding your
cursor above the line with errors, you should see a message similar to:
unreported exception FileNotFoundException; must be caught or
declared to be thrown
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
12. Surround the file IO code provided in step 8 with a try-with-resources statement.
The line that creates and initializes the BufferedReader should be an automatically
closed resource.
Add a catch clause for a FileNotFoundException. Within the catch clause:
Print "File not found:" + args[0]
Exit the application.
Add a catch clause for an IOException. Within the catch clause:
Print " Error reading file:" along with the message available in the
IOException object
s a
Exit the application.
)h a
try (BufferedReader b =
c m
o {ideฺ
ฺ
new BufferedReader(new FileReader(args[0]));)
r a cle t Gu
String s = null;
@ o e n
e d
while((s = b.readLine()) != null)
System.out.println(s); str
at s Stu
{
r a ฺi
e t hi
}
x a nd e)us{
} catch(FileNotFoundException
a l e e tonot found:" + args[0]);
(
System.out.println("File
t e ns
a
tr le li
System.exit(1); c e
I s
a rab e) {
r
} catch(IOException
d
x n fe
an System.out.println("Error
s reading file:" + e.getMessage());
e ra
Al }n-tSystem.exit(1);
no
13. Run the project. You should see the content of the
D:\labs\resources\DeclarationOfIndependence.txt file displayed in the output
window.
Overview
In this practice, you will take an existing application and refactor the code to make use of a
custom exception class and a custom auto-closeable resource.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the exception handling section of this lesson.
Summary
You have been given a project that implements the logic for a human resources application. The
application allows for creating, retrieving, updating, deleting, and listing of Employee objects.
This is the same project that you completed in the “Applying the DAO Pattern” practice.
Currently the only exceptions generated by the DAO implementation
(EmployeeDAOMemoryImpl) are unchecked exceptions such as
s a
ArrayIndexOutOfBoundsException.
Future DAO implementations should not require any rewriting of the application logic ) h a
(EmployeeTestInteractive). However, some DAO implementations will generate checked
c o m e ฺ
ฺ i d
r a cle t Gu
exceptions that must be dealt with. By creating a custom checked exception class that will be
used to wrap any DAO generated exceptions, all DAO implementations can appear to generate
@ o e n
t e tu d
the same type of exception. This will completely eliminate the need to change any application
r a S
logic when you create database enabled DAO implementations in later practices.
t
r a ฺis this
Tasks
a n d use
1. Open the DAOException project l e xas the main
to project.
( a ns e
a e
a. Select File > OpentProject.
c e
s tr le li
b. Browse to D:\labs\09-Exceptions\practices.
I
c. Select d a rab and select the "Open as Main Project" check box.
rDAOException
n
a the nOpen
d.exClick s feProject button.
l
2. AExpand
n - traproject directories.
the
3. Runnothe project. You should see a menu. Test all the menu choices.
[C]reate | [R]ead | [U]pdate | [D]elete | [L]ist | [Q]uit:
4. Create a DAOException class in the com.example.dao package.
5. Complete the DAOException class. The DAOException class should:
Extend the Exception class
Contain four constructors with parameters matching those of the four constructors
present in the Exception class. For each constructor, use super() to invoke the
parent class constructor with matching parameters.
6. Modify the EmployeeDAO interface.
All methods should declare that a DAOException may be thrown during execution.
Extend the AutoCloseable interface.
7. Modify the add method within the EmployeeDAOMemoryImpl class to:
Declare that a DAOException may be produced during execution of this method.
Use an if statement to validate that an existing employee will not be overwritten by the
add. If one would, generate a DAOException and deliver it to the caller of the method.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
a n d use
Use an if statement to validate that an existing employee is being deleted. If one would
x to
not be, generate a DAOException and deliver it to the caller of the method. The
l e
( a e
DAOException should contain a message String indicating what went wrong and why.
ns
a t e c e
I s tr le li
Use a try-catch block to catch the ArrayIndexOutOfBoundsException
unchecked exception that could possibly be generated.
n d ra erab
Within the catch block that you just created, generate a DAOException and deliver it to
x a n s f
the caller of the method. The DAOException should contain a message String
e
Al n-tra
indicating what went wrong and why.
no
10. Modify the findById method within the EmployeeDAOMemoryImpl class to:
Declare that a DAOException may be produced during execution of this method.
Use a try-catch block to catch the ArrayIndexOutOfBoundsException
unchecked exception that could possibly be generated.
Within the catch block that you just created, generate a DAOException and deliver it to
the caller of the method. The DAOException should contain a message String
indicating what went wrong and why.
11. Add a close method within the EmployeeDAOMemoryImpl class to implement the
AutoCloseable interface.
@Override
public void close() {
System.out.println("No database connection to close just
yet");
}
Note: At this point the application will compile and run, but DAOException instances
generated will cause the application to terminate. For example, if you create an
employee with an ID of 100, the application will break out of the do-while loop and
pass to this catch clause.
e. Add a nested try-catch block in the main method that handles exceptions of type
DAOException that may be thrown by the executeMenu method.
try {
timeToQuit = executeMenu(in, dao);
} catch (DAOException e) {
System.out.println("Error " + e.getClass().getName());
System.out.println("Message: " + e.getMessage());
}
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will take an existing application and refactor the code to make use of a
custom exception class and a custom auto-closeable resource.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the exception handling section of this lesson.
Summary
You have been given a project that implements the logic for a human resources application. The
application allows for creating, retrieving, updating, deleting, and listing of Employee objects.
This is the same project that you completed in the “Applying the DAO Pattern” practice.
Currently the only exceptions generated by the DAO implementation
(EmployeeDAOMemoryImpl) are unchecked exceptions such as a
ArrayIndexOutOfBoundsException.
h a s
Future DAO implementations should not require any rewriting of the application logic m )
ฺ c
(EmployeeTestInteractive). However, some DAO implementations will generate checked o d e ฺ
cle t Gu i
exceptions that must be dealt with. By creating a custom-checked exception class that will be
o r a n
used to wrap any DAO generated exceptions, all DAO implementations can appear to generate
e @ d e
t r a t S tu
the same type of exception. This will completely eliminate the need to change any application
logic when you create database enabled DAO implementations in later practices.
r a ฺis this
Tasks a n d use
1. Open the DAOException project l e xas the main
to project.
( a ns e
a. Select File > Open a t e
Project.
c e
I s tr le li
b. Browse to D:\labs\09-Exceptions\practices.
d a rab and select the "Open as Main Project" check box.
rDAOException
c. Select
x n
a the nOpen s fe
A l
d. e Click
- t r a Project button.
on the project directories.
2. Expand
n
3. Run the project. You should see a menu. Test all the menu choices.
[C]reate | [R]ead | [U]pdate | [D]elete | [L]ist | [Q]uit:
4. Create a DAOException class in the com.example.dao package.
5. Complete the DAOException class. The DAOException class should:
Extend the Exception class.
Contain four constructors with parameters matching those of the four constructors
present in the Exception class. For each constructor, use super() to invoke the
parent class constructor with matching parameters.
public class DAOException extends Exception {
public DAOException() {
super();
}
}
}
Note: Checking the length of the employeeArray could be used to determine whether the
DAOException should be thrown however the use of a try-catch block will be typical of
the structure used when create a database enabled DAO.
8. Modify the update method within the EmployeeDAOMemoryImpl class to:
Declare that a DAOException may be produced during execution of this method.
Use an if statement to validate that an existing employee is being updated. If one would
not be, generate a DAOException and deliver it to the caller of the method. The
s a
DAOException should contain a message String indicating what went wrong and why.
Use a try-catch block to catch the ArrayIndexOutOfBoundsException )h a
unchecked exception that could possibly be generated.
c m
o ideฺ
ฺ
r a cle t Gu
Within the catch block that you just created, generate a DAOException and deliver it to
@ o
the caller of the method. The DAOException should contain a message String
e n
indicating what went wrong and why.
t e tu d
t r a S
public void update(Employee emp)
r a ฺ is this
throws DAOException {
a n d use== null) {
if(employeeArray[emp.getId()]
ex e to
throw new DAOException("Error
no such employee ("al+ emp.getId());
updating employee in DAO,
a t e c e ns
}
I s tr le li
rab
ra employeeArray[emp.getId()]
try {
a n d f e = emp;
x s
n (ArrayIndexOutOfBoundsException e) {
Ale n-t}racatch
noid must throw new DAOException("Error updating employee in DAO,
be less than " + employeeArray.length);
}
}
9. Modify the delete method within the EmployeeDAOMemoryImpl class to:
Declare that a DAOException may be produced during execution of this method.
Use an if statement to validate that an existing employee is being deleted. If one would
not be, generate a DAOException and deliver it to the caller of the method. The
DAOException should contain a message String indicating what went wrong and why.
Use a try-catch block to catch the ArrayIndexOutOfBoundsException
unchecked exception that could possibly be generated.
Within the catch block that you just created, generate a DAOException and deliver it to
the caller of the method. The DAOException should contain a message String
indicating what went wrong and why.
public void delete(int id) throws DAOException {
if(employeeArray[id] == null) {
} catch (ArrayIndexOutOfBoundsException e) {
throw new DAOException("Error deleting employee in DAO,
id must be less than " + employeeArray.length);
}
}
10. Modify the findById method within the EmployeeDAOMemoryImpl class to:
Declare that a DAOException may be produced during execution of this method.
Use a try-catch block to catch the ArrayIndexOutOfBoundsException
unchecked exception that could possibly be generated.
s a
a
Within the catch block that you just created, generate a DAOException and deliver it to
)h
the caller of the method. The DAOException should contain a message String
indicating what went wrong and why. c m
o ideฺ
ฺ
public Employee findById(int id) throws DAOException
r a cle t G{u
@ o e n
try {
return employeeArray[id];rat
e tu d
t S
r a ฺis this e) {
} catch (ArrayIndexOutOfBoundsException
a n d use finding employee in DAO",
throw new DAOException("Error
e); l e x to
( a ns e
}
a t e c e
}
I s tr le li
d
11. Add a closeramethod b the EmployeeDAOMemoryImpl class to implement the
rawithin
n f e
xa rans interface.
l e
AutoCloseable
-t
A @Override
o n
n public void close() {
System.out.println("No database connection to close just
yet");
}
Note: The EmployeeDAOMemoryImpl class implements EmployeeDAO which extends
AutoCloseable and, therefore, EmployeeDAOMemoryImpl class must provide a close
method.
12. Modify the EmployeeTestInteractive class to handle the DAOException objects that
are thrown by the EmployeeDAO.
a. Import the com.example.dao.DAOException class.
import com.example.dao.DAOException;
b. Modify the executeMenu method to declare that it throws an additional exception of
type DAOException.
public static boolean executeMenu(BufferedReader in, EmployeeDAO
dao) throws IOException, DAOException {
resources.
Add a catch clause for an IOException to the end of the try block to handle both
I/O errors thrown from the executeMenu method and when auto-closing the
BufferedReader.
Add a second catch clause for an Exception to the end of the try block to handle
errors when auto-closing the EmployeeDAO.
try (EmployeeDAO dao = factory.createEmployeeDAO();
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in))) {
s a
do { )h a
timeToQuit = executeMenu(in, dao);
c m
o ideฺ
ฺ
} while (!timeToQuit);
r a cle t Gu
} catch (IOException e) {
@ o e n
t e tu d
t r a
System.out.println("Error " + e.getClass().getName() +
S
" , quitting.");
r a ฺis this
n d use
System.out.println("Message: " + e.getMessage());
a
} catch (Exception e) { l e x to
( a ns e
t e e
System.out.println("Error closing resource " +
a c
I s tr le li
e.getClass().getName());
n d ra erab
System.out.println("Message: " + e.getMessage());
x a }
n s f
e
Al Note:- trAta this point, the application will compile and run, but DAOException instances
n
nogenerated will cause the application to terminate. For example, if you create an
employee with an ID of 100, the application will break out of the do-while loop and
pass to this catch clause.
e. Add a nested try-catch block in the main method that handles exceptions of type
DAOException that may be thrown by the executeMenu method.
try {
timeToQuit = executeMenu(in, dao);
} catch (DAOException e) {
System.out.println("Error " + e.getClass().getName());
System.out.println("Message: " + e.getMessage());
}
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
s a
)h a
c m
o ideฺ
ฺ
Practices for r a cle t G10:
Lesson
u
Java
@ o e n
r a t e Stud
I/O Fundamentals
r a ฺist 10 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you will use some of the java.io classes to read from the console, open and
read files, and serialize and deserialize objects to and from the file system.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will write a simple console-based application that reads from and writes to
the system console. In NetBeans, the console is opened as a window in the IDE.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Tasks
1. Open the project FileScanner in the following directory:
D:\labs\10-IO_Fundamentals\practices\
2. Open the file FileScanInteractive.
Notice that the class has a method called countTokens already written for you. This
method takes a String file and String search as parameters. The method will open the
file name passed in and use an instance of a Scanner to look for the search token. For
each token encountered, the method increments the integer field instanceCount. When
s a
h a
the file is exhausted, it returns the value of instanceCount. Note that the class rethrows
)
c o m
any IOException encountered, so you will need to be sure to use this method inside a
e ฺ
try-catch block. ฺ i d
3. r a cle t Gu
Code the main method to check the number of arguments passed. The application expects
@ o e n
at least one argument (a string representing the file to open). If the number of arguments is
t e tu d
t r a
less than one, exit the application with an error code (-1). S
r a ฺis this
a. The main method is passed an array of Strings. Use the length attribute to determine
n d use
whether the array contains less than one argument.
a
l e x to
b. Print a message if there is less than one argument, and use System.exit to return
( a ns e
an error code. (-1 typically is used to indicate an error.)
a t e c e
4. tr le li
Save the first argument passed into the application as a String.
I s
5. ra erab
Create an instance of the FileScanInteractive class. You will need this instance to
n d
a s f
call the countTokens method.
x n
6. Al
e - tra
Open the system console for input using a buffered reader.
no n
a. Use a try-with-resources to open a BufferedReader chained to the system console
input. (Recall that System.in is an input stream connected to the system console.)
b. Be sure to add a catch statement to the try block. Any exception returned will be an
IOException type.
c. In a while loop, read from the system console into a string until the string “q” is entered
on the console by itself.
Note: You can use equalsIgnoreCase to allow your users to enter an upper- or
lowercase “Q.”. Also the trim() method is a good choice to remove any whitespace
characters from the input.
d. If the string read from the console is not the terminate character, call the
countTokens method, passing in the file name and the search string.
e. Print a string indicating how many times the search token appeared in the file.
f. Add any missing import statements.
7. Save the FileScanInteractive class.
8. If you have no compilation errors, you can test your application by using a file from the
resources directory.
o r a n
e @ d e
t r a t S tu
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will write a simple console-based application that reads from and writes to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
the system console. In NetBeans, the console is opened as a window in the IDE.
Tasks
1. Open the project FileScanner in the following directory:
D:\labs\10-IO_Fundamentals\practices\
a. Select File > Open Project.
b. Browse to D:\labs\10-IO_Fundamentals\practices.
c. Select FileScanner and select the “Open as Main Project” check box.
d. Click the Open Project button.
s a
2. Open the file FileScanInteractive. a
) hThis
Notice that the class has a method called countTokens already written form you. ฺ the
method takes a String file and String search as parameters. Theemethod ฺ c o willidopen
e
file name passed in and use an instance of a Scanner to lookra
l
forcthe searchG utoken. For
each token encountered, the method increments the integer e t
ofield instanceCount.
n When
t e @ t u d
the file is exhausted, it returns the value of instanceCount.
any IOException encountered, so you will ฺneed i s trtoa be sure
i s StoNote
use
that the class rethrows
this method inside a
r a e t h
try-catch block.
x nd ofuarguments
anumber s
3. Code the main method to checkethe
a l e t o passed. The application expects
at least one argument (a string
t e ( n s
representing the file to open). If the number of arguments is
less than one, exit the
t raapplicationl e
ic with an error code (-1).
a. The main I s
athemethod l e
isbpassed an array of Strings. Use the length attribute to determine
d
whether
n r r a
e contains less than one argument.
array
x a s f
n if there is less than one argument, and use System.exit to return
Ab.le Print- taa
r message
non
an error code. (-1 typically is used to indicate an error.) For example:
if (args.length < 1) {
System.out.println("Usage: java FileScanInteractive <file to
search>");
System.exit(-1);
}
4. Save the first argument passed into the application as a String.
String file = args[0];
5. Create an instance of the FileScanInteractive class. You will need this instance to
call the countTokens method.
FileScanInteractive scan = new FileScanInteractive ();
try (BufferedReader in =
new BufferedReader(new InputStreamReader(System.in))) {
d. Click OK
e. Run the application and try searching for some words like when, rights, and free.
Your output should look something like this:
Searching through the file:
D:\labs\resources\DeclarationOfIndependence.txt
Enter the search string or q to exit: when
The word "when" appears 3 times in the file.
Enter the search string or q to exit: rights
s a
The word "rights" appears 3 times in the file.
Enter the search string or q to exit: free ) h a
c o m e ฺ
The word "free" appears 4 times in the file. ฺ i d
Enter the search string or q to exit: q
r a cle t Gu
@ o e n
BUILD SUCCESSFUL (total time: 16 seconds)
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you use the java.io.ObjectOutputStream class to write a Java object to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
the file system (serialize), and then use the same stream to read the file back into an object
reference. You will also customize the serialization and deserialization of the ShoppingCart
object.
Tasks
1. Open the SerializeShoppingCart project in the
D:\labs\10-IO_Fundamentals\practices directory.
2. Expand the com.example.test package. Notice there are two Java main classes in this
package, SerializeTest and DeserializeTest. You will be writing the code in these
main classes to serialize and deserialize ShoppingCart objects.
s a
3. Open the SerializeTest class. You will write the methods in this class to write
a
) hseveral
ShoppingCart objects to the file system.
c m
o ideฺ
a. Read through the code. You will note that the class prompts c
ฺ
lethe cartGIDuand
constructs an instance of ShoppingCart with the cart o afor
IDrin t
the constructor.
n
@
e Stud e
b. The code then adds three Item objects to the ShoppingCart.
r a t
c. The code then prints out the number of items
r a ฺ ist in the
t is and the total cost of the items
hcart,
n d us
in the cart. Look through the ShoppingCart e
and Item classes in the
com.example.domain package
e x a for details
t o on how these classes work.
d. You will be writing the (
l
a to open
code sean ObjectOutputStream and write the
t e e n
ShoppingCart
I s traas a lserialized
e lic object on the file system.
4. Create the try
d r b a FileOutputStream chained to an
ablock toraopen
x a n
ObjectOutputStream.
s f e The file name is already constructed for you.
Aa.b.le Open r
Your code
- t anwill go where the comment line is at the bottom of the file.
n on a FileOutputStream with the cartFile string in a try-with-resources block.
c. Pass the file output stream instance to an ObjectOutputStream to write the
serialized object instance to the file.
d. Write the cart object to the object output stream instance by using the writeObject
method.
e. Be sure to catch any IOException and exit with an error as necessary.
f. Add a success message before the method ends:
System.out.println ("Successfully serialized shopping cart with
ID: " + cart.getCartId());
g. Save the file.
5. Open the DeserializeTest class. The main method in this class reads from the console
for the ID of the customer shopping cart to deserialize.
6. Your code will go where the comment line is at the bottom of the file.
a. Open a FileOutputStream with the cartFile string in a try-with-resources block.
b. Pass the file output stream instance to an ObjectOutputStream to write the
serialized object instance to the file.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
x a n s f
a. To run the SerializeTest class, right-click the class name and select Run File.
e
Al n-tra
b. The output will look like this:
noEnter the ID of the cart file to create and serialize or q exit.
101
Shopping cart 101 contains 3 items
Shopping cart total: $58.39
Successfully serialized shopping cart with ID: 101
c. To run the DeserializeTest, right-click the class name and select Run File.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you use the java.io.ObjectOutputStream class to write a Java object to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
the file system (serialize), and then use the same stream to read the file back into an object
reference. You will also customize the serialization and deserialization of the ShoppingCart
object.
Tasks
1. Open the SerializeShoppingCart project in the
D:\labs\10-IO_Fundamentals\practices directory.
a. Select File > Open Project.
b. Browse to the D:\labs\10-IO_Fundamentals\practices directory.
c. Select the project SerializeShoppingCart. s a
)h a
d. Click the Open Project button.
2. Expand the com.example.test package. Notice there are two Javaฺmain c m
o classes e ฺin this
le theGcode
cwriting i d
u in these
package, SerializeTest and DeserializeTest. You will be a
o r n t
main classes to serialize and deserialize ShoppingCart objects.
e @ d e
3. Open the SerializeTest class. You will write the r a t
methods S intu
this class to write several
ShoppingCart objects to the file system. ฺis
t i s
d a e th
rthat
a. Read through the code. You will n
a note sclass prompts for the cart ID and
the
u
x o
le se t with the cart ID in the constructor.
constructs an instance of ShoppingCart
( a
b. The code then adds
t r a c enobjects to the ShoppingCart.
tethreeliItem
c. The code then
a s printsbout
ILook l the number of items in the cart, and the total cost of the items
e the
n d r
in the cart.
e ra package
through ShoppingCart and Item classes in the
x a s f
com.example.domain
n for details on how these classes work.
e
Ad.l You - rabe writing the code to open an ObjectOutputStream and write the
twill
n
noShoppingCart as a serialized object on the file system.
4. Create the try block to open a FileOutputStream chained to an
ObjectOutputStream. The file name is already constructed for you.
a. Your code will go where the comment line is at the bottom of the file.
b. Open a FileOutputStream with the cartFile string in a try-with-resources block.
c. Pass the file output stream instance to an ObjectOutputStream to write the
serialized object instance to the file.
d. Write the cart object to the object output stream instance by using the writeObject
method.
e. Be sure to catch any IOException and exit with an error as necessary.
t r a t lice
multi-catch expression.
s
I look
e. Your code should
a b lelike this:
r er a
nd(FileInputStream
x
try
a s f fis = new FileInputStream (cartFile);
Ale n-tcart an
rObjectInputStream in = new ObjectInputStream (fis)) {
System.out.println (item);
}
System.out.println ("Shopping cart total: " +
NumberFormat.getCurrencyInstance().format(cart.getCartTotal()));
g. Save the file.
7. Open the ShoppingCart class. You will customize the serialization and deserialization of
this class by adding the two methods called during serialization/deserialization.
a. Add a method invoked during serialization that will add a timestamp (Date object
instance) to the end of the object stream.
b. Add a method with the signature: s a
)h a
private void writeObject(ObjectOutputStream oos) throws
c m
o ideฺ
IOException { ฺ
le andGthen
u write the
c. Make sure that the method serializes the current object fields r a cfirst, t
Date object instance: @ o e n
t e tu d
oos.defaultWriteObject(); t r a S
oos.writeObject(new Date()); r a ฺis this
a n d use
}
l e x tothat is invoked during deserialization. This
(
8. Add a method to the ShoppingCarta e
class
nofs the shopping cart and print the timestamp that was
method will recalculatea t e
the e
totalccost
I s
added to the stream. tr le li
a. Add d
n ra ewith
a method
f rabthe signature:
e a
xprivate n s readObject(ObjectInputStream ois) throws
l -t r
A IOException,a void
n o n ClassNotFoundException {
b. This method will deserialize the fields from the object stream, and recalculate the total
dollar value of the current cart contents:
ois.defaultReadObject();
if (cartTotal == 0 && (items.size() > 0)) {
for (Item item : items)
cartTotal += item.getCost();
}
c. Get the Date object from the serialized stream and print the timestamp to the console.
Date date = (Date)ois.readObject();
System.out.println ("Restored Shopping Cart from: " +
DateFormat.getDateInstance().format(date));
}
d. Save the ShoppingCart.
n d ra erab
x a n s f
e
Al n-tra
no
s a
)h a
c m
o ideฺ
ฺ
Practices for r a cle t G11:
Lesson
u
Java
@ o e n
File I/O
r a t e(NIO.2)
S t ud
r a ฺist 11 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In the first practice, you will use the JDK 7 NIO.2 API to write an application to create custom
letters by merging a template letter with a list of names, utilizing Files and Path methods. In
the second practice, you will use the walkFileTree method to copy all the files and directories
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
from one folder to another on the disk. In the final optional practice, you will use the same
method to write an application to recursively find and delete all the files that match a supplied
pattern.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
letter. You will also use the Pattern and Matcher classes that you saw in the “String
Processing” lesson.
Assumptions
You participated in the lecture for this lesson. Note there are Netbeans projects in the example
directory to help you understand how to use the Files class readAllLines and write
methods.
Tasks
1. Open the file FormTemplate in the resources directory.
s a
a
Note that this is a form letter with a string <NAME> that will be replaced by a name from the
)h
name list file. m
2. Open the file NamesList.txt in the resources directory. ฺ c o ideฺ
a. This file contains the names to send the form letters to. r a cle t Gu
@ o e n
b. Add your name to the end of the list.
t e tu d
c. Save the file. t r a S
3. r a ฺis this
Open the project FormLetterWriter in the practices directory.
4. Expand the FormLetterWriterxclass. a ndNoticeuthat sethis class contains the main method, and
that the application requires(twoa leparameters:
e toOne is the path to the form letter template, and
the second is the pathato t e e ns the list of names to substitute in the form letter.
the file containing
c
I s r a valid
tfor e i
lnumber
a. After checking
r a a b l of arguments, the main method then checks to see
a n d fer
whether the Path objects point to valid files.
s
b. xThe mainnmethod creates an instance of the FileMerge class with the form letter
Ale Pathn - a and the list of names Path object.
trobject
o
c.n In a try block, the main method calls the writeMergedForm method of the
FileMerge class. This is the method that you will write in this practice.
5. Expand the FileMerge class.
a. Note the writeMergedForms method is empty. This is the method that you will write
in this practice.
b. The mergeName method uses the Pattern object defined in the field declarations to
replace the string from the form template (first argument) with a name from the name
list (second argument). It returns a String. For example, it replaces "Dear <NAME>,"
with "Dear Wilson Ball,".
c. The hasToken method returns a boolean to indicate whether the string passed in
contains the token. This is useful to identify which string has the token to replace with
the name from the name list.
6. Code the writeMergedForms method. The overall plan for this method is to read in the
entire form letter, line by line, and then read in the entire list of names and merge the
names with the form letter, replacing the placeholder in the template with a name from the
list and then writing that out as a file. The net result should be that if you have ten names in
c o m
from the nameList. Use the hasToken method to look for the String that contains the
e ฺ
ฺ d
token string and replace that string with one containing the name from the nameList.
i
a cle t Gu
Use the mergeName method to create the new String. Add the modified String and all
r
o e n
of the other Strings from the formLetter to the new customLetter List.
@
t e tu d
r a S
f. Still inside the first for loop, write the modified List of Strings that represents the
t
r a ฺis this
customized form letter to the file system by using the Files.write method. Print a
a n d use
message that the file write was successful and close the outer for loop.
g. Save the FileMerge class. l e x to
( a ns e
7.
a t e
Modify the FormLetterWriter project to pass the form letter file and the name list file to
c e
the main method.
I s tr le li
n d ra erab
a. Right-click the project and select Properties.
a s
b. Select Run.
x n f
e
Al n-tra
c. In the Arguments text field, enter: D:\labs\resources\FormTemplate.txt
no D:\labs\resources\NamesList.txt
d. Click OK.
s a
Good Luck!
) h a
c o m e ฺ
ฺ i d
cle t Gu
Oracle University
o r a n
e @ d e
t r a t S tu
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
letter. You will also use the Pattern and Matcher classes that you saw in the “String
Processing” lesson.
Assumptions
You participated in the lecture for this lesson. Note there are Netbeans projects in the example
directory to help you understand how to use the Files class readAllLines and write
methods.
Tasks
1. Open the file FormTemplate in the resources directory. a
a. Select File > Open File a s
m )h
b. Navigate to the resources directory in D:\labs
ฺ c o ideฺ
c. Select the file FormTemplate.txt and click the Open button.
r a cle t Gu
Note that this is a form letter with a string placeholder tokeno n will be replaced
<NAME> that
e @ d e
by a name from the name list file.
t r a t S tu
2. Open the file NamesList.txt in the resources
r a ฺis this
directory.
a. This file contains the names to send
n d form
the
u e to.
sletters
b. Add your name to the end e of x a
the list. to
c. Save the file. ( a l se
t e e n
I tra le lic
3. Open the projectsFormLetterWriter in the practices directory.
n d a > Open
a. Select rFile
f e rabProject.
a tonD:\labs\11-NIO.2\practices.
b. xBrowse
e s
l r a
-t FormLetterWriter.
Ac. Select
o n
d.n Select the “Open as Main Project” check box.
e. Click the Open Project button.
4. Expand the FormLetterWriter class. Notice that this class contains the main method,
and that the application requires two parameters: One is the path to the form letter
template, and the second is the path to the file containing the list of names to substitute in
the form letter.
a. After checking for a valid number of arguments, the main method then checks to see
whether the Path objects point to valid files.
b. The main method creates an instance of the FileMerge class with the form letter
Path object and the list of names Path object.
c. In a try block, the main method calls the writeMergedForm method of the
FileMerge class. This is the method that you will write in this practice.
5. Expand the FileMerge class.
a. Note the writeMergedForms method is empty. This is the method that you will write
in this practice.
nowayn-inside the for loop, you need to create a name for the custom letter. One easy
to do this is to use the name from the name list. You should replace any spaces in
the name with underscores for readability of the file name. Create a new Path object
relative to the form template path.
String formName = nameList.get(j).replace(' ',
'_').concat(".txt");
Path formOut = form.getParent().resolve(formName);
customLetter List.
for (int k = 0; k < formLetter.size(); k++) {
if (hasToken(formLetter.get(k))) {
customLetter.add(mergeName(formLetter.get(k),
nameList.get(j)));
} else {
customLetter.add(formLetter.get(k));
}
} s a
g. Finally, still inside the first for loop, write the modified List of Strings )that h a
represents the customized form letter to the file system by using the c m
oFiles.writee ฺ
ฺ i d
method. Print a message that the file write was successful and
r a clecloset the
G uouter for loop.
Files.write(formOut, customLetter, cs);
@ o e n
e
tletterStto: d
u "+
System.out.println ("Wrote form
t r a
nameList.get(j));
aฺis for is
thloop
} // closing brace for thedouter r s e
e x anyou thave
o ueverything
h. Reformat the code to ensure
Alt-F key combination (
ora l that
s
right-click e
in the editor pane
in the right place. Press the Ctrl-
and choose Format.
a t e c e n
i. Save the FileMerge
I s tr leclass.li
n d ra erab
7. Modify the FormLetterWriter project to pass the form letter file and the name list file to
a
the main method.
xRight-click
n s f
l e r a
A n-t the project and select Properties.
a.
b.no Select Run.
c. In the Arguments text field, enter: D:\labs\resources\FormTemplate.txt
D:\labs\resources\NamesList.txt
d. Click OK.
s a
Good Luck!
) h a
c o m e ฺ
ฺ i d
cle t Gu
Oracle University
o r a n
e @ d e
t r a t S tu
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you write Java classes that use the FileVisitor class to recursively copy one
directory to another.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You participated in the lecture for this lesson.
Tasks
1. Open the project RecursiveCopyExercise in the directory D:\labs\11-
NIO.2\practices.
2. Expand the Source Packages folder and subfolders and look at the Copy.java class.
a. Note that the Copy.java class contains the main method.
b. The application takes two arguments, a source and target paths. s a
)h a
c. If the target file or directory exists, the user is prompted whether to overwrite.
c m
o ideฺ
d. If the answer is yes (or the letter y), the method continues. ฺ
e. a cle t Gu
An instance of the CopyFileTree class is created with the source and target.
r
@ o e n
f.
t e tu d
This instance is then passed to the walkFileTree method (with the source Path
object). t r a S
a ฺis this
You will need to provide method bodies for the methods in the CopyFileTree.java
r
class. a n d use
3. Open the CopyFileTree.java class. l e x to
a e
(the FileVisitor
ns
a. This class implements
r a t e i c e interface. Note that FileVisitor is a
I s
generic interface,t and l e l
this interface is boxed with the Path class. This allows the
r
interface a
d to define b
rathe type of the arguments passed to its methods.
a n s
b. xThe CopyFileTree f e implements all the methods defined by FileVisitor.
n
Ac.le Your t r a
n- task You
is to write method bodies for the preVisitDirectory and visitFile
nomethods. will not need the postVisitDirectory method, and you have been
provided a method body for the visitFileFailed method.
4. Write the method body for preVisitDirectory. This method is called for the starting
node of the tree and every subdirectory. Therefore, you should copy the directory of the
source to the target. If the file already exists, you can ignore that exception (because you
are doing the copy because the user elected to overwrite.)
a. Start by creating a new directory that is relative to the target passed in, but is the node
name from the source. The method call to do this is:
Path newdir = target.resolve(source.relativize(dir));
b. In a try block, copy the directory passed to the preVisitDirectory method to the
newdir that you created.
c. You can ignore any FileAlreadyExistsException thrown, because you are
overwriting any existing folders and files in this copy.
d. Catch any other IOExceptions, and use the SKIP_SUBTREE return to avoid
repeated errors.
Overview
In this practice, you write Java classes that use the FileVisitor class to recursively copy one
directory to another.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You participated in the lecture for this lesson.
Tasks
1. Open the project RecursiveCopyExercise in the directory D:\labs\11-
NIO.2\practices.
a. Select File > Open Project.
b. Browse to D:\labs\11-NIO.2\practices.
c. Select RecursiveCopyExercise. s a
d. Select the “Open as Main Project” check box. )h a
e. Click the Open Project button. c m
o ideฺ
ฺ
2. Expand the Source Packages folder and subfolders and look atathe
r cleCopy.java
t G u class.
a. Note that the Copy.java class contains the main method. @ o e n
e d
tu paths.
tand target
b. The application takes two arguments, a source t r a S
c. If the target file or directory exists, thera user
e his whether to overwrite.
ฺisis prompted
t
d. If the answer is yes (or the letter
x a ny),dthe method
us continues.
e t o
al nseclass is created with the source and target.
e. An instance of the CopyFileTree
e (
s t at passed
f. This instance isrthen l i ceto the walkFileTree method (with the source Path
object).
r a I
a b le
x a s f er method bodies for the methods in the CopyFileTree.java
d to provide
You willnneed
le -tran
class.
3. AOpen n
n o the CopyFileTree.java class.
a. This class implements the FileVisitor interface. Note that FileVisitor is a
generic interface, and this interface is boxed with the Path class. This allows the
interface to define the type of the arguments passed to its methods.
b. The CopyFileTree implements all the methods defined by FileVisitor.
c. Your task is to write method bodies for the preVisitDirectory and visitFile
methods. You will not need the postVisitDirectory method, and you have been
provided a method body for the visitFileFailed method.
on newdir
b.n As in the preVisitDirectory method, use the Files.copy method in a try block.
Make sure that you pass REPLACE_EXISTING in as an option to overwrite any existing
file in the directory.
try {
Files.copy(file, newdir, REPLACE_EXISTING);
Note: To use the REPLACE_EXISTING enum type, you must import the
java.nio.file.StandardCopyOption enum class using a static import, like this:
import static java.nio.file.StandardCopyOption.*;
c. Catch any IOException thrown and report an error.
} catch (IOException x) {
System.err.format("Unable to copy: %s: %s%n", source, x);
}
d. Fix any missing imports.
e. Save your class.
D:\labs\11-NIO.2 D:\Temp
d. Click OK.
7. Run the project and you should see the following message:
Successfully copied D:\labs\11-NIO.2 to D:\Temp
a. Run the project again, and you should be prompted:
Target directory exists. Overwrite existing files? (yes/no):
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Assumptions
You have completed the previous practice.
Tasks
1. Open the project RecursiveDeleteExercise in the practices directory.
2. Expand the Source Packages folders.
3. Open the Delete.java class file. This is the class that contains the main method. The
main class accepts two arguments: the first is the starting path and the other the pattern to
delete. s a
)h a
4. You must code the remainder of this class. Look at the comments for hints as to what to do.
c m
o ideฺ
ฺ
a. Start by creating a PathMatcher object from the search string passed in as the
a cle t Gu
second argument. To obtain a PathMatcher instance, you will need to use the
r
o e n
FileSystems class to get a path matcher instance from the default file system.
@
t e tu d
b. Create a Path object from the first argument.
t r a S
c. If the starting path is a file, check it against
r a e hisusing the PathMatcher
ฺisthe pattern
t
instance that you created. If therenis
a da match,u sdelete the file, and then terminate the
application. x
le se t o
( a
d. If the starting path tisea directory,
t
starting directoryr a i c encreate anobject
and the lPathMatcher
instance of the DeleteFileTree with the
as initial arguments in the constructor.
Pass the
I
a rabs
starting l e
directory and the file tree to a method to
d r Files.walkFileTree
x an nslook
recursively fe for the pattern to delete.
e tramissing imports.
Ae.l Fixn-any
f. o Save the Delete class.
n
5. Open the DeleteFileTree class file. This class implements FileVisitor. This class
recursively looks for instances of files or directories that match the PathMatcher object
passed into the constructor. This class is complete with the exception of the delete
method.
a. The delete method is called by the preVisitDirectory and visitFile methods.
You must check whether the file or directory reached by these methods matches the
pattern.
b. We only want to match the path name at the node, so use the Path.getFileName
method to obtain the file name at the end of the full path.
c. If the name matches, use the Files.delete method to attempt to delete the file
pattern and print a result statement, or print an error if an IOException is thrown.
d. Save the DeleteFileTree class.
6. Run the Delete application using a temporary directory.
a. For example, if you completed the first practice, you can delete all the Java class files
from the D:\Temp directory.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you write a Java main that creates a PathMatcher class and uses
FileVisitor to recursively delete a file or directory pattern.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have completed the previous practice.
Tasks
1. Open the project RecursiveDeleteExercise in the practices directory.
a. Select File > Open Project.
b. Browse to D:\labs\11-NIO.2\practices.
c. Select RecursiveDeleteExercise. s a
) h a
d. Click the Open Project button.
c o m e ฺ
2. Expand the Source Packages folders. ฺ i d
3. a cle t Gu
Open the Delete.java class file. This is the class that contains the main method. The
r
o e n
main class accepts two arguments: the first is the starting path and the other the pattern to
@
t e tu d
delete.
t r a S
4. ฺis this
You must code the remainder of this class. Look at the comments for hints as to what to do.
r a
n d use
a. Start by creating a PathMatcher object from the search string passed in as the
a
l e x to
second argument. To obtain a PathMatcher instance, you will need to use the
( a ns e
FileSystems class to get a path matcher instance from the default file system.
a t e c e
s tr le li
PathMatcher matcher =
I
n d ra erab
FileSystems.getDefault().getPathMatcher("glob:" + args[1]);
x a n s f
b. Create a Path object from the first argument.
e
Al n-tra
Path root = Paths.get(args[0]);
no
x}an
s fe
catch (IOException
n
e) {
e ra
Al }n-tSystem.out.println("Exception: " + e);
no
e. Fix any missing imports.
f. Save the Delete class.
5. Open the DeleteFileTree class file. This class implements FileVisitor. This class
recursively looks for instances of files or directories that match the PathMatcher object
passed into the constructor. This class is complete with the exception of the delete
method.
a. The delete method is called by the preVisitDirectory and visitFile methods.
You must check whether the file or directory reached by these methods matches the
pattern.
b. We only want to match the path name at the node, so use the Path.getFileName
method to obtain the file name at the end of the full path.
Path name = file.getFileName();
Files.delete(file);
System.out.println("Deleted: " + file);
} catch (IOException e) {
System.err.println("Unable to delete: " + name);
System.err.println("Exception: " + e);
}
}
d. Save the DeleteFileTree class.
6. Run the Delete application using a temporary directory. s a
) h a
a. For example, if you completed the first practice, you can delete all the Java class files
from the D:\Temp directory. c o m e ฺ
ฺ i d
b. Right-click the project and select Properties.
r a cle t Gu
o
c. Click Run and enter the following in the Arguments text field:
@ e n
t e tu d
D:\Temp\examples *.class
t r a S
d. Run the project.
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G12:
Lesson
u
@ o e n
Threading t e tu d
t r a S
r a ฺis 12 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you will use the multithreaded features of the Java programming language.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will add code to an existing application. You must determine whether the
code is run in a multithreaded environment, and, if so, make it thread-safe.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the sections covering the use of the Thread class and the synchronized
keyword of this lesson.
Summary
You will open a project that purchases shirts from a store. The file-reading code will be provided
to you. Your task is to add the appropriate exception handling code.
Tasks
1. Open the project Synchronized as the main project. s a
a. Select File > Open Project. ) h a
c o m e ฺ
b. Browse to D:\labs\12-Threading\practices. ฺ i d
a cle t Gu
c. Select Synchronized and select the "Open as Main Project" check box.
r
@ o e n
d. Click the Open Project button.
t e tu d
2. t r a S
Expand the project directories but avoid opening and review the provided classes at this
a ฺis this
point. You will attempt to discover whether this application is multithreaded by observing the
r
behavior of code that you provide.
a n d use
3. l e x to
Create a PurchasingAgent class in the com.example package.
( a ns e
4. t e
Complete the PurchasingAgent class.
a c e
s tr le li
a. Add a purchase method.
I
n d
public
f ab
ravoiderpurchase() {}
a s
x ranthe purchase method. The purchase() method should:
Ab.le Complete
n -t a Store reference. Note that the Store class implements the Singleton
Obtain
o
n design pattern.
Store store = Store.getInstance();
store.authorizeCreditCard("1234", 15.00)
If there are shirts in stock and the credit card purchase was authorized, you should
take a shirt from the store.
Shirt shirt = store.takeShirt();
Print out the shirt and a success message if a shirt was acquired or a failure
message if one was not.
5. Run the project multiple times. Note that the store contains only a single shirt. You can see
many possible variations of output. You might see:
Two success messages and two shirts (output may appear in varying order) s a
Two success messages, one shirt, and one null ) h a
Two success messages, one shirt, and one exception c o m e ฺ
ฺ i d
r a cle t Gu
One success message, one shirt, and one failure message (desired behavior, but least
likely)
@ o e n
6. Discover how the PurchasingAgent class is being used.t e tu d
t r a S
r a ฺis this
a. Use a constructor and a print statement to discover how many instances of the
a n d use
PurchasingAgent class are being created when running the application.
x to
Reminder: Sometimes objects are created per-request and sometimes an object may
l e
( a ns e
be shared by multiple requests. The variations in the model affect which code must be
thread-safe. a t e c e
I s tr le li
b. Within the purchase method use the Thread.currentThread() method to obtain
d ra erab
a reference to the thread currently executing the purchase() method. Use a single
n
x a s f
print statement to print the name and ID of the executing thread.
n
e
Al n-tra
c. Run the project and observe the output.
7. no
Open the Store class and add a delay to the authorizeCreditCard method.
Obtain a random number in the range of 1–3, the number of seconds to delay. Print a
message indicating how many seconds execution will be delayed.
int seconds = (int) (Math.random() * 3 + 1);
Use the appropriate static method in the Thread class to delay execution for 1 to 3
seconds.
Optional Task: What if your delay is interrupted? How can you be sure that execution is
delayed for the desired number of seconds? Or should a different action be taken?
8. Run the project multiple times. You should see a stack trace for a
java.util.NoSuchElementException. Locate the line within the
com.example.PurchasingAgent.purchase method that is displayed in the stack
trace. Review the action occurring on that line.
9. Use a synchronized code block to create predictable behavior.
Modify the purchase method in the PurchasingAgent class to contain a
synchronized code block.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will add code to an existing application. You must determine whether the
code is run in a multithreaded environment, and, if so, make it thread-safe.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the sections covering the use of the Thread class and the synchronized
keyword of this lesson.
Summary
You will open a project that purchases shirts from a store. The file-reading code will be provided
to you. Your task is to add the appropriate exception handling code.
Tasks
1. Open the project Synchronized as the main project. s a
a. Select File > Open Project. ) h a
c o m e ฺ
b. Browse to D:\labs\12-Threading\practices. ฺ i d
a cle t Gu
c. Select Synchronized and select the "Open as Main Project" check box.
r
@ o e n
d. Click the Open Project button.
t e tu d
2. t r a S
Expand the project directories but avoid opening and review the provided classes at this
a ฺis this
point. You will attempt to discover whether this application is multithreaded by observing the
r
behavior of code that you provide.
a n d use
3. l e x to
Create a PurchasingAgent class in the com.example package.
( a ns e
4. t e
Complete the PurchasingAgent class.
a c e
s tr le li
a. Add a purchase method. The purchase() method should:
I
d ra erab
Obtain a Store reference. Note that the Store class implements the Singleton
n
x a s f
design pattern.
n
e
Al n-tra
Buy a Shirt.
no Verify that the store has at least one shirt in stock.
Use the store to authorize a credit card purchase. Use a credit card account
number of "1234" and a purchase amount of 15.00. A boolean result is returned.
If there are shirts in stock and the credit card purchase was authorized, you should
take a shirt from the store.
Print out the shirt and a success message if a shirt was acquired or a failure
message if one was not.
store.authorizeCreditCard("1234", 15.00)) {
Shirt shirt = store.takeShirt();
System.out.println("The shirt is ours!");
System.out.println(shirt);
} else {
System.out.println("No shirt for you");
}
}
}
s a
5. h a
Run the project multiple times. Note that the store contains only a single shirt. You can see
)
many possible variations of output. You might see:
c o m e ฺ
ฺ i d
r a cle t Gu
Two success messages and two shirts (output may appear in varying order)
Adding a shirt to the store.
@ o e n
Total shirts in stock: 1 t e tu d
t r a S
The shirt is ours!
r a ฺis this
The shirt is ours!
a n d use
Shirt ID: 1
Description: Polo(a
lex se to
t
Color: Rainbowr a te licen
Size:ra Is ble
d fera
Large
a n
xShirtraID:s
l e n
A n-t 1
noDescription:
Color: Rainbow
Polo
Size: Large
Two success messages, one shirt, and one null
Adding a shirt to the store.
Total shirts in stock: 1
The shirt is ours!
The shirt is ours!
null
Shirt ID: 1
Description: Polo
Color: Rainbow
Size: Large
Two success messages, one shirt, and one exception
Adding a shirt to the store.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Size: Large
Exception in thread "Thread-0" java.util.NoSuchElementException
One success message, one shirt, and one failure message (desired behavior but least
likely)
Adding a shirt to the store.
Total shirts in stock: 1
The shirt is ours!
Shirt ID: 1
Description: Polo
s a
Color: Rainbow
)h a
Size: Large
c m
o ideฺ
ฺ
r a cle t Gu
No shirt for you
@ o e n
6. Discover how the PurchasingAgent class is being e
tused. Stu d
t r a
ฺis thand
a. In the PurchasingAgent class, use a constructor
a is a print statement to discover
how many instance of the PurchasingAgent
n r
d us e class are being created when running
the application.
e x a to
( a l e
a t e
public PurchasingAgent()
c e ns{
s tr le li
System.out.println("Creating
I a purchasing agent");
}
n d ra erab
x a
Reminder:
n s f
Sometimes objects are created per-request and sometimes an object may
l e be t r
shared
A thread-safe.
- a by multiple requests. The variations in the model affect which code must be
no n
b. Within the purchase method use the Thread.currentThread() method to obtain
a reference to the thread currently executing the purchase() method. Use a single
print statement to print the name and ID of the executing thread.
Thread t = Thread.currentThread();
System.out.println("Thread:" + t.getName() + "," + t.getId());
c. Run the project and observe the output.
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
8. Run the project multiple times. You should see a stack trace for a
java.util.NoSuchElementException. Locate the line within the
com.example.PurchasingAgent.purchase method that is displayed in the stack
trace. The exception is being generated by the call to store.takeShirt().
Note: The delay introduced in the previous step makes it more likely that concurrent
s a
PurchasingAgent.purchase methods calls will both believe that a shirt can be taken
) h a
but take the shirt at a different time. Taking the shirt at the near the same time typically
results in some of the other errors shown in step 5. c o m e ฺ
ฺ i d
9. Use a synchronized code block to create predictable behavior.
r a cle t Gu
o e n
Modify the purchase method in the PurchasingAgent class to contain a
@
synchronized code block. t e tu d
t r a S
synchronized (store) {
r a ฺis this
if (store.getShirtCount()
a n d >u0se&&
l e x
store.authorizeCreditCard("1234", to 15.00)) {
a e
( = store.takeShirt();
n s
Shirt shirt
a t e c e
I s tr le li
System.out.println("The shirt is ours!");
n d raelse e{rab
System.out.println(shirt);
x a }
n s f
e
Al n-t}ra System.out.println("No shirt for you");
no}
Note: Adding synchronized to the method signature or using a synchronized
block that uses the this object’s monitor will not work.
10. Run the project. You should now see the desired behavior. In the output window, you
should see one success message, one shirt, and one failure message.
Adding a shirt to the store.
Total shirts in stock: 1
The shirt is ours!
Shirt ID: 1
Description: Polo
Color: Rainbow
Size: Large
Overview
In this practice, you will create a new project and start a new thread.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
You have reviewed the sections covering the use of the Thread class.
Summary
You will create a project that slowly prints an incrementing number. A new thread will be used to
increment and print the number. The application should wait for Enter to be pressed before
interrupting any threads.
Tasks
1. Create a new project ThreadInterrupted as the main project. a
a. Select File > New Project. h a s
m )
b. Select Java under Categories and Java Application under Projects. Click the Next
ฺ c o d e ฺ
button.
cle t Gu i
r a
c. Enter the following information in the “Name and Location” dialog box:
o n
Project Name: ThreadInterrupted e @ d e
t r a t
Project Location: D:\labs\12-Threading\practices. S tu
r a ฺis this
(checked) Create Main Class: com.example.ThreadInterruptedMain
a n d use
l e x
(checked) Set as Main Project
to
(
d. Click the Finish button.a ns e
a t e c e
2. tr le li
Create a Counter class in the com.example package.
I s
3. ra erab
Complete the Counter class. The Counter class should:
n d
x n s f
Implement the Runnable interface.
a
e
Al n-tra
Within the run method:
no Create an int variable called x and initialize it to zero.
Construct a loop that will repeat until the executing thread is interrupted.
Within the loop, print and increment the value of x.
Within the loop, delay for 1 second. Return from the run method or exit the loop if the
thread is interrupted while delayed.
4. Add the following to the main method in the ThreadInterruptedMain class:
Create a Counter instance.
Create a thread and pass to its constructor the runnable Counter.
Start the thread.
5. Run the project. You should see an incrementing sequence of numbers with a one second
delay between each number. Notice that while the main method has completed the
application continues to run.
6. Stop the project.
a. Open the Run menu.
b. Click Stop Build/Run.
InputStreamReader(System.in))) {
br.readLine();
} catch (IOException e) {}
Note: You may need to fix your imports and update the project properties to support
JDK 7 features.
Print out a message indicating whether or not the thread is alive.
Interrupt the thread.
Delay for one second (to allow the thread time to complete) and then print out a
message indicating whether or not the thread is alive. s a
8. ) h a
Run the project. You should see an incrementing sequence of numbers with a one second
o m ฺ
delay between each number. Press Enter while the output window is selected to gracefully
c e
ฺ i d
terminate the application.
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will create a new project and start a new thread.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
You have reviewed the sections covering the use of the Thread class.
Summary
You will create a project that slowly prints an incrementing number. A new thread will be used to
increment and print the number. The application should wait for Enter to be pressed before
interrupting any threads.
Tasks
1. Create a new project ThreadInterrupted as the main project.
s a
a. Select File > New Project.
) h a
b. Select Java under Categories and Java Application under Projects. Click the Next
m
button. ฺ c o d e ฺ
cle t Gu i
o r a
c. Enter the following information in the “Name and Location” dialog box:
n
Project Name: ThreadInterrupted
e @ d e
Project Location: D:\labs\12-Threading\practices. t r a t S tu
r a ฺis this
(checked) Create Main Class: com.example.ThreadInterruptedMain
(checked) Set as Main Project a n d use
d. Click the Finish button.(al
ex e to
2. Create a Counter r a t
class e ns
ein theiccom.example package.
I s
3. Complete theaCounter b
t l e l
class. The Counter class should:
n d r e r a
Implement
x a the
s fRunnable interface.
AleWithin
- tthe
r anrun method:
nonConstruct
Create an int variable called x and initialize it to zero.
a loop that will repeat until the executing thread is interrupted.
Within the loop, print and increment the value of x.
Within the loop, delay for 1 second. Return from the run method or exit the loop if the
thread is interrupted while delayed.
} catch (InterruptedException e) {
return;
}
}
4. Add the following to the main method in the ThreadInterruptedMain class:
Create a Counter instance.
Create a thread and pass to its constructor the runnable Counter.
Start the thread.
Runnable r = new Counter(); s a
Thread t = new Thread(r); )h a
c m
o ideฺ
t.start(); ฺ
a cle with
5. Run the project. You should see an incrementing sequence ofrnumbers
t Gauone second
delay between each number. Notice that while the main method
@ o hasecompleted
n the
application continues to run. t e t u d
i s t ra is S
6. Stop the project.
d r aฺ e th
a. Open the Run menu.
b. Click Stop Build/Run. e x an to us
Note: You can also stop ea ( al nbysclicking
build/run
e the red square along the left side of the
output window. tra
t lic e
I s l e
n d f r ab to support the try-with-resources statement.
ra eproperties
7. Modify the project
a
a. xRight-click
e n sthe ThreadInterrupted project and click Properties.
l r a
-t Project Properties dialog box select the Sources category.
Ab. Innthe
o
c.n In the Source/Binary Format drop-down list select JDK 7.
d. Click the OK button.
8. Modify the main method in the ThreadInterruptedMain class.
After starting the thread, wait for Enter to be pressed in the output window. You can use
the following code:
try(BufferedReader br = new BufferedReader(new
InputStreamReader(System.in))) {
br.readLine();
} catch (IOException e) {}
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G13:
Lesson
u
@ o e n
Concurrency t e tu d
t r a S
r a ฺis 13 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you will use the java.util.concurrent package and sub-packages of
the Java programming language.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will modify an existing project to use an ExecutorService from the
java.util.concurrent package.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have reviewed the sections covering the use of the java.util.concurrent package.
Summary
You will create a multithread networking client that will rapidly read the price of a shirt from
several different servers. Instead of manually creating threads, you will leverage an
ExecutorService from the java.util.concurrent package.
Tasks
1. Open the ExecutorService project as the main project. s a
) h a
a. Select File > Open Project.
c o m e ฺ
b. Browse to D:\labs\13-Concurrency\practices. ฺ i d
r a cle t Gu
c. Select ExecutorService and select the "Open as Main Project" check box.
@ o e n
d. Click the Open Project button.
t e tu d
2. Expand the project directories. t r a S
3. r a ฺis this
Run the NetworkServerMain class in the com.example.server package by
a n d use
right-clicking the class and selecting Run File.
l e x to
4. a e
Open the NetworkClientMain class in the com.example.client package.
( ns
5. t e e
Run the NetworkClientMain class package by right-clicking the class and selecting Run
a c
I s tr le li
File. Notice the amount of time it takes to query all the servers sequentially.
6. d ra erab
Create a NetworkClientCallable class in the com.example.client package.
n
x a n s f
Add a constructor and a field to receive and store a RequestResponse reference.
e
Al n-tra
Implement the Callable interface with a generic type of RequestResponse.
nopublic class NetworkClientCallable implements
Callable<RequestResponse>
Complete the call method by using a java.net.Socket and a
java.util.Scanner to read the response from the server. Store the result in the
RequestResponse object and return it.
Note: You may want to use a try-with-resource statement to ensure that the
Socket and Scanner objects are closed.
7. Modify the main method of the NetworkClientMain class to query the servers
concurrently by using an ExecutorService.
a. Comment out the contents of the main method.
b. Obtain an ExecutorService that reuses a pool of cached threads.
c. Create a Map that will be used to tie a request to a future response.
Map<RequestResponse, Future<RequestResponse>> callables = new
HashMap<>();
d. Code a loop that will create a NetworkClientCallable for each network request.
servers’ response or an error message with the server details if there was a problem
communicating with a server.
8. Run the NetworkClientMain class by right-clicking the class and selecting Run File.
Notice the amount of time it takes to query all the servers concurrently.
9. When done testing your client, be sure to select the ExecutorService output tab and
terminate the server application.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will modify an existing project to use the Fork-Join framework.
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
You have reviewed the sections covering the use of the Fork-Join framework.
Summary
You are given an existing project that already leverages the Fork-Join framework to process the
data contained within an array. Before the array is processed, it is initialized with random
numbers. Currently the initialization is single-thread. You must use the Fork-Join framework to
initialize the array with random numbers.
Tasks
1. Open the ForkJoinFindMax project as the main project. s a
a. Select File > Open Project. ) h a
c o m e ฺ
b. Browse to D:\labs\13-Concurrency\practices. ฺ i d
a cle t Gu
c. Select ForkJoinFindMax and select the "Open as Main Project" check box.
r
@ o e n
d. Click the Open Project button.
t e tu d
2. Expand the project directories. t r a S
3. r a ฺis this
Open the Main class in the com.example package.
a n d use
Review the code within the main method. Take note of how the compute method splits
l e x to
a e
the data array if the count of elements to process is too great.
( ns
3. a t e e
Open the FindMaxTask class in the com.example package.
c
I s tr le li
Review the code within the class. Take note of the for loop used to initialize the data
d ra erab
array with random numbers.
n
4. lex
a n s f
Create a RandomArrayAction class in the com.example package.
A n-tra
a. Add four fields.
noprivate final int threshold;
private final int[] myArray;
private int start;
private int end;
b. Add a constructor that receives parameters and saves their values within the fields
defined in the previous step.
public RandomArrayAction(int[] myArray, int start, int end, int
threshold)
c. Extend the RecursiveAction class from the java.util.concurrent package.
Note: A RecursiveAction is used when a ForkJoinTask with no return values is
needed.
d. Add the compute method. Note that unlike the compute method from a
RecursiveTask, the compute method in a RecursiveAction returns void.
protected void compute() { }
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G14:
Lesson
u
@ o e n
Building e
t Database
tu d
t r a S
r a ฺis this with JDBC
Applications
a n d use
l e x to 14
Chapter
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you will work with the JavaDB (Derby) database, creating, reading, updating,
and deleting data from a SQL database by using the Java JDBC API.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will start the JavaDB (Derby) database, load some sample data using a
script, and write an application to read the contents of an employee database table and print the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Tasks
1. Create the Employee Database by using the SQL script provided in the resource directory.
a. Open the Services window by selecting Windows > Services, or by pressing Ctrl-5.
b. Expand the Databases folder.
c. Right-click JavaDB and select Start Server.
d. Right-click JavaDB again and select Create Database.
e. Enter the following information: s a
)h a
Window/Page Description Choices or Values
c m
o ideฺ
ฺ
Database Name EmployeeDB
r a cle t Gu
User Name public
@ o e n
t e tu d
Password tiger
t r a S
Confirm Password tiger
r a ฺis this
f. Click OK a n d use
l e x to
g. Right-click the connection ( a that you
ns e
created:
r a t e i c e
jdbc:derby://localhost:1527/EmployeeDB[public on PUBLIC]and select
Connect. I s t le l
r a r a b
and nD:\labs\resources
h. Select File > Open File.
i.lexBrowseato sfe and open the EmployeeTable.sql script. The file
tr in a SQL Execute window.
A willn-open
o
j. n Select the connection that you created from the drop-down list, and click the Run-SQL
icon or press Ctrl-Shift-E to run the script.
k. Expand the EmployeeDB connection. You will see that the PUBLIC schema is now
created. Expand the PUBLIC Schema and look at the table Employee.
l. Right-click the connection again and select Execute Command to open another SQL
window. Enter the command:
select * from Employee
and click the Run-SQL icon to see the contents of the Employee table.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will start the JavaDB (Derby) database, load some sample data using a
script, and write an application to read the contents of an employee database table and print the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Tasks
1. Create the Employee Database by using the SQL script provided in the resource directory.
a. Open the Services Window by selecting Windows > Services, or by pressing Ctrl-5.
b. Expand the Databases folder.
c. Right-click JavaDB and select Start Server.
d. Right-click JavaDB again and select Create Database.
e. Enter the following information: s a
)h a
Window/Page Description Choices or Values
c m
o ideฺ
ฺ
Database Name EmployeeDB
r a cle t Gu
User Name public
@ o e n
t e tu d
Password tiger
t r a S
Confirm Password tiger
r a ฺis this
f. Click OK. a n d use
l e x to
g. Right-click the connection ( a that you
ns e
created:
r a t e i c e
jdbc:derby://localhost:1527/EmployeeDB[public on PUBLIC]and select
Connect. I s t le l
r a r a b
and nD:\labs\resources
h. Select File > Open File.
i.lexBrowseato sfe and open the EmployeeTable.sql script. The file
tr in a SQL Execute window.
A willn-open
o
j. n Select the connection that you created from the drop-down list and click the Run-SQL
icon or press Ctrl-Shift-E to run the script.
k. Expand the EmployeeDB connection. You will see that the PUBLIC schema is now
created. Expand the PUBLIC Schema, expand Tables, and then expand the table
Employee.
l. Right-click the connection again and select Execute Command to open another SQL
window. Enter the command:
select * from Employee
and click the Run-SQL icon to see the contents of the Employee table.
e. Click OK.
f. Expand the Source Packages and test packages and look at the
SimpleJDBCExample.java class.
g. Run the project: Right-click the project and select Run, or click the Run icon, or press
F6.
h. You should see all the records from the Employee table displayed.
3. (Optional) Add a SQL command to add a new Employee record.
a. Modify the SimpleJDBCExample class to add a new Employee record to the
database.
s a
b. The syntax for adding a row in a SQL database is:
)h a
INSERT INTO <table name> VALUES (<column 1 value>, <column 2
c m
o ideฺ
value>, ...)
ฺ
le What uis the return
c. Use the Statement executeUpdate method to execute the
r a cquery. t G
type for this method? What value should the return typeobe? Test e n make sure that the
to
value of the return is correct. t e @ tu d
t r a S
d. Your code may look like this:
r a ฺis this
query = "INSERT INTO Employee n d VALUES u s e (200, 'Bill',
e a
x 150000)";
to
'Murray','1950-09-21',
( a l e
a t e
if (stmt.executeUpdate(query)
c e ns != 1) {
s tr le li ("Failed to add a new employee record");
System.out.println
I
}
n d ra erab
Note:
x aIf you run
n s f application again, it will throw an exception, because this key already
the
e
l in-the
Aexists tradatabase.
no n
Overview
In this practice, you will take the existing Employee DAO Memory application and refactor the
code to use JDBC instead. The solution from the “Exceptions and Assertions” lesson has been
renamed to EmployeeDAOJDBC. You will need to create an EmployeeDAOJDBCImpl class to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Tasks
1. Open and examine the EmployeeDAOJDBC project in the
D:\labs\12-JDBC\practices folder.
a. In the com.example.test package, you see the class a
EmployeeTestInteractive. This class contains the main method and provides a
h a s
)
console-based user interface. Through this UI, you will be able to create new records,
m
ฺ c o
read all the records, update a record, and delete a record from the Employee
d e ฺ
cle t Gu i
database. Note how the main method creates an instance of a Data Access Object
(DAO). o r a n
e @ d e
t r a t S tu
b. In the com.example.model package, look at the Employee class. This class is a
r a ฺis this
Plain Old Java Object (POJO) that encapsulates all of the data from a single employee
record and row in the Employee table. Note that there are no set methods in this class,
a n d use
only get methods. Once an Employee object is created, it cannot be changed. It is
immutable. l e x to
( a ns e
a t e
c. Expand the com.example.dao package. Look at the EmployeeDAO class and you
c e
s tr le li
see the methods that an implementation of this interface is expected to implement.
I
n d ra erab
Each of these methods throws a DAOException. Note that this interface extends
x a n s f
AutoCloseable. Therefore, you will need to provide a close() method to satisfy the
e
Al n-tra
contract with AutoCloseable.
no
d. Look at the EmployeeDAOFactory. You see that this class has one method,
getFactory(), that returns an instance of an EmployeeDAOMemoryImpl.
e. Look at the EmployeeDAOMemoryImpl class. This class is the workhorse of the DAO
pattern. This is the class that the EmployeeDAOJDBCFactory returns as an instance
from the createEmployeeDAO method. This is the class that you will replace with a
JDBC implementation.
2. Create a new class, EmployeeDAOJDBCImpl, that implements EmployeeDAO in the
com.example.dao package.
a. Note that the class has an error.
Note: Your line numbers may differ from the picture shown.
c. The class must implement all the methods in the interface because this is a concrete
class (not abstract). You can have NetBeans provide all the method bodies by pressing
the Enter key to accept the suggestion “Implement all abstract methods.”
d. You will notice that the error in the file goes away immediately, and NetBeans has
s
provided all the method signatures based on the EmployeeDAO interface declarations. a
) h a
e. Your next task is to add a constructor and fill in the bodies of the methods.
c o m e ฺ
4. ฺ
Add a private instance variable, con, to hold a Connection object instance. i d
5. a cle t Gu
Write a package-level constructor for the class. The constructor for this class will create an
r
o e n
instance of a Connection object that the methods of this class can reuse during the
@
t e tu d
t r a
lifetime of the application. Be sure to catch a SQLException.
S
6. ฺis this
Write a method body for the add method. The add method creates a new record in the
r a
n d use
database from the Employee object passed in as a parameter. Recall that the SQL
a
e x to
command to create a new record in the database is: INSERT INTO <table> VALUES
l
( a ns e
(...).
a t e c e
I s tr le li
Note: Use single quotes for the strings and the date.
n d ra erab
a. Rethrow any SQLException caught as a DAOException.
7. a s f
Write a method body for the findById method. This method is used by the update and
x n
e
Al n-tra
delete methods and is used to locate a single record to display. Recall that the SQL
no
command to read a single record is: SELECT * FROM <table> WHERE <pk>=<value>.
a. Rethrow any SQLException caught as a DAOException.
8. Write a method body for the update method. The update method updates an existing
record in the database from the Employee object passed in as a parameter. Recall that the
SQL command to create a new record in the database is: UPDATE <table> SET
COLUMNNAME=<value>, COLUMNNAME=<value>, ... WHERE <pk>=<value>.
Note: Be sure to add single quotes around string and date values.
a. Rethrow any SQLException caught as a DAOException.
9. Write a method body for the delete method. The delete method tests to see whether an
employee exists in the database by using the findById method, and then deletes the
record if it exists. Recall that the SQL command to delete a record from the database is:
DELETE FROM <table> WHERE <pk>=<value>.
a. Rethrow any SQLException caught as a DAOException.
10. Write the method body for the getAllEmployees method. This method returns an array of
Employee records. The SQL query to return all records is quite simple: SELECT * FROM
<table>.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
so.
13. Update the EmployeeDAOFactory to return an instance of your new
EmployeeDAOJDBCImpl.
return new EmployeeDAOJDBCImpl();
14. Add the JDBC Derby driver class to the project, but adding the derbyclient.jar file to
the Libraries for the project.
a. Right-click the Libraries folder in the project and select Add Jar/Folder.
b. Browse to D:\Program Files\Java\jdk1.7.0\db\lib.
c. Select derbyclient.jar. s a
) h a
d. Absolute Path should be checked. m
ฺ c o d e ฺ
e. Click Open.
cle t Gu i
r a
15. Save the updated class, and if you have no errors, compile and run the project. This
o n
@ e
application has an interactive feature that allows you to query the database and read one or
e d
a t tu
all of the records, find an employee by ID, and update and delete an employee record.
t r S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you will take the existing Employee DAO Memory application and refactor the
code to use JDBC instead. The solution from the “Exceptions and Assertions” lesson has been
renamed to EmployeeDAOJDBC. You will need to create an EmployeeDAOJDBCImpl class to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Tasks
1. Open and examine the EmployeeDAOJDBC project in the
D:\labs\12-JDBC\practices folder.
a. In the com.example.test package, you see the class a
EmployeeTestInteractive. This class contains the main method and provides a
h a s
)
console-based user interface. Through this UI, you will be able to create new records,
m
ฺ c o
read all the records, update a record, and delete a record from the Employee
d e ฺ
cle t Gu i
database. Note how the main method creates an instance of a Data Access Object
(DAO). o r a n
e @ d e
t r a t S tu
b. In the com.example.model package, look at the Employee class. This class is a
r a ฺis this
Plain Old Java Object (POJO) that encapsulates all the data from a single employee
record and row in the Employee table. Note that there are no set methods in this class,
a n d use
only get methods. Once an Employee object is created, it cannot be changed. It is
immutable. l e x to
( a ns e
a t e
c. Expand the com.example.dao package. Look at the EmployeeDAO class and you
c e
s tr le li
see the methods that an implementation of this interface is expected to implement.
I
n d ra erab
Each of these methods throws a DAOException. Note that this interface extends
x a n s f
AutoCloseable; therefore, you will need to provide a close() method to satisfy the
e
Al n-tra
contract with AutoCloseable.
no
d. Look at the EmployeeDAOFactory. You see that this class has one method,
getFactory(), that returns an instance of an EmployeeDAOMemoryImpl.
e. Look at the EmployeeDAOMemoryImpl class. This class is the workhorse of the DAO
pattern. This is the class that the EmployeeDAOJDBCFactory returns as an instance
from the createEmployeeDAO method. This is the class that you will replace with a
JDBC implementation.
2. Create a new class, EmployeeDAOJDBCImpl, in the com.example.dao package.
a. Right-click on the com.example.dao package and choose New Java Class
b. Enter EmployeeDAOJDBCImpl as the class name and click Finish.
c. Change this class to implement EmployeeDAO.
d. Note that causes an error.
Note: Your line numbers may differ from the picture shown.
c. The class must implement all the methods in the interface because this is a concrete
class (not abstract). You can have NetBeans provide all of the method bodies by
pressing the Enter key to accept the suggestion “Implement all abstract methods.”
d. You will notice that the error in the file goes away immediately, and NetBeans has
provided all the method signatures based on the EmployeeDAO interface declarations.
s a
)h
e. Your next task is to add a constructor and fill in the bodies of the methods.
a
4. Add a private instance variable, con, to hold a Connection object instance.
c m
o ideฺ
ฺ
private Connection con = null;
r a cle t Gu
5. Write a constructor for the class. The constructor for this@ o will create
class e n an instance of a
Connection object that the methods of this class a e
t reuseSduring
can
d
tu the lifetime of the
t r
application.
r a ฺis this
d uaccess.
a. Write the constructor to use package-level
n s e This will enable only classes within
a
x of this
the package to create an instance
e to class (like the EmployeeDAOFactory).
( a l e
EmployeeDAOJDBCImpl()
a t e c e
{
ns
I s tr lusing
b. Open the connection
e li the JDBC URL, name, and password from the
application:
n d ra erab
SimpleJDBCExample
x a
String
n s
urlf = "jdbc:derby://localhost:1527/EmployeeDB";
e
Al String- tra username = "public";
n
noString password = "tiger";
c. In a try block (not a try-with-resources, because you want to keep this connection
open until you exit the application) create an instance of a Connection object and
catch any exception. If the connection cannot be made, exit the application.
Note: Ideally you would rather indicate to the user that the connection could not be
made and retry the connection a number of times before exiting.
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException se) {
System.out.println("Error obtaining connection with the
database: " + se);
System.exit(-1);
}
6. Write a method body for the add method. The add method creates a new record in the
database from the Employee object passed in as a parameter. Recall that the SQL
}
c. Inside the try block, create a query to insert the values passed in the Employee
instance to the database. Your query string should look something like this:
String query = "INSERT INTO EMPLOYEE VALUES (" + emp.getId()
+ ", '" + emp.getFirstName() + "', "
+ "'" + emp.getLastName() + "', "
+ "'" +
s a
new java.sql.Date(emp.getBirthDate().getTime()) + "',"
)h a
+ emp.getSalary() + ")";
c m
o ideฺ
Note the use of single quotes for the strings and the date. ฺ
r
d. Since you are not expecting a result from the query, the appropriate a cle tStatement
G u class
o n
method to use is updateQuery. Make sure to test @
t e t u deFortheexample:
to see whether statement
executed properly by looking at the integer result
s a
tr is S
of the method.
if (stmt.executeUpdate(query) r ฺ i
a 1)e {th
!=
throw new DAOException("Error
d
an to us adding employee");
e x
}
e ( al nse
e. At the end of the
s t r atryt block,liccatch
e any SQLException thrown, and wrap them in the
a I to bbelehandled by the calling application. For example:
DAOException
r
n f e ra
d (SQLException
x a
catch
s se) {
ran new DAOException("Error adding employee in DAO", se);
Ale }n-tthrow
n o
7. Write a method body for the findById method. This method is used by the update and
delete methods and is used to locate a single record to display. Recall that the SQL
command to read a single record is: "SELECT * FROM <table> WHERE
<pk>=<value>".
a. Delete the boiler-plate code created by NetBeans for the findById method.
b. Create an instance of a Statement object in a try-with-resources block:
try (Statement stmt = con.createStatement()) {
}
c. Inside the try block, write a query statement to include the integer id passed in as an
argument to the method and execute the query, returning a ResultSet instance:
String query = "SELECT * FROM EMPLOYEE WHERE ID=" + id;
ResultSet rs = stmt.executeQuery(query);
d. Test the ResultSet instance for null using the next() method and return the result
as a new Employee object:
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
rs.getString("LASTNAME"),
rs.getDate("BIRTHDATE"),
rs.getFloat("SALARY")));
e. At the end of the try block, catch any SQLException thrown, and wrap them in the
DAOException to be handled by the calling application. For example
catch (SQLException se) {
throw new DAOException("Error finding employee in DAO", se);
}
8. Write a method body for the update method. The update method updates an existing s a
)h a
record in the database from the Employee object passed in as a parameter. Recall that the
SQL command to create a new record in the database is: "UPDATE <table> SET
c m
o ideฺ
ฺ
COLUMNNAME=<value>, COLUMNNAME=<value>, ... WHERE <pk>=<value>".
r a cle t Gu
o
Note: Be sure to add single quotes around string and date values.
@ e n
t e tu d
a. Delete the boiler-plate code created by NetBeans for the update method.
t r a S
r a ฺis this
b. Create an instance of a Statement object in a try-with-resources block:
a n d use
try (Statement stmt = con.createStatement()) {
x
le se t o
( a
}
t r a te licen
Isblock,bcreate
c. Inside the try
r a le the SQL UPDATE query from the Employee object passed
in: d
n query f er a
x a n s
Ale n-t+ra"SET FIRSTNAME='" + emp.getFirstName() + "',"
String = "UPDATE EMPLOYEE "
b. Call the findById method with the id passed in as a parameter and if the record
returned is null, throw a new DAOException.
Employee emp = findById(id);
if (emp == null) {
throw new DAOException("Employee id: " + id + " does not
exist to delete.");
}
c. Create an instance of a Statement object in a try-with-resources block:
s a
try (Statement stmt = con.createStatement()) {
)h a
c m
o ideฺ
ฺ
}
r a cle t Gu
d. Inside the try block, create the SQL DELETE query andotest the e n returned to
result
e @ tu d
make sure a single record was altered – throw atnew DAOException if not:
t r a S
String query = "DELETE FROM EMPLOYEE
a ฺis thWHEREis ID=" + id;
if (stmt.executeUpdate(query)
r
nd us != 1) {e
e x a to
( a l
throw new DAOException("Error
s e deleting employee");
}
t r a te licen
r a Isthe trybblock,
e. At the end of l e catch any SQLException thrown, and wrap them in the
a n d fertoa be handled by the calling application. For example:
DAOException
l e s
xcatchra(SQLException
n se) {
A n-tthrow new DAOException("Error deleting employee in DAO",
nose);
}
}
c. Inside the try block, create and execute the query to return all the employee records:
String query = "SELECT * FROM EMPLOYEE";
ResultSet rs = stmt.executeQuery(query);
d. The easiest way to create an array of employees to return is to use a Collection object,
ArrayList, and then convert the ArrayList object to an array. Iterate through the
a
ResultSet and add each record to the ArrayList. In the return statement, use the
s
toArray method to convert the collection to an array:
)h a
ArrayList<Employee> emps = new ArrayList<>();
c m
o ideฺ
ฺ
while (rs.next()) {
r a cle t Gu
emps.add(new Employee(rs.getInt("ID"),
@ o e n
t e tu
rs.getString("FIRSTNAME"), d
t r a S
r a ฺis this
rs.getString("LASTNAME"),
a n d use
rs.getDate("BIRTHDATE"),
l e x rs.getFloat("SALARY")));
to
}
( a ns e
a t e c e
return emps.toArray(new Employee[0]);
I
e. At the end ofs tr le licatch any SQLException thrown, and wrap them in the
the try block,
n d ra ertoabbe handled by the calling application. For example:
x
DAOException
n s f
a (SQLException
e ra new DAOException("Error
Al n-tthrow
catch se) {
nose);
getting all employees in DAO",
}
11. Write the method body for the close method. This method is defined by the
AutoCloseable interface. This method should explicitly close the Connection object
that you created in the constructor.
a. Delete the boiler-plate code created by NetBeans for the close method.
b. In a try block (you must use a try block, because Connection.close throws an
exception that must be caught or rethrown), call the close method on the
Connection object instance, con. Rather than rethrow the exception, simply report it.
try {
con.close();
} catch (SQLException se) {
System.out.println ("Exception closing Connection: " + se);
}
12. Save the class. Fix any missing imports and compilation errors if you have not already.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
s a
) h a
c o m e ฺ
ฺ i d
Practices for r a cle t G15:
Lesson
u
@ o e n
Localizationt e tu d
t r a S
r a ฺis 15 this
Chapter
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Practices Overview
In these practices, you create a date application that is similar to the example used in the
lesson. For each practice, a NetBeans project is provided for you. Complete the project as
indicated in the instructions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you create a text-based application that displays dates and times in a number of
different ways. Create the resource bundles to localize the application for French, Simplified
Chinese, and Russian.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have attended the lecture for this lesson. You have access to the JDK7 API documentation.
Summary
Create a simple text-based date application that displays the following date information for
today:
• Default date
• Long date a
• Short date h a s
m )
• Full date
ฺ c o d e ฺ
• Full time cle t Gu i
• Day of the week o r a n
e @ d e
•
t r a t S tu
And a custom day and time that displays: day of the week, long date, era, time, and time
zone
r a ฺis this
a n d use
Localize the application so that it displays this information in Simplified Chinese and Russian.
l e x
The user should be able to switch between the languages.
to
( a ns e
The application output in English is shown here.
a t e c e
I s tr le li
=== Date App ===
n d ra erab
Default Date is: Aug 1, 2011
x a s f
Long Date is: August 1, 2011
n
e
Al n-tra
Short Date is: 8/1/11
Tasks
Open the Localized-Practice01 project in NetBeans and make the following changes:
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
Overview
In this practice, you create a text-based application that displays dates and times in a number of
different ways. Create the resource bundles to localize the application for French, Simplified
Chinese, and Russian.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have attended the lecture for this lesson. You have access to the JDK7 API documentation.
Summary
Create a simple text-based date application that displays the following date information for
today:
• Default date
• Long date a
• Short date h a s
m )
• Full date
ฺ c o d e ฺ
• Full time cle t Gu i
• Day of the week o r a n
e @ d e
•
t r a t S tu
And a custom day and time that displays: day of the week, long date, era, time, and time
zone
r a ฺis this
a n d use
Localize the application so that it displays this information in Simplified Chinese and Russian.
l e x
The user should be able to switch between languages.
to
( a ns e
The application output in English is shown here.
a t e c e
I s tr le li
=== Date App ===
n d ra erab
Default Date is: Aug 1, 2011
x a s f
Long Date is: August 1, 2011
n
e
Al n-tra
Short Date is: 8/1/11
o n -t
n }
currentLocale);
pw.println(messages.getString("date1") + " " +
df.format(today));
df = DateFormat.getDateInstance(DateFormat.LONG,
currentLocale);
pw.println(messages.getString("date2") + " " +
df.format(today));
df = DateFormat.getDateInstance(DateFormat.SHORT,
currentLocale);
pw.println(messages.getString("date3") + " " +
s a
df.format(today));
) h a
df = DateFormat.getDateInstance(DateFormat.FULL,
c o m e ฺ
ฺ i d
currentLocale);
r a cle t Gu
pw.println(messages.getString("date4") + " " +
@ o e n
df.format(today));
t e tu d
t r a S
df = DateFormat.getTimeInstance(DateFormat.FULL,
currentLocale);
r a ฺis this
a n d use
pw.println(messages.getString("date5") + " " +
df.format(today)); l e x to
( a ns e
t e e
sdf = new SimpleDateFormat("EEEE", currentLocale);
a c
I s tr le li
pw.println(messages.getString("date6") + " " +
n d ra erab
sdf.format(today));
x a n s f
sdf = new SimpleDateFormat("EEEE MMMM d, y G kk:mm:ss
e
Al n-tra
zzzz", currentLocale);
Overview
In this practice, you localize the JDBC application that you created in the practices for the
“Building Database Applications with JDBC” lesson.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2013, Oracle and/or its affiliatesฺ
Assumptions
You have attended the lecture for this lesson. You have completed the practices for the
“Building Database Applications with JDBC” lesson.
Summary
Localize the JDBC application from the previous lesson. Identify any object that displays menu
or object information and change them so that localized messages are displayed instead of
static text.
Localize the application so that it displays this information in English, French, and Russian. The s a
user should be able to switch between languages. )h a
c m
o ideฺ
ฺ
Tasks
r a cle t Gu
You have a couple of project choices in this lab. First you can use
@ o the project
e n files from Lesson
14, Practice 2, “Using the Data Access Object Pattern,” and t e just continue
t d
uthe following
with that project.
Alternatively, open the Practice02 project for thisslesson. t r a S
Perform
s steps:
ฺ i t h i
1. Open the EmployeeTestInteractive.java
n d ra file. s e Examine the source code and
determine which messages printed xato the console
t o u should be converted into resource
bundles. Notice that not all text
( l
a nseeoutput is included in this class file.
Note: You do not have
r e
attoshould
includee
i cbeerror messages in the bundle. Only prompt and
s
informational messages
I t l included.
leinterface is required.
r a r a b
x a ndthe main
2. A slight change
s
to
f the user
einterface
Currently n looks like this:
Ale [C]reate
n- t r a | [R]ead | [U]pdate | [D]elete | [L]ist | [Q]uit:
n o
Changing the user interface to the following makes it easier to translate just the words in
the menu.
[C] - Create | [R] - Read | [U] - Update | [D] - Delete | [L] -
List | [S] – Set Language | [Q] - Quit:
This separates the single character commands from the words. For the solution only the
words were translated. You could, of course, translate both. Notice a new option has been
added to set the language.
3. Create a message bundle for English, French, and Russian.
• The translated text for the menus can be found in the MessagesText02.txt file in
the practices directory.
4. Add a ResourceBundle object to any object that displays menu-related information.
Replace the static text with a call to the resource bundle and get the appropriate string
message.
5. Examine all the date-related source code. Make sure that date information will print in the
appropriate localized format.
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no
s a
) h a
c o m e ฺ
ฺ i d
r a cle t Gu
@ o e n
t e tu d
t r a S
r a ฺis this
a n d use
l e x to
( a ns e
a t e c e
I s tr le li
n d ra erab
x a n s f
e
Al n-tra
no