You are on page 1of 137

Copyright 2012, 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.
The information contained in this document is subject to
change without notice. If you find any problems in the
document, please report them in writing to: Oracle
University, 500 Oracle Parkway, Redwood Shores,
California 94065 USA. This document is not warranted to
be error-free.
Restricted Rights Notice
If this documentation is delivered to the United States
Government or anyone using the documentation on behalf
of the United States Government, the following notice is
applicable:
U.S. GOVERNMENT RIGHTS
The U.S. Governments rights to use, modify, reproduce,
release, perform, display, or disclose these training
materials are restricted by the terms of the applicable
Oracle license agreement and/or the applicable U.S.
Government contract.
Trademark Notice
Oracle and Java are registered trademarks of Oracle and/or
its affiliates. Other names may be trademarks of their
respective owners.
Experience with at least one programming
language
An understanding of object-oriented principles
Chapter 1 Experience with basic database concepts and a
basic knowledge of SQL
Introduction
Prerequisites
Course Goals To successfully complete this course, you must know how
to:
This course covers the core APIs that you use to Compile and run Java applications
design object-oriented applications with Java. Create Java classes
This course also covers writing database Create object instances using the new keyword
programs with JDBC. Declare Java primitive and reference variables
Use this course to further develop your skills with Declare Java methods using return values and
the Java language and prepare for the Oracle parameters
Certified Professional, Java SE 7 Programmer Use conditional constructs such as if and
Exam. switch statements
Use looping constructs such as for, while, and
do loops
Course Objectives Declare and instantiate Java arrays
After completing this course, you should be able to do the Use the Java Platform, Standard Edition API
following: Specification (Javadocs)
Create Java technology applications that leverage
the object-oriented features of the Java language,
such as encapsulation, inheritance, and Class Introductions
polymorphism Briefly introduce yourself:
Execute a Java application from the command Name
line Title or position
Create applications that use the Collections Company
framework Experience with Java programming and Java
Implement error-handling techniques using applications
exception handling Reasons for attending
Implement input/output (I/O) functionality to read
from and write to data and text files and
understand advanced I/O streams Course Environment
Manipulate files, directories, and file systems
using the JDK7 NIO.2 specification
Perform multiple operations on database tables,
including creating, reading, updating, and
deleting, using the JDBC API
Process strings using a variety of regular
expressions
Create high-performing multi-threaded
applications that avoid deadlock
Localize Java applications

Audience
The target audience includes those who have:
Completed the Java SE 7 Fundamentals course or
have experience with the Java language, and can
create, compile, and execute programs In this course, the following products are preinstalled for
the lesson practices:
JDK 7: The Java SE Development Kit includes
the command-line Java compiler (javac) and
the Java Runtime Environment (JRE), which
supplies the java command needed to execute
Java applications.
Firefox: A web browser is used to view the
HTML documentation (Javadoc) for the Java SE
Platform libraries.
NetBeans 7.0.1: The NetBeans IDE is a free and
open-source software development tool for
professionals who create enterprise, web,
desktop, and mobile applications. NetBeans 7.0.1
fully supports the Java SE 7 Platform. Support is
provided by Oracle's Development Tools Support Identifying Java Technology Groups
offering.
Oracle provides a complete line of Java technology
Java DB: Java DB is Oracle's supported
products ranging from kits that create Java technology
distribution of the open-source Apache Derby
programs to emulation (testing) environments for
100% Java technology database. It is fully
consumer devices, such as cellular phones. As indicated in
transactional, secure, easy-to-use, standards-
the graphic, all Java technology products share the
based SQL, JDBC API, and Java EE yet small,
foundation of the Java language. Java technologies, such
only 2.5 MB.
as the Java Virtual Machine, are included (in different
forms) in three different groups of products, each designed
to fulfill the needs of a particular target market. The figure
Java Programs are Platform- illustrates the three Java technology product groups and
Independent their target device types. Among other Java technologies,
each edition includes a Software Development kit (SDK)
that allows programmers to create, compile, and execute
Java technology programs on a particular platform:
Java Platform, Standard Edition (Java SE):
Develops applets and applications that run within
Web browsers and on desktop computers,
respectively. For example, you can use the Java
SE Software Development Kit (SDK) to create a
word processing program for a personal
computer. You can also use the Java SE to create
an application that runs in a browser.
Platform-Independent Programs Note: Applets and applications differ in several ways.
Java technology applications are written in the Java Primarily, applets are launched inside a web browser,
programming language and compiled to Java bytecode. whereas applications are launched within an operating
Bytecode is executed on the Java platform. The software system.
that provides you with a runnable Java platform is called a
Java Runtime Environment (JRE). A compiler, included in
the Java SE Development Kit (JDK), is used to convert Java SE Platform Versions
Java source code to Java bytecode.

Java Technology Product Groups Year Developer Platform


Version (JDK)
1996 1.0 1
1997 1.1 1
1998 1.2 2
2000 1.3 2
2002 1.4 2
2004 1.5 5
2006 1.6 6
2011 1.7 7

How to Detect Your Version


If Java SE is installed on your system, you can detect the
version number by running java -version. Note that
the java command is included with the Java Runtime
Environment (JRE). As a developer, you also need a Java
compiler, typically javac. The javac command is
included in the Java SE Development Kit (JDK). Your
operation systems PATH may need to be updated to
include the location of javac.

Downloading and Installing the JDK

Java is common in enterprise environments:


Oracle Fusion Middleware
Java application servers
- GlassFish
- WebLogic
Database servers
MySQL
Oracle Database

Enterprise Environments
In this course, you develop Java SE applications. There
are standard patterns you need to follow when
implementing Java SE applications, such as always
creating a main method that may be different when
1. Go to http://www.oracle.com/technetwork/java/ implementing enterprise applications. Java SE is only the
javase/downloads/index.html. starting point in your path to becoming a Java developer.
2. Choose the Java Platform, Standard Edition (Java Depending on the needs of your organization, you may be
SE) link. required to develop applications that run inside Java EE
3. Download the version that is appropriate for your application servers or other types of Java middleware.
operation system. Often, you will also need to manipulate information stored
4. Follow the installation instructions. inside relational databases such as MySQL or Oracle
5. Set your PATH. Database. This course introduces you to the fundamentals
of database programming.

Java in Server Environments


The Java Community
OpenJDK
OpenJDK is the open-source implementation of Java:
http://openjdk.java.net/
GPL licensed open-source project
JDK reference implementation
Where new features are developed
Open to community contributions
Basis for Oracle JDK

Why OpenJDK Is Important


Because it is open source, OpenJDK enables users to port
Java to operating systems and hardware platforms of their
What Is the Java Community? choosing. Ports are underway for many platforms (besides
those already supported) including FreeBSD, OpenBSD,
At a very high level, Java Community is the term used to NetBSD, and MacOS X.
refer to the many individuals and organizations that
develop, innovate, and use Java technology. This
community includes developers as individuals, Oracle Java SE Support
organizations, businesses, and open-source projects. It is
very common for you to download and use Java libraries Java is available free of charge. However, Oracle does
from non-Oracle sources within the Java community. For provide pay-for Java solutions:
instance, in this course, you use an Apache-developed The Java SE Support Program provides updates
JDBC library to access a relational database. for end-of-life Java versions.
Oracle Java SE Advanced and Oracle Java SE
Suite:
The Java Community Process (JCP) - JRockit Mission Control
- Memory Leak Detection
The JCP is used to develop new Java standards: - Low Latency GC (Suite)
http://jcp.org - JRockit Virtual Edition (Suite)
Free download of all Java Specification Requests
(JSRs) Still Free
Early access to specifications
Public review and feedback opportunities Java (Oracle JDK) is freely available at no cost. Oracle
Open membership offers advanced commercial solutions at cost. The
previously offered Java for Business program has been
JCP.next replaced by Oracle Java SE Support, which provides
access to Oracle Premier Support and the Oracle Java SE
The JCP produces the JSRs that outline the standards of Advanced and Oracle Java SE Suite binaries. For more
the Java platform. The behavior of the JCP itself is also information, visit http://www.oracle.com/us/technologies/
defined and improved through the JSR process. The JCP is java/java-se-suite-394230.html.
evolving and its improvements are defined in JSR-348.
JSR-348 introduces changes in the areas of transparency,
participation, agility, and governance. Additional Resources
Transparency: In the past, some aspects of the
development of a JSR may have occurred behind
closed doors. Transparent development is now the
recommended practice. Topic Website
Participation: Individuals and Java User Groups Education and Training http://education.oracle.com
are encouraged to become active in the JCP. Product Documentation http://www.oracle.com/
Agility: Slow-moving JSRs are now actively technology/documentation
discouraged. Product Downloads http://www.oracle.com/
Governance: The SE and ME expert groups are technology/software
merging into a single body. Product Articles http://www.oracle.com/
technology/pub/articles
Product Support http://www.oracle.com/
support
Product Forums http://forums.oracle.com
Product Tutorials http://www.oracle.com/
technetwork/tutorials/
index.html
Sample Code https://
www.samplecode.oracle.co
m
Oracle Technology Network http://www.oracle.com/
for Java Developers technetwork/java/index.html
Oracle Learning Library http://www.oracle.com/goto/
oll

The table in the slide lists various web resources that are
available for you to learn more about Java SE
programming.

Summary
In this lesson, you should have learned about:
The course objectives
Software used in this course
Java platforms (ME, SE, and EE)
Java SE version numbers
Obtaining a JDK
The open nature of Java and its community
Commercial support options for Java SE
lives relative to other classes, and provides a level
of access control. You use access modifiers (such
as public and private) later in this lesson.
Chapter 2 The import keyword defines other classes or
groups of classes that you are using in your class.
Java Syntax and Class Review The import statement helps to narrow what the
compiler needs to look for when resolving class
names used in this class.
The class keyword precedes the name of this
Objectives class. The name of the class and the file name
After completing this lesson, you should be able to do the must match when the class is declared public
following: (which is a good practice). However, the keyword
Create simple Java classes public in front of the class keyword is a
- Create primitive variables modifier and is not required.
- Manipulate Strings Variables, or the data associated with programs
- Use if-else and switch branching (such as integers, strings, arrays, and references
statements to other objects), are called instance fields (often
- Iterate with loops shortened to fields).
- Create arrays Constructors are functions called during the
Use Java fields, constructors, and methods creation (instantiation) of an object (a
Use package and import statements representation in memory of a Java class.)
Methods are the functions that can be performed
on an object. They are also referred to as instance
Java Language Review methods.

This lesson is a review of fundamental Java and


programming concepts. It is assumed that students are A Simple Class
familiar with the following concepts:
The basic structure of a Java class A simple Java class with a main method:
Program block and comments
Variables
Basic if-else and switch branching
constructs
Iteration with for and while loops

Class Structure
To run a Java program, you must define a main method as
shown in the slide. The main method is automatically
called when the class is called from the command line.
Command-line arguments are passed to the program
through the args[] array.
Note: A method that is modified with the keyword
static is invoked without a reference to a particular
object. The class name is used instead. These methods are
referred to as class methods. The main method is a
special method that is invoked when this class is run using
the Java runtime.

A Java class is described in a text file with a .java


extension. In the example shown, the Java keywords are Code Blocks
highlighted in bold. Every class declaration is enclosed in a code
The package keyword defines where this class
block. The most common integer type is int. Number
Method declarations are enclosed in code blocks. of bits = 32.
Java fields and methods have block (or class) long range is 9,223,372,036,854,775,808 to
scope. +9,223,372,036,854,775,807. Number of bits =
Code blocks are defined in braces: 64.

Example: Floating Point


The floating-point types hold numbers with a fractional
part and conform to the IEEE 754 standard. There are two
types of floating points: float and double.
double is so called because it provides double the
Java fields (variables) and methods have a class scope precision of float. A float uses 32 bits to store data,
defined by the opening left curly brace and ending at the whereas a double uses 64 bits.
closing right curly brace.
Class scope allows any method in the class to call or Character
invoke any other method in the class. Class scope also
The char type is used for individual characters, as
allows any method to access any field in the class.
opposed to a string of characters (which is implemented as
Code blocks are always defined using braces {}. A block
a String object). Java supports Unicode, an
is executed by executing each of the statements defined
international standard for representing a character in any
within the block in order from first to last (left to right).
written language in the world in a single 16-bit value. The
The Java compiler ignores white space that precedes or first 256 characters coincide with the ISO Latin 1
follows the elements that make up a line of code. Line character set, part of which is ASCII.
indentation is not required but makes code much more
readable. In this course, the line indentation is four spaces, Boolean
which is the default line indentation used by the NetBeans
IDE. The boolean type can hold either true or false.
Note: true and false may appear to be keywords, but
they are technically boolean literals.
Primitive Data Types
Default Values
If a value is not specified, a default value is used. The
values in red in the slide are the defaults used. The default
char value is null (represented as '\u0000'), and the
default value for boolean is false.
Note: Local variables (that is, variables declared within
methods) do not have a default value. An attempt to use a
local variable that has not been assigned a value will cause
a compiler error. It is a good practice always to supply a
default value to any variable.

Append uppercase or lowercase L or F to the number


to specify a long or a float number. Java SE 7 Numeric Literals
Integer In Java SE 7 (and later versions), any number of
underscore characters (_) can appear between digits in a
Java provides four different integer types to accommodate numeric field. This can improve the readability of your
different size numbers. All the numeric types are signed, code.
which means that they can hold positive or negative
numbers. The integer types have the following ranges:
byte range is 128 to +127. Number of bits = 8.
short range is 32,768 to +32,767. Number of
bits = 16.
int range is 2,147,483,648 to +2,147,483,647.
Arithmetic operators
+ Additive operator (also used for String
concatenation)
Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Unary operators
Rules for Literals + Unary plus operator; indicates positive
Unary minus operator; negates an expression
You can place underscores only between digits; you ++ Increment operator; increments a value by 1
cannot place underscores in the following places: Decrement operator; decrements a value by 1
At the beginning or end of a number ! Logical complement operator; inverts the value
Adjacent to a decimal point in a floating point of a Boolean
literal Because numbers have been introduced, the slide shows a
Prior to an F or L suffix list of common operators. Most are common to any
In positions where a string of digits is expected programming language, and a description of each is
Note: The Java language is case-sensitive. In Java, the provided in the slide.
variable creditCardNumber is different from The binary and bitwise operators have been omitted for
CREDITCARDNUMBER. Convention indicates that Java brevity. For details about those operators, refer to the Java
variables and method names use lower camel case Tutorial:
lowercase for the first letter of the first element of a http://download.oracle.com/javase/tutorial/java/
variable name and uppercase for the first letter of nutsandbolts/operators.html
subsequent elements. Note: Operators have definitive precedence. For the
complete list, see the Java Tutorial link mentioned above.
Precedence can be overridden using parentheses.
Java SE 7 Binary Literals
In Java SE 7 (and later versions), binary literals can also
be expressed using the binary system by adding the
Strings
prefixes 0b or 0B to the number:

Binary literals are Java int values. A cast is required


when the integer value of the literal exceeds the greatest
non-negative value that the type can hold. For example:
byte aByte = 0b0111_1111; // aByte is The code in the slide demonstrates how text characters are
127 represented in Java. Single characters can be represented
byte aByte = 0b1000_0000; // compiler with the char type. However, Java also includes a
error - a cast is required // (value is String type for representing multiple characters. Strings
-128) can be defined as shown in the slide and combined using
the + sign as a concatenation operator.
The output from the code in the slide is:
Operators Output: HelloWorld a
Simple assignment operator Caution: Strings should always be initialized using the
= Simple assignment operator assignment operator = and text in quotation marks, as
shown in the examples. The use of new to initialize a
String is strongly discouraged. The reason is that Bad
Practice in line 10 is a String literal of type
String, Using the new keyword simply creates another
instance functionally identical to the literal. If this
statement appeared inside of a loop that was frequently
invoked, there could be a lot of needless String
instances created.

String Operations

The example in the slide demonstrates the syntax for an


if-else statement in Java. The output from the code in
the slide is as follows:
False

Logical Operators
Equality and relational operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
This slide demonstrates some common string methods, <= Less than or equal to
including: Conditional operators
concat() && Conditional-AND
length()
|| Conditional-OR
substring()
?: Ternary (shorthand for if-then-else
toUpperCase()
statement)
To see what other methods can be used on a String, see
Type comparison operator
the API documentation. The output from the program is: instanceof Compares an object to a specified
string3: HelloWorld
type
Length: 5
The slide shows a summary of the logic and conditional
Sub: Hello operators in Java.
Upper: HELLOWORLD
Note: String is a class, not a primitive type. Instances of
the class String represent sequences of Unicode Arrays and for-each Loop
characters. String literals are stored as String objects
and interned, meaning that for strings with matching
characters, they all point to the same String object.

if else
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8

while Loop

This class demonstrates how to define arrays in Java. The


first example creates a String array and initializes each
element separately. The second int array is defined in a
single statement.
Each array is iterated through using the Java for-each
construct. The loop defines an element which will
represent each element of the array and the array to loop
through. The output of the class is shown here:
Name: Blue Shirt
The while loop performs a test and continues if the
Name: Red Shirt
expression evaluates to true. The while loop, shown
Name: Black Shirt
here, iterates through an array using a counter. Here is the
Number: 100
output from the code in the slide:
Number: 200 Number: 100
Number: 300 Number: 200
Note: Arrays are also objects by default. All arrays support Number: 300
the methods of the class Object. You can always obtain the Note: There is also a do-while loop, where the test after
size of an array using its length field. the expression has run at least once:
class DoWhileDemo {
public static void main(String[]
for Loop args){
int count = 1;
do {
System.out.println(Count is: +
count);
count++;
} while (count < = 11);
}
}

String switch Statement


The classic for loop is shown in the slide. A counter is
initialized and incremented for each step of the loop.
When the condition statement evaluates to false (when i
is no longer less than 9), the loop exits. Here is the sample
output for this program.
i: 0
i: 1
i: 2
value. You will learn more about the keyword final in
the lesson Advanced Class Design.
For the complete Code Conventions for the Java
Programming Language document, go to http://
www.oracle.com/technetwork/java/
codeconv-138413.html.

A Simple Java Class: Employee


A Java class is often used to represent a concept.

This example shows a switch statement in Java using a


String. Prior to version 7 of Java, only enums and
byte, short, char, and int primitive data types could
be used in a switch statement. You will see enums in the
lesson titled Advanced Class Design.

Java Naming Conventions

A Java class is often used to store or represent data for the


construct that the class represents. For example, you could
create a model (a programmatic representation) of an
Employee. An Employee object defined using this model
will contain values for empId, name, Social Security
Number (ssn), and salary.
The constructor in this class creates an instance of an
object called Employee.
A constructor is unique in Java. A constructor is used to
create an instance of a class. Unlike methods, constructors
do not declare a return type, and are declared with the
Class names should be nouns in mixed case, with same name as their class. Constructors can take arguments
the first letter uppercase and the first letter of and you can declare more than one constructor, as you will
each internal word capitalized. This is approach is see in the lesson titled Java Class Design.
termed upper camel case.
Methods should be verbs in mixed case, with the
first letter lowercase and the first letter of each Methods
internal word capitalized. This is termed lower When a class has data fields, a common practice is to
camel case. provide methods for storing data (setter methods) and
Variable names should be short but meaningful. retrieving data (getter methods) from the fields.
The choice of a variable name should be
mnemonic: designed to indicate to the casual
observer the intent of its use.
One-character variable names should be avoided
except as temporary throwaway variables.
Constants should be declared using all uppercase
letters.
Note: The keyword final is used to declare a variable
whose value may only be assigned once. Once a final
variable has been assigned, it always contains the same
instance of the Employee class and assign the
reference to the new object to a variable called
emp.
Then you assign values to the Employee object.

Creating an Instance of the Employee


Class
In order to use the Employee class to hold the
information of an employee, you need to allocate memory
for the Employee object and call a constructor method in
Adding Instance Methods to the the class. An instance of an object is created when you use
the new keyword with a constructor. All of the fields
Employee Class declared in the class are provided memory space and
A common practice is to create a set of methods that initialized to their default values. If the memory allocation
manipulate field data: methods that set the value of each and constructor are successful, a reference to the object is
field, and methods that get the value of each field. These returned as a result. In the example in the slide, the
methods are called accessors (getters) and mutators reference is assigned to a variable called emp.
(setters). To store values (data) into the Employee object instance,
The convention is to use set and get plus the name of you could just assign values to each field by accessing the
the field with the first letter of the field name capitalized fields directly. However, this is not a good practice and
(lower camel case). Most modern integrated development negates the principle of encapsulation. Instead, you should
environments (IDEs) provide an easy way to automatically invoke instance methods and pass a value to the method to
generate the accessor (getter) and mutator (setter) methods set the value of each data field. Later in this lesson you
for you. will look at restricting access to the fields to promote
Notice that the set methods use the keyword this. The encapsulation.
this keyword allows the compiler to distinguish between Once all the data fields are set with values, you have an
the field name of the class (this) and the parameter instance of an Employee with an empId with a value of
name being passed in as an argument. Without the 101, name with the string John Smith, Social Security
keyword this, the net effect is you are assigning a value number string (ssn) set to 011-22-3467, and salary
to itself. (In fact, NetBeans provides a warning: with the value of 120,345.27.
Assignment to self.)
In this simple example, you could use the setName
method to change the employee name and the Constructors
setSalary method to change the employee salary.
Note: The methods declared on this slide are called
instance methods. They are invoked using an instance of
this class (described on the next slide.)

Creating an Instance of an Object


To construct or create an instance (object) of the A constructor is used to create an instance of a
Employee class, use the new keyword. class.
Constructors can take parameters.
A constructor that takes no arguments is called a
no-arg constructor.
A constructor is used to create an object. In the Java
programming language, constructors are declared with the
same name as their class used to create an instance of an
object. Constructors are invoked using the new keyword.
Constructors are covered in more detail in the lesson titled
Encapsulation and Subclassing.
In this fragment of Java code, you construct an
But that would quickly lead to a lot of typing! Instead,
package Statement Java provides the import statement to allow you to declare
that you want to reference a class in another package.
The package keyword is used in Java to group classes
Note: It is a good practice to use the specific, fully
together. A package is implemented as a folder and, like a
qualified package and class name to avoid confusion when
folder, provides a namespace to a class.
there are two classes with the same name, as in the
following example: java.sql.Date and
java.util.Date. The first is a Date class used to
store a Date type in a database, and java.util.Date
is a general purpose Date class. As it turns out,
java.sql.Date is a subclass of java.util.Date.
This is covered in more detail later in the course.
Note: Modern IDEs, like NetBeans and Eclipse,
automatically search for and add import statements for
you. In NetBeans, for example, use the Ctrl + Shift + I key
sequence to fix imports in your code.

Packages More on import


Import statements follow the package declaration
In Java, a package is a group of (class) types. There can be
and precede the class declaration.
only one package declaration for a file.
An import statement is not required.
Packages are more than just a convenience. Packages By default, your class always imports
create a namespace, a logical collection of things, like a java.lang.*
directory hierarchy.
You do not need to import classes that are in the
It is a good practice to always use a package same package:
declaration. The package declaration is always at the top
of the file.
Details about the java.lang package and its classes are
covered later in the course.
import Statements
The import keyword is used to identify classes you want Java is Pass-By-Value
to reference in your class.
The import statement provides a convenient The Java language (unlike C++) uses pass-by-value for all
way to identify classes that you want to reference assignment operations.
in your class. To visualize this with primitives, consider the
following:
You can import a single class or an entire
package:
The value of x is copied and passed to y:
You can include multiple import statements:

It is good practice to use the full package and


class name rather than the wildcard * to avoid
class name conflicts.

Imports
If x is later modified (for example, x = 5;), the
You could refer to a class using its fully qualified value of y remains unchanged.
namespace in your applications, as in the following The Java language uses pass-by-value for all assignment
example: operations. This means that the argument on the right side
java.util.Date date = new of the equal sign is evaluated, and the value of the
java.util.Date(); argument is assigned to the left side of the equal sign.
For Java primitives, this is straightforward. Java does not In the first line of code, a new object (Employee) is
pass a reference to a primitive (such as an integer), but created and the reference to that object is assigned to the
rather a copy of the value. variable x.
In the second line of code, the value of that reference is
passed to a method called foo.
Pass-By-Value for Object References When the foo method is called, (Employee e) holds a
For Java objects, the value of the right side of an reference to the Employee object, x. In the next line, the
assignment is a reference to memory that stores a Java value of e is now a new Employee object, by virtue of the
object. call to the constructor.
The reference to the x object is replaced by a reference to
a new object. The x object remains unchanged.
Note: The object e, created inside of the method foo, can
no longer be referenced when the method finishes. As a
The reference is some address in memory. result, it will be eligible for garbage collection at some
future point.
If the code in the foo method was written differently, like
this:
public void foo(Employee e) {
e.setSalary(1_000_000.00):
}
After the assignment, the value of y is the same Then referenced object that the setSalary method is
as the value of x: a reference to the same being called on is the object referenced by x, and after the
Employee object. foo method returns, the object x is modified.
For Java objects, the value of an object reference is the Note: The memory locations 42 and 99 are simply for
memory pointer to the instance of the Employee object illustrative purposes!
created.
When you assign the value of x to y, you are not creating
a new Employee object, but rather a copy of the value of How to Compile and Run
the reference. Java class files must be compiled before running them.
Note: An object is a class instance or an array. The To compile a Java source file, use the Java compiler
reference values (references) are pointers to these objects, (javac).
and a special null reference, which refers to no object.

Objects Passed as Parameters


Whenever a new object is created, a new You can use the CLASSPATH environment
reference is created. Consider the following code variable to the directory above the location of the
fragments: package hierarchy.
After compiling the source .java file, a .class
file is generated.
To run the Java application, run it using the Java
interpreter (java):
The value of x is unchanged as a result of the
method call foo:
CLASSPATH
The default value of the classpath is the current
working directory (.), however, specifying the
CLASSPATH variable or the -cp command line switch
overrides this value.
The CLASSPATH variable is used by both the Java
compiler and the Java interpreter (runtime).
The classpath can include:
A list of directory names (separated by Machine loads the compiled Java class files using a Java
semicolons in Windows and colons in UNIX) class of its own called the class
- The classes are in a package tree relative loader (java.lang.ClassLoader).
to any of the directories on the list. The class loader is called when a class member is
A .zip or .jar file name that is fully qualified used for the first time:
with its path name
- The classes in these files must be zipped
with the path names that are derived from
the directories formed by their package
names.
Note: The directory containing the root name of the
package tree must be added to the classpath. Consider Typically, the use of the class loader is completely
putting classpath information in the command invisible to you. You can see the results of the class loader
by using the -verbose flag when you run your
window or even in the Java command, rather than hard-
coding it in the environment. application. For example:
java -verbose -classpath D:\test
com.example.HelloWorld
Compiling and Running: Example [Loaded java.lang.Object from shared
objects file]
Assume that the class shown in the notes is in the [Loaded java.io.Serializable from
directory D:\test\com\example: shared objects file]
[Loaded java.lang.Comparable from
To run the application, you use the interpreter and shared objects file]
the fully qualified class name: [Loaded java.lang.CharSequence from
shared objects file]
[Loaded java.lang.String from shared
objects file]
[Loaded
The advantage of an IDE like NetBeans is that java.lang.reflect.GenericDeclaration
management of the class path, compilation, and from shared objects
running the Java application are handled through file]
the tool. [Loaded java.lang.reflect.Type from
shared objects file]
Example [Loaded
Consider the following simple class in a file named java.lang.reflect.AnnotatedElement from
HelloWorld.java in the D:\test\com\example shared objects file]
directory: [Loaded java.lang.Class from shared
package com.example; objects file]
public class HelloWorld { [Loaded java.lang.Cloneable from shared
public static void main (String [] objects file]
args) { [Loaded java.lang.ClassLoader from
if (args.length < 1) { shared objects file]
System.out.println("Hello ... and many more
World!");
} else {
System.out.println("Hello " + Garbage Collection
args[0] + "!");
} When an object is instantiated using the new keyword,
} memory is allocated for the object. The scope of an object
} reference depends on where the object is instantiated:

Java Class Loader


During execution of a Java program, the Java Virtual
When someMethod completes, the memory following fragment:
referenced by e is no longer accessible.
Javas garbage collector recognizes when an
instance is no longer accessible and eligible for
collection.
Note: When an objects memory is freed depends upon a
number of factors. a. Fred
Javas garbage collection scheme can be tuned depending b. Bob
on the type of application you are creating. For more c. null
information, consider taking the Oracle University course d. an empty String
Java Performance Tuning and Optimization Answer: b
(D69518GC10). 3. In the following fragment, what is the printed
result?

Summary
In this lesson, you should have learned how to:
Create simple Java classes
- Create primitive variables
- Manipulate Strings
a. 100.00
- Use if-else and switch branching
b. 150.00
statements
c. 166.66667
- Iterate with loops
d. 200.00
- Create arrays
Answer: c
Use Java fields, constructors, and methods
Arrays begin with an index of 0. This average
Use package and import statements
method is only averaging the 2nd through Nth
values. Therefore, the result is the average of 200
Quiz +300/3 = 166.66667. Change the for loop to int =
0; to properly calculate the average.
1. In the following fragment, what three issues can
you identify?
Practice 2-1 Overview: Creating Java
Classes
This practice covers the following topics:
Creating a Java class using the NetBeans IDE
a. An import statement is missing. Creating a Java class with a main method
b. The boolean valid is assigned a Writing code in the body of the main method to
String. create an instance of the Employee object and
c. String s is created using new. print values from the class to the console
d. BrokenClass method is missing a Compiling and testing the application using the
return statement. NetBeans IDE
e. Need to create a new BrokenClass
object.
f. The integer value i is assigned a double.
Answer: b and f will cause compilation errors.
c will compile but is not a good practice.
a. An import statement is not required, unless
the class uses classes outside of java.lang.
d. BrokenClass() is a constructor.
e. Construction of a BrokenClass instance
would typically happen in another class.
2. Using the Employee class defined in this
lesson, determine what will be printed in the
Encapsulation: Example
What data and operations would you encapsulate in an
Chapter 3 object that represents an employee?

Encapsulation and Subclassing

Objectives
After completing this lesson, you should be able to do the
following:
Use encapsulation in Java class design
Model business problems using Java classes
Make classes immutable
Create and use Java subclasses
Overload methods
A Simple Model
Use variable argument methods Suppose that you are asked to create a model of a typical
employee. What data might you want to represent in an
object that describes an employee?
Encapsulation Employee ID: You can use this as a unique
The term encapsulation means to enclose in a capsule, or identifier for the employee.
to wrap something around an object to cover it. In object- Name: Humanizing an employee is always a
oriented programming, encapsulation covers, or wraps, the good idea!
internal workings of a Java object. Social Security Number: For United States
Data variables, or fields, are hidden from the user employees only. You may want some other
of the object. identification for non-U.S. employees.
Methods, the functions in Java, provide an Salary: How much the employee makes is always
explicit service to the user of the object but hide good to record.
the implementation. What operations might you allow on the employee object?
As long as the services do not change, the Change Name: If the employee gets married or
implementation can be modified without divorced, there could be a name change.
impacting the user. Raise Salary: Increases based on merit.
The term encapsulation is defined by the Java Technology After an employee object is created, you probably do not
Reference Glossary as follows: want to allow changes to the Employee ID or Social
The localization of knowledge within a module. Because Security fields. Therefore, you need a way to create an
objects encapsulate data and implementation, the user of employee without alterations except through the allowed
an object can view the object as a black box that provides methods.
services. Instance variables and methods can be added,
deleted, or changed, but if the services provided by the
object remain the same, the code that uses the object can Encapsulation: Private Data, Public
continue to use it without being rewritten. Methods
An analogy for encapsulation is the steering wheel of a
car. When you drive a car, whether it is your car, a friends One way to hide implementation details is to declare all of
car, or a rental car, you probably never worry about how the fields private.
the steering wheel implements a right-turn or left-turn
function. The steering wheel could be connected to the
front wheels in a number of ways: ball and socket, rack
and pinion, or some exotic set of servo mechanisms.
As long as the car steers properly when you turn the
wheel, the steering wheel encapsulates the functions you
needyou do not have to think about the implementation.
Although the fields are now hidden using private
access, there are some issues with the current Employee
class.
The setter methods (currently public access )
allow any other class to change the ID, SSN, and
salary (up or down).
The current class does not really represent the
operations defined in the original Employee
class design.
Two best practices for methods:
- Hide as many of the implementation
In this example, the fields custID, name, and amount details as possible.
- Name the method in a way that clearly
are now marked private, making them invisible outside
identifies its use or functionality.
of the methods in the class itself.
The original model for the Employee class had
For example:
a Change Name and Increase Salary operation.
CheckingAccount ca = new
CheckingAccount(): Choosing Well-Intentioned Methods
ca.amount = 1_000_000_000.00; //
illegal! Just as fields should clearly define the type of data that
they store, methods should clearly identify the operations
that they perform. One of the easiest ways to improve the
Public and Private Access Modifiers readability of your code (Java code or any other) is to
write method names that clearly identify what they do.
The public keyword, applied to fields and
methods, allows any class in any package to
access the field or method. Employee Class Refined
The private keyword, applied to fields and
methods, allows access only to other methods
within the class itself.

The private keyword can also be applied to a


method to hide an implementation detail.

Revisiting Employee
The Employee class currently uses public access for
all of its fields. To encapsulate the data, make the fields
private. The current setter methods in the class allow any class that
uses an instance of Employee to alter the objects ID,
salary, and SSN fields. From a business standpoint, these
are not operations you would want on an employee. Once
the employee is created, these fields should be immutable
(no changes allowed).
The Employee model as defined in the slide titled
Encapsulation: Example had only two operations: one
for changing an employee name (as a result of a marriage
or divorce) and one for increasing an employees salary.
To refine the Employee class, the first step is to remove
Method Naming: Best Practices the setter methods and create methods that clearly identify
their purpose. Here there are two methods, one to change
an employee name (setName) and the other to increase
an employee salary (raiseSalary).
Note that the implementation of the setName method
tests the string parameter passed in to make sure that the
string is not a null. The method can do further checking as
necessary.

Make Classes as Immutable as


Possible Specialization Using Java Subclassing
The Manager class shown here closely resembles the
Employee class, but with some specialization. A
Manager also has a department, with a department name.
As a result, there are likely to be additional operations as
well.
What this demonstrates is that a Manager is an
Employeebut an Employee with additional features.
However, if we were to define Java classes this way, there
would be a lot of redundant coding!

Subclassing
In an object-oriented language like Java, subclassing is
used to define a new class in terms of an existing one.
Good Practice: Immutability
Finally, because the class no longer has setter methods,
you need a way to set the initial value of the fields. The
answer is to pass each field value in the construction of the
object. By creating a constructor that takes all of the fields
as arguments, you can guarantee that an Employee
instance is fully populated with data before it is a valid
employee object. This constructor replaces the no-arg
constructor.
Granted, the user of your class could pass null values, and
you need to determine if you want to check for those in
your constructor. Strategies for handling those types of
situations are discussed in later lessons.
Removing the setter methods and replacing the no-arg A Simple Java Program
constructor also guarantees that an instance of Employee
When an existing class is subclassed, the new class created
has immutable Employee ID and Social Security Number
is said to inherit the characteristics of the other class. This
(SSN) fields.
new class is called the subclass and is a specialization of
the superclass. All of the non-private fields and methods
from the superclass are part of the subclass.
Creating Subclasses So in this diagram, a Manager class gets empId, name,
You created a Java class to model the data and operations SSN, salary, and all of the public methods from
of an Employee. Now suppose you wanted to specialize Employee.
the data and operations to describe a Manager. It is important to grasp that although Manager
specializes Employee, a Manager is still an
Employee.
Note: The term subclass is a bit of a misnomer. Most
people think of the prefix sub- as meaning less.
However, a Java subclass is the sum of itself and its Write your own constructor.
parent. When you create an instance of a subclass, the Use the default constructor.
resulting in-memory structure contains all codes from the - If you do not declare a constructor, a
parent class, grandparent class, and so on all the way up default no-argument constructor is provided
the class hierarchy until you reach the class Object. for you.
- If you declare your own constructor, the
default constructor is no longer provided.
Manager Subclass
Constructors in Subclasses
Every subclass inherits the non-private fields and methods
from its parent (superclass). However, the subclass does
not inherit the constructor from its parent. It must provide
a constructor.
The Java Language Specification includes the following
description:
Constructor declarations are not members. They are
never inherited and therefore are not subject to hiding or
overriding.

Using super in Constructors


Java Syntax for Subclassing To construct an instance of a subclass, it is often easiest to
call the constructor of the parent class.
The keyword extends is used to create a subclass. In its constructor, Manager calls the constructor
The Manager class, by extending the Employee class, of Employee.
inherits all of the non-private data fields and methods from
Employee. After all, if a manager is also an employee, The super keyword is used to call a parents
then it follows that Manager has all of the same constructor.
attributes and operations of Employee. It must be the first statement of the constructor.
Note that the Manager class declares its own constructor. If it is not provided, a default call to super() is
Constructors are not inherited from the parent class. There inserted for you.
are additional details about this in the next slide. The The super keyword may also be used to invoke
constructor that Manager declares in line 4 calls the a parents method or to access a parents (non-
constructor of its parent class, Employee, using the private) field.
super keyword. This sets the value of all of the The Manager class declares its own constructor and calls
Employee fields: id, name, ssn, and salary. the constructor of the parent class using the super
Manager is a specialization of Employee, so keyword.
constructing a Manager requires a department name, Note: The super call of the parents constructor must
which is assigned to the deptName field in line 7. appear first in the constructor.
What other methods might you want in a model of The super keyword can also be used to explicitly call the
Manager? Perhaps you want a method that adds an methods of the parent class or access fields.
Employee to this Manager. You can use an array or a
special class called a collection to keep track of the
employees for whom this manager is responsible. For Constructing a Manager Object
details about collections, see the lesson titled Generics
and Collections. Creating a Manager object is the same as creating an
Employee object:

Constructors are not Inherited


Although a subclass inherits all of the methods and fields
from a parent class, it does not inherit constructors. There All of the Employee methods are available to
are two ways to gain a constructor: Manager:
You might want to design methods with the same intent
The Manager class defines a new method to get (method name), like print, to print out several different
the Department Name: types. You could design a method for each type:
printInt(int i)
Even though the Manager.java file does not contain printFloat(float f)
all of the methods from the Employee.java class printString(String s)
(explicitly), they are included in the definition of the But this would be tedious and not very object-oriented.
object. Thus, after you create an instance of a Manager Instead, you can create a reusable method name and just
object, you can use the methods declared in Employee. change the argument list. This process is called
You can also call methods that are specific to the overloading.
Manager class as well. With overloading methods, the argument lists must be
differentin order, number, or type. And the return types
can be different. However, two methods with the same
What is Polymorphism? argument list that differ only in return type are not
allowed.
The word polymorphism, strictly defined, means many
forms.
Methods Using Variable Arguments
A variation of method overloading is when you need a
method that takes any number of arguments of the same
This assignment is perfectly legal. An employee type:
can be a manager.
However, the following does not compile:

The Java compiler recognizes the emp variable


only as an Employee object. Because the
Employee class does not have a
setDeptName method, it shows an error. These three overloaded methods share the same
In object-oriented programming languages such as Java, functionality. It would be nice to collapse these
polymorphism is the ability to refer to an object using methods into one method.
either its actual form or a parent form.
This is particularly useful when creating a general-purpose
business method. For example, you can raise the salary of
any Employee object (parent or child) by simply passing
the object reference to a general-purpose business method
Methods with a Variable Number of
that accepts an Employee object as an argument. the Same Type
One case of overloading is when you need to provide a set
of overloaded methods that differ in the number of the
Overloading Methods same type of arguments. For example, suppose you want
Your design may call for several methods in the same to have methods to calculate an average. You may want to
class with the same name but with different arguments. calculate averages for 2, 3, or 4 (or more) integers.
Each of these methods performs a similar type of
computationthe average of the arguments passed in, as in
this example:
public class Statistics {
public float average(int x1, int x2)
Java permits you to reuse a method name for
{ return (x1 + x2) / 2; }
more than one method.
public float average(int x1, int x2,
Two rules apply to overloaded methods: int x3) {
- Argument lists must differ.
return (x1 + x2 + x3) / 3;
- Return types can be different.
}
Therefore, the following is not legal:
public float average(int x1, int x2,
int x3, int x4) {
return (x1 + x2 + x3 + x4) / 4;
}
}
Java provides a convenient syntax for collapsing these
three methods into just one and providing for any number
of arguments.
Java provides a feature called varargs or variable
arguments.

Note that the nums argument is actually an array Although Java does not permit more than one class to a
object of type int[]. This permits the method to subclass, the language does provide features that enable
iterate over and allow any number of elements. multiple classes to implement the features of other classes.
You will see this in the lesson on inheritance.
Using Variable Arguments Single inheritance does not prevent continued refinement
and specialization of classes as shown above.
The average method shown in the slide takes any In the diagram shown in the slide, a manager can have
number of integer arguments. The notation (int... employees, and a director has a budget and can approve
nums) converts the list of arguments passed to the expenses.
average method into an array object of type int.
Note: Methods that use varargs can also take no
parameters?an invocation of average() is legal. You Summary
will see varargs as optional parameters in use in the NIO.2
API in the lesson titled Java File I/O. To account for In this lesson, you should have learned how to:
this, you could rewrite the average method in the slide Create simple Java classes
as follows: Use encapsulation in Java class design
public float average(int... nums) { Model business problems using Java classes
int sum = 0; float result = 0; Make classes immutable
if (nums.length > 0) { Create and use Java subclasses
Overload methods
for (int x : nums) // iterate int
Use variable argument methods
array nums
sum += x;
result = (float) sum / nums.length; Quiz
}
return (result); 1. Given the diagram in the slide titled Single
} Inheritance and the following Java statements,
} which statements do not compile?

Single Inheritance a. e.addEmployee (a);


The Java programming language permits a class to extend b. m.addEmployee(a);
only one other class. This is called single inheritance. c. m.approveExpense
(100000.00);
d. All of them fail to compile.
Answer: a, c
a. A compiler error because the
Employee class does not have an
addEmployee method. This is a part
of the Manager class.
b. Compiles properly because, although the
constructor is creating a Director, it constant. It is in uppercase, however, it is
is the Manager class that the compiler not declared final and there is no
is looking at to determine if there is an assigned value.
addEmployee method 4. Follows the Java naming convention. It
c. A compiler error because the Manager clearly identifies its intent and will
class does not contain an calculate the offset between the two
approveExpense method coordinate pairs passed as arguments.
2. Consider the following classes that do not 4. What changes would you perform to make this
compile: class immutable? (Choose all that apply.)

What fix allows these classes to compile?


a. Make the fields symbol, shares, and
a. Add a no-arg constructor to Savings.
price private.
b. Call the setBalance method of
b. Remove setSymbol, setPrice, and
Account from Savings.
setShares.
c. Change the access of interestRate
c. Make the getStockValue method
to public.
private.
d. Replace the constructor in Savings
d. Add a constructor that takes symbol,
with one that calls the constructor of
shares, and price as arguments.
Account using super.
Answer: a, b, d
Answer: d
Immutable simply means that the object cannot
Savings must call the constructor of its parent
be changed after it is created. Making the fields
class (Account). To do that, you must replace
private prevents access from outside the class.
the current Savings constructor with one that
Removing the setter methods prevents changes.
includes an initial balance, and calls the Account Adding the constructor allows the object to be
constructor using super, as in this example: built for the first time with values. The
public Savings (double balance,
getStockValue method does not change any
double rate) {
of the fields of the object, so it does not need to
super(balance);
be removed.
interestRate = rate;
}
3. Which of the following declarations demonstrates
the application of good Java naming conventions?
Practice 3-1 Overview: Creating
1. public class repeat { } Subclasses
2. public void Screencoord
This practice covers the following topics:
(int x, int y){}
3. private int XCOORD; Applying encapsulation principles to the
4. public int calcOffset (int Employee class that you created in the previous
x1, int y1, int x2, int y2) practice
{ } Creating subclasses of Employee, including
Answer: d Manager, Engineer, and Administrative
1. Uses a lowercase first letter and a verb assistant (Admin)
for a class name. Class names should be Creating a subclass of Manager called
nouns with an initial uppercase letter. Director
2. Is a method name with its first letter Creating a test class with a main method to test
uppercase, rather than lower camel case your new Classes
(with the first letter lowercase and the
first letter of each name element in
uppercase). In addition, Screencoord (Optional) Practice 3-2 Overview:
sounds like a noun rather than a verb. Adding a Staff to a Manager
3. Is questionable because it appears to be a
This practice covers the following topics:
Creating an array of Employees called staff
Creating a method to add an employee to the
managers staff
Creating a method to remove an employee from
the managers staff
use protected are said to be subclass-friendly.
*Note: protected access is extended to subclasses that
reside in a package different from the class that owns the
Chapter 4 protected feature. As a result, protected fields or
methods are actually more accessible than those marked
Java Class Design with default access control. You should use protected
access when it is appropriate for a class's subclass, but not
unrelated classes.
Objectives
After completing this lesson, you should be able to do the Protected Access Control: Example
following:
Use access levels: private, protected,
default, and public
Override methods
Overload constructors and other methods
appropriately
Use the instance of operator to compare
object types
Use virtual method invocation
Use upward and downward casts
Override methods from the Object class to
improve the functionality of your class

Using Access Control


You have seen the keywords public and private. In this example, there are two classes in two packages.
There are four access levels that can be applied to data Class Foo is in the package demo, and declares a data
fields and methods. The following table illustrates access field called result with a protected access modifier.
to a field or method marked with the access modifier in In the class Bar, which extends Foo, there is a method,
the left column. reportSum, that adds the value of result to sum. The
method then attempts to add the value of other to sum.
The field other is declared using the default modifier,
and this generates a compiler error. Why?
Answer: The field result, declared as a protected
field, is available to all subclasses-even those in a different
package. The field other is declared as using default
access and is only available to classes and subclasses
declared in the same package.
This example is from the JavaAccessExample
Classes can be default (no modifier) or public. project.
The access modifier keywords shown in this table are
private, protected, and public. When a keyword
is absent, the default access modifier is applied.
Field Shadowing: Example
The private keyword provides the greatest control over
access to fields and methods. With private, a data field
or method can be accessed only within the same Java
class.
The public keyword provides the greatest access to
fields and methods, making them accessible anywhere: in
the class, package, subclasses, and any other class.
The protected keyword is applied to keep access
within the package and subclass. Fields and methods that
In this example, the class Foo2 declares the field Although the Employee class has getters to return values
result. However, the class Bar2 declares its own field for a print statement, it might be nice to have a utility
result. The consequence is that the field result from method to get specific details about the employee.
class Foo2 is shadowed by the field result in class Consider a method added to the Employee class to print
Bar2. What is sum in this example? sum is now 40 (10 + details about the Employee object.
30). Modern IDEs (such as Net Beans) detect shadowing In addition to adding fields or methods to a subclass, you
and produce a warning. can also modify or change the existing behavior of a
Methods with the same name are not shadowed but are method of the parent (superclass).
overridden. You learn about overriding later in this lesson. You may want to specialize this method to describe a
Manager object.
In the Manager class, by creating a method with the
Access Control: Good Practice same signature as the method in the Employee class, you
A good practice when working with fields is to make are overriding the getDetai1s method:
fields as inaccessible as possible, and provide clear intent
for the use of fields through methods.

A subclass can invoke a parent method by using the


super keyword.
When a method is overridden, it replaces the method in
the superclass (parent) class. This method is called for any
Manager instance.
A call of the form super.getDetails() invokes the
A slightly modified version of the example using the getDetails method of the parent class.
protected keyword is shown in the slide. If the idea is Note: If, for example, a class declares two public methods
to limit access of the field result to classes within the with the same name, and a subclass overrides one of them,
package and the subclasses (package-protected), you the subclass still inherits the other method.
should make the access explicit by defining a method
purposefully written for package and subclass-level
access. Invoking an Overridden Method
Using the previous examples of Employee and
Overriding Methods Manager:

Consider a requirement to provide a String that represents


some details about the Employee class fields.

The correct getDetails method of each class


is called:
During run time, the Java Virtual Machine invokes the
getDetails method of the appropriate class. If you
comment out the getDetails method in the Manager
class shown in the previous slide, what happens when
m.getDetails() is invoked? To override a method, the name and the order of
Answer: Recall that methods are inherited from the parent arguments must be identical.
class. So, at run time, the getDetails method of the When a method is a subclass overrides a method in the
parent class(Employee) is executed. parent class, it must provide the same or greater access
than the parent class. For example, if the parent method
get Details() on the slide was protected, then the
Virtual Method Invocation overriding method getDetails() in the subclass must be
protected or public.
What happens if you have the following?

Applying Polymorphism
During execution, the object's runtime type is
determined to be a Manager object: Suppose that you are asked to create a new class that
calculates a stock grant for employees based on their
The compiler is satisfied because the Employee salary and their role (manager, engineer, or admin):
class has a getDetails method, and at run
time the method that is executed is referenced
from a Manager object.
This is an aspect of polymorphism called virtual
method invocation.

Compiler Versus Runtime Behavior


The important thing to remember is the difference between
the compiler (which checks that each method and field is
accessible based on the strict definition of the class) and
the behavior associated with an object determined at run
time. Design Problem
This distinction is an important and powerful aspect of What is the problem in the example in the slide? Each
polymorphism: The behavior of an object is determined by method performs the calculation based on the type of
its runtime reference. employee passed in, and returns the number of shares.
Because the object you created was a Manager object, at Consider what happens if you add two or three more
run time, when the getDetails method was invoked, employee types. You would need to add three additional
the run time reference is to the getDetails method of a methods, and possibly replicate code depending upon the
Manager class, even though the variable e is of the type business logic required to compute shares.
Employee. Clearly, this is not a good way to treat this problem.
This behavior is referred to as virtual method invocation. Although the code will work, this is not easy to read and is
Note: If you are a C++ programmer, you get this behavior likely to create much duplicate code.
in C++ only if you mark the method using the C++ A good practice is to pass parameters and write methods
keyword virtual. that use the most generic form of your object as possible.

Accessibility of Overridden Methods


An overriding method must provide at least as much
access as the overridden method in the parent class.
Use the Most Generic Form Casting Object References
A good practice is to design and write methods that take In order to access a method in a subclass passed as an
the most generic form of your object as possible. generic argument, you must cast the reference to the class
In this case, Employee is a good base class to start from. that will satisfy the compiler:
Adding a method to Employee allows
EmployeeStockPlan to use polymorphism to
calculate stock.

Without the cast to Manager, the setDeptName


method would not compile.
Although a generic superclass reference is useful for
passing objects around, you may need to use a method
from the subclass.
In the slide, for example, you need the setDeptName
method of the Manager class. To satisfy the compiler,
you can cast a reference from the generic superclass to the
specific class.
However, there are rules for casting references. You see
In this modified EmployeeStockPlan, the these in the next slide.
grantStock method calls a method defined by the base Note: The instanceof operator shown on the slide is
class, Employee, that returns a base stock count. The not required by the compiler before the cast, however,
EmployeeStockPlan class uses a multiplier to without checking the object's type, if a non-Manager
determine how many stocks to grant. A class may override object type is passed to the modifyDeptForManager
the calculateStock method (as the Manager class method, an exception (ClassCastException) will be
does here) based on business policy. thrown at runtime.
In this approach, regardless of the number of different
Employee types (all extending the Employee object) the
EmployeeStockPlan class will always function.
Casting Rules
Upward casts are always permitted and do not require a
cast operator.
Using the instanceof Keyword
The Java language provides the ins tanceof keyword to
determine an object's class type at run time.

In this example, a class, EmployeeRequisition has a For downward casts, the compiler must be satisfied that
the cast is at least possible.
method that uses the instanceof keyword to determine
if the object can open an requisition for an employee. Per
the business policy, only Managers and above can open a
requisition for a new employee.
subclass Object by default.
Object defines several non-final methods that are
designed to be overridden by your class. These are
equals, hashCode, toString, clone, and
finalize. Of these, there are three methods that you
should consider overriding.

Downward Casts Object toString Method


With a downward cast, the compiler simply determines if The toString method is called to return the string value
the cast is possible; if the cast down is to a subclass, then it of an object. For example, using the method println:
is possible that the cast will succeed.
Note that at run time the cast results in a
java.lang.ClassCastException if the object
reference is of a superclass and not of the class type or a
String concatenation operations also invoke
subclass.
toString:
The cast of the variable e to a Manager reference m
satisfies the compiler, because Manager and Employee You can use toString to provide instance
are in the same class hierarchy, so the cast will possibly information:
succeed. This cast also works at run time, because it turns
out that the variable e is actually a Manager object. This
cast would also work at run time if e pointed to an
instance of a Director object. This is a better approach to getting details about
The cast of the variable m to a Director instance your class than creating your own getDetai1s
satisfies the compiler, but because m is actually a method.
Manager instance, this cast fails at run time with a The println method is overloaded with a number of
ClassCastException. parameter types. When you invoke
Finally, any cast will fail that is outside the class hierarchy, System.out.println(e); the method that takes an
such as the cast from a Manager instance to an Object parameter is matched and invoked. This method
Engineer. A Manager and an Engineer are both in turn invokes the toString() method on the object
employees, but a Manager is not an Engineer. instance.
Note: Sometimes you may want to be able to print out the
name of the class that is executing a method. The
Overriding Object Methods getClass() method is an Object method used to
return the Class object instance, and the getName()
One of the advantages of single inheritance is that every method provides the fully qualified name of the runtime
class has a parent object by default. The root class of every class.
Java class is java.lang.Object. getClass().getName(); // returns the
You do not have to declare that your class extends name of this class instance
Object. The compiler does that for you. These methods are in the Object class.

is equivalent to:
Object equals Method
The root class contains several non-final methods,
but there are three that are important to consider The Object equals method compares only object
overriding: references.
- toString, equals, and hashCode If there are two objects x and y in any class, x is
equal to y if and only if x and y refer to the same
Best Practice: Overload Object object.
Methods Example:

The java.lang.Object class is the root class of all


classes in the Java programming language. All classes will
Because what we really want is to test the
contents of the Employee object, we need to
override the equals method:

The equals method of Object determines (by default)


only if the values of two object references point to the
same object. Basically, the test in the Object class is
simply as follows: Overriding hashCode
The Java documentation for the Object class states:
lf x == y, return true. ... It is generally necessary to override the hashCode
method whenever this method [equals] is overridden, so
For an object (like the Employee object) that contains
as to maintain the general contract for the hashCode
values, this comparison is not sufficient, particularly if we
method, which states that equal objects must have equal
want to make sure there is one and only one employee
hash codes.
with a particular ID.
The hashCode method is used in conjunction with the
equals method in hash-based collections, such as
Overriding equals in Employee HashMap, HashSet, and Hashtable.
This method is easy to get wrong, so you need to be
An example of overriding the equals method in the careful. The good news is that IDEs such as NetBeans can
Employee class compares every field for equality: generate hashCode for you.
To create your own hash function, the following will help
approximate a reasonable hash value for equal and
unequal instances:
1. Start with a non-zero integer constant. Prime
numbers result in fewer hashcode collisions.
2. For each field used in the equals method,
compute an int hash code for the field. Notice
that for the Strings, you can use the
hashCode of the String.
3. Add the computed hash codes together.
4. Return the result.
This simple equals test first tests to make sure that the
object passed in is not null, and then tests to make sure Summary
that it is an instance of an Employee class (all subclasses
are also employees, so this works). Then the Object is In this lesson, you should have learned how to:
cast to Employee, and each field in Employee is Use access levels: private, protected,
checked for equality. default, and public
Note: For String types, you should use the equals Override methods
method to test the strings character by character for Overload constructors and other methods
equality. appropriately
Use the instanceof operator to compare
object types
Overriding Object hashCode Use virtual method invocation
Use upward and downward casts
The general contract for Object states that if two objects Override methods from the Object class to
are considered equal (using the equals method), then improve the functionality of your class
integer hashcode returned for the two objects should also
be equal.
Quiz
1. Suppose that you have an Account class with a
withdraw () method, and a Checking class
that extends Account that declares its own Practice 4-1 Overview: Overriding
withdraw () method. What is the result of the Methods and Applying Polymorphism
following code fragment?
This practice covers the following topics:
Modifying the Employee, Manager, and
a. The compiler complains about line 1. Director classes; overriding the tostring
b. The compiler complains about line 2. () method
c. Runtime error: incompatible assignment Creating an EmployeestockPlan class with a
(line 1) grant stock method that uses the instanceof
d. The Account.withdraw () method keyword
executes.
e. The Checking.withdraw ()
method executes.
Answer: e
Because the Checking class extends Account,
the withdraw method declared in Checking
overrides the withdraw method in Account.
At run time, the method for the object
(Checking) is executed.
2. Suppose that you have an Account class and a
Checking class that extends Account. The
body of the if statement in line 2 will execute.

a. True
b. False
Answer: a
Actually, acct is also an instanceof the
Account class.
3. Suppose that you have an Account class and a
Checking class that extends Account. You
also have a Savings class that extends
Account. What is the result of the following
code?

a. acct 3 contains the reference to acct


1.
b. A runtime ClassCastException
occurs.
c. The compiler complains about line 2.
d. The compiler complains about the cast in
line 3.
Answer: b
4. The compiler will assume that it is possible to
cast an Account type object to another
Account. Because Savings extends from
Account, this looks like a typical downward
cast. However, at run time, the true type of the
object is determined, and you cannot cast
between children.
a shared base type identified between two classes, any
shared code may be placed in a parent class.
When possible, use object references of the most generic
Chapter 5 base type possible. In Java, generalization and
specialization enable reuse through method inheritance
Advanced Class Design and virtual method invocation (VMI). VMI, sometimes
called late-binding, enables a caller to dynamically call
a method as long as the method has been declared in a
generic base type.
Objectives
After completing this lesson, you should be able to do the
following:
Enabling Generalization
Design general-purpose base classes by using Coding to a common base type allows for the introduction
abstract classes of new subclasses with little or no modification of any
Construct abstract Java classes and subclasses code that depends on the more generic base type.
Model business problems by using the static
and final keywords
Implement the singleton design pattern
Distinguish between top-level and nested classes
Always use the most generic reference type possible.

Modeling Business Problems with Coding for Generalization


Classes Always use the most generic reference type possible. Java
IDEs may contain refactoring tools that assist in changing
Inheritance (or subclassing) is an essential feature of the
existing references to a more generic base type.
Java programming language. Inheritance provides code
reuse through:
Method inheritance: Subclasses avoid code Identifying the Need for Abstract
duplication by inheriting method
implementations. Classes
Generalization: Code that is designed to rely on Subclasses may not need to inherit a method
the most generic type possible is easier to implementation if the method is specialized.
maintain.

Class Inheritance Diagram Method Implementations


Class Inheritance When sibling classes have a common method, it is
typically placed in a parent class. Under some
When designing an object-oriented solution, you should circumstances, however, the parent class's implementation
attempt to avoid code duplication. will always need to be overridden with a specialized
One technique to avoid duplication is to create library implementation.
methods and classes. Libraries function as a central point In these cases, inclusion of the method in a parent class
to contain often reused code. Another technique to avoid has both advantages and disadvantages. It allows the use
code duplication is to use class inheritance. When there is of generic reference types, but developers can easily forget
to supply the specialized implementation in the subclasses. - Declare the child class as abstract.
- Override all abstract methods inherited
from the parent class. Failure to do so will
Defining Abstract Classes result in a compile-time error.
A class can be declared as abstract by using the
abstract class-level modifier.

Making Use of Abstract Classes


An abstract class can be subclassed. While it is possible to avoid implementing an abstract
method by declaring child classes as abstract, this only
An abstract class cannot be instantiated. serves to delay the inevitable. Applications require non-
abstract methods to create objects. Use abstract methods to
outline functionality required in child classes.
Declaring a class as abstract prevents any instances of that
class from being created. It is a compile-time error to
instantiate an abstract class. An abstract class will Quiz
typically be extended by a child class and may be used as
a reference type. To compile successfully, an abstract method must not
have:
a. A return value
Defining Abstract Methods b. A method implementation
c. Method parameters
A method can be declared as abstract by using the
d. private access
abstract method-level modifier.
Answer: b, d

static Keyword
The static modifier is used to declare fields and
methods as class-level resources. Static class members:
Can be used without object instances
An abstract method: Are used when a problem is best solved without
Cannot have a method body objects
Must be declared in an abstract class Are used when objects of the same type need to
Is overridden in subclasses share fields
Should not be used to bypass the object-oriented
Inheriting Abstract Methods features of Java unless there is a good reason
When a child class inherits an abstract method, it is
inheriting a method signature but no implementation. For Java: Object-oriented by Design
this reason, no braces are allowed when defining an The Java programming language was designed as an
abstract method. An abstract method is a way to guarantee object-oriented language, unlike languages like Objective-
that any child class will contain a method with a matching C and C++, which inherited the procedural design of C.
signature. When developing in Java, you should always attempt to
design an object-oriented solution.
Validating Abstract Classes
The following additional rules apply when you use Static Methods
abstract classes and methods: Static methods are methods that can be called even if the
An abstract class may have any number of class they are declared in has not been instantiated. Static
abstract and non-abstract methods. methods:
When inheriting from an abstract class, you must Are called class methods
do either of the following: Are useful for APIs that are not object oriented.
- java.lang.Math contains many static When calling static methods, you should:
methods Qualify the location of the method with a class
Are commonly used in place of constructors to name if the method is located in a different class
perform tasks related to object initialization than the caller
Cannot access non-static members within the - Not required for methods within the same
same class class
Can be hidden in subclasses but not overridden Avoid using an object reference to call a static
- No virtual method invocation method

Factory Methods
In place of directly invoking constructors, you will often
Static Variables
use static methods to retrieve object references. Unless Static variables are variables that can be accessed even if
something unexpected happens, a new object is created the class they are declared in has not been instantiated.
whenever a constructor is called. A static factory method Static variables are:
could maintain a cache of objects for reuse or create new Called class variables
instances if the cache was depleted. A factory method may Limited to a single copy per JVM
also produce an object that subclasses the methods return Useful for containing shared data
type. - Static methods store data in static
Example: variables.
NumberFormat nf = - All object instances share a single copy of
NumberFormat.getInstance(); any static variables.
Initialized when the containing class is first
loaded
Implementing Static Methods
Class Loading
Application developer-supplied classes are typically
loaded on demand (first use). Static variables are
initialized when their enclosing class is loaded. An attempt
to access a static class member can trigger the loading of a
class.

Defining Static Variables

Static Method Limitations


Static methods can be used before any instances of their
enclosing class have been created. Chronologically
speaking, this means that in a running Java Virtual
Machine, there may not be any occurrences of the
containing classes instance variables. Static methods can
never access their enclosing classes instance variables or
call their non-static methods.

Persisting Static Variables


Calling Static Methods Many technologies that are used to persist application state
in Java only save instance variables. Maintaining a single
object that keeps track of shared state may be used as an
alternative to static variables.

Using Static Variables


When accessing static variables, you should:
Qualify the location of the variable with a class
name if the variable is located in a different class
than the caller
- Not required for variables within the same
class
Avoid using an object reference to access a static Performance Myths
variable
There is little to no performance benefit when you declare
Object References to Static Members a method as final. Methods should be declared as final
only to disable method overriding.
Just as using object references to static methods should be
avoided, you should also avoid using object references to
access static variables. If all the members of a class are
static, consider using a private constructor to prevent
Final Classes
object instantiation. A class can be declared final. Final classes may not be
extended.

Static Imports
A static import statement makes the static members of a
class available under their simple name.
Given either of the following lines:

Calling the Math.random()method can be Final Variables


written as:
The final modifier can be applied to variables. Final
variables may not change their values after they are
initialized. Final variables can be:
Class fields
Overusing static import can negatively affect the - Final fields with compile-time constant
readability of your code. Avoid adding multiple static expressions are constant variables.
imports to a class. - Static can be combined with final to
create an alwaysavailable, never-changing
variable.
Quiz Method parameters
The number of instances of a static variable is related to Local variables
the number of objects that have been created. Note: Final references must always reference the same
a. True object, but the contents of that object may be modified.
b. False Benefits and Drawbacks of Final
Answer: b
Variables
Final Methods Bug Prevention
Final variables can never have their values modified after
A method can be declared final. Final methods may not they are initialized. This behavior functions as a bug-
be overridden. prevention mechanism.
Thread Safety
The immutable nature of final variables eliminates any of
the concerns that come with concurrent access by multiple but there is a particular usage pattern you should avoid.
threads. Constants may provide a false sense of input validation or
Final Reference to Objects value range checking.
A final object reference only serves to prevent a Consider a method that should receive only one
reference from pointing to another object. If you are of three possible values:
designing immutable objects, you must prevent the
object's fields from being modified. Final references also
prevent you from assigning a value of null to the The following lines of code still compile:
reference. Maintaining an object's references prevents that
object from being available for garbage collection.
Runtime Range Checking
Declaring Final Variables In the example in the slide, you must perform a runtime
range check when using an int to represent state. Within
the setState method, an if statement can be used to
validate that only the values 0, 1, or 2 are accepted. This
type of check is performed every time the setState
method is called, resulting in additional overhead.

Typesafe Enumerations
Java 5 added a typesafe enum to the language. Enums:
Are created using a variation of a Java class
Provide a compile-time range check

Final Fields
An enum can be used in the following way:
Initializing
Final fields (instance variables) must be either of the
following:
Assigned a value when declared
Assigned a value in every constructor
Static and Final Combined Compile-Time Range Checking
A field that is both static and final is considered a constant. In the example in the slide, the compiler performs a
By convention, constant fields use identifiers consisting of compile-time check to ensure that only valid
only uppercase letters and underscores. PowerState instances are passed to the setState
method. No range checking overhead is incurred at run
time.
Quiz
A final field (instance variable) can be assigned a value
either when declared or in all constructors. Enum Usage
1. True Enum references can be statically imported.
2. False
Answer: a

When to Avoid Constants


public static final variables can be very useful,
Enums can be used as the expression in a switch A vocabulary used to discuss design
statement.
Design Pattern Catalogs
Pattern catalogs are available for many programming
languages. Most of the traditional design patterns apply to
any object-oriented programming language. One of the
most popular books, Design Patterns: Elements of
Reusable Object-Oriented Software, uses a combination of
C++, Smalltalk, and diagrams to show possible pattern
Note: When an enum is used in a switch statement, implementations. Many Java developers still reference this
only the enum constants can be used as labels for the case book because the concepts translate to any object-oriented
statements. language.
You learn more about design patterns and other Java best
practices in the Java Design Patterns course.
Complex Enums
Enums can have fields, methods, and private constructors. Singleton Pattern
The singleton design pattern details a class
implementation that can be instantiated only once.

Enum Constructors Implementing the Singleton Pattern


You may not instantiate an enum instance with new. The singleton design pattern is one of the creational design
patterns that are categorized in Design Patterns: Elements
of Reusable Object-Oriented Software.
Quiz To implement the singleton design pattern:
An enum can have a constructor with the following access 1. Use a static reference to point to the single
levels: instance. Making the reference final ensures that
a. public it will never reference a different instance.
b. protected 2. Add a single private constructor to the singleton
c. Default (no declared access level) class. The private modifier allows only same
d. private class access, which prohibits any attempts to
Answer: c, d instantiate the singleton class except for the
attempt in step 1.
3. A public factory method returns a copy of the
Design Patterns singleton reference. This method is declared static
to access the static field declared in step 1. Step 1
Design patterns are: could use a public variable, eliminating the need
Reusable solutions to common software for the factory method. Factory methods provide
development problems greater flexibility (for example, implementing a
Documented in pattern catalogs per-thread singleton solution) and are typically
- Design Patterns: Elements of Reusable used in most singleton implementations.
Object-Oriented Software, written by Erich To obtain a singleton reference, call the getInstance
Gamma et al. (the Gang of Four) method:
SingletonClass ref =
SingletonClass.getInstance(); Inner Classes Versus Static Nested
Classes
Nested Classes An inner class is considered part of the outer class and
inherits access to all the private members of the outer
A nested class is a class declared within the body of
class. The example in the slide shows an inner class,
another class. Nested classes:
which is a member class. Inner classes can also be
Have multiple categories
declared inside a method block (local classes).
Inner classes
A static nested class is not an inner class, but its
- Member classes
declaration appears similar with an additional static
- Local classes
modifier on the nested class. Static nested classes can be
- Anonymous classes
instantiated before the enclosing outer class and, therefore,
Static nested classes
are denied access to all non-static members of the
Are commonly used in applications with GUI
enclosing class.
elements
Can limit utilization of a helper class to the
enclosing toplevel Class Anonymous Inner Classes
Reasons to Use Nested Classes An anonymous class is used to define a class with no
name.
The following information is taken from
http://download.oracle.com/javase/tutorial/java/javaOO/
nested.html.
Logical Grouping of Classes
If a class is useful to only one other class, then it is logical
to embed it in that class and keep the two together. Nesting
such helper classes" makes their package more
streamlined.
Increased Encapsulation
Consider two top-level classes, A and B, where B needs
access to members of A that would otherwise be declared A Class with No Name
private. By hiding class B within class A, As members can In the example in the slide, the java.lang.Object
be declared private and B can access them. In addition, B
class is being subclassed, and it is that subclass that is
itself can be hidden from the outside world.
being instantiated. When you compile an application with
More Readable, Maintainable Code anonymous classes, a separate class file following a
Nesting small classes within top-level classes places the naming convention of Outer$1.class will be
code closer to where it is used. generated, where 1 is the index number of anonymous
classes in an enclosing class and Outer is the name of the
enclosing class.
Inner Class: Example Anonymous inner classes can also be local classes.

Quiz
Which of the following nested class types are inner
classes?
a. anonymous
b. local
c. static
d. member
Answer: a, b, d

Summary
In this lesson, you should have learned how to:
Design general-purpose base classes by using
abstract classes
Construct abstract Java classes and subclasses
Model business problems by using the static
and final keywords
Implement the singleton design pattern
Distinguish between top-level and nested classes

Practice 5-1 Overview: Applying the


Abstract Keyword
This practice covers the following topics:
Identifying potential problems that can be solved
using abstract classes
Refactoring an existing Java application to use
abstractclasses and methods

Practice 5-2 Overview: Applying the


Singleton Design Pattern
This practice covers using the static and final keywords
and refactoring an existing application to implement the
singleton design pattern.

Practice 5-3 Overview: (Optional)


Using Java Enumerations
This practice covers taking an existing application and
refactoring the code to use an enum.

(Optional) Practice 5-4 Overview:


Recognizing Nested Classes
This practice covers analyzing an existing Java application
and identifying the number and types of classes present.
- Methods must not have an
implementation {braces}.
Can contain constant fields
Chapter 6 Can be used as a reference type
Are an essential component of many design
Inheritance with Java Interfaces patterns
In Java, an interface outlines a contract for a class. The
contract outlined by an interface mandates the methods
that must be implemented in a class. Classes implementing
Objectives the contract must fulfill the entire contract or be declared
After completing this lesson, you should be able to do the abstract.
following:
Model business problems by using interfaces
Define a Java interface
Developing Java Interfaces
Choose between interface inheritance and class Public, top-level interfaces are declared in their
inheritance own .java file. You implement interfaces instead of
Extend an interface extending them.
Refactor code to implement the DAO pattern

Implementation Substitution
The ability to outline abstract types is a powerful feature
of Java. Abstraction enables:
Ease of maintenance
- Classes with logic errors can be
substituted with new and improved classes.
Implementation substitution
- The java.sql package outlines the
methods used by developers to
communicate with databases, but the Rules for Interfaces
implementation is vendor-specific.
Division of labor Access Modifiers
- Outlining the business API needed by an All methods in an interface are public, even if you
applications UI allows the UI and the forget to declare them as public. You may not declare
business logic to be developed in tandem. methods as private or protected in an interface.
Abstraction The contract that an interface outlines is a public API that
must be provided by a class.
You just learned how to define abstract types by using Abstract Modifier
classes. There are two ways to define type abstraction in Because all methods are implicitly abstract, it is
Java: abstract classes and interfaces. By writing code to redundant (but allowed) to declare a method abstract.
reference abstract types, you no longer depend on specific
Because all interface methods are abstract, you may not
implementing classes. Defining these abstract types may
provide any method implementation, not even an empty
seem like extra work in the beginning but can reduce
set of braces.
refactoring at a later time if used appropriately.
Implements and Extends
A class can extend one parent class and then implement a
Java Interfaces comma-separated list of interfaces.

Java interfaces are used to define abstract types.


Interfaces: Constant Fields
Are similar to abstract classes containing only
public abstract methods Interfaces can have constant fields.
Outline methods that must be implemented by a
class
Television implements ElectronicDevice .
Therefore, a Television is an instance of a
Television, an ElectronicDevice, and a
java.lang.Object.

Only constant fields are permitted in an interface. When Marker Interfaces


you declare a field in an interface, it is implicitly public, Marker interfaces define a type but do not outline
static, and final. You may redundantly specify these any methods that must be implemented by a class.
modifiers. Avoid grouping all the constant values for an
application in a single interface; good design distributes The only reason these type of interfaces exist is
the constant values of an application across many classes type checking.
and interfaces. Creating monolithic classes or interfaces
that contain large groupings of unrelated code does not
follow best practices for object-oriented design.

java.io.Serializable is a marker interface used


Interface References by Javas I/O library to determine if an object can have its
state serialized. When implementing Serializable,
You can use an interface as a reference type. When using you are not required to provide method implementations.
an interface reference type, you must use only the methods Testing (in the form of the instanceof operator) for the
outlined in the interface. serializability of an object is built into the standard I/O
libraries. You use this interface in the lesson titled Java I/
O Fundamentals.

Casting to Interface Types


You can cast to an interface type.
An interface-typed reference can be used only to reference
an object that implements that interface. If an object has
all the methods outlined in the interface but does not
implement the interface, you may not use the interface as a
reference type for that object. Interfaces implicitly include
all the methods from java.lang.Object.

instanceof Operator Casting Guidelines


You can use instanceof with interfaces.
Just as you do when casting to class types, if you cast to a
type that is invalid for that object, your application
generates an exception and is even likely to crash. To
verify that a cast will succeed, you should use an
instanceof test.
The example in the slide shows poor design because the
turnObjectOn() method operates only on
ElectronicDevices. Using instanceof and
casting adds overhead at run time. When possible, use a
compile-time test by rewriting the method as:
public static void turnObjectOn
(ElectronicDevice e) {
Television is an instance of an ElectronicDevice. e.turnOn();
Previously, you used instanceof on class types. Any }
type that can be used as a reference can be used as an
operand for the instanceof operator. In the slide, a
AmphibiousCar class must fulfill the contract
Using Generic Reference Types outlined by both MotorizedBoat and Boat:
Use the most generic type of reference wherever
possible:

Interfaces in Inheritance Hierarchies


By using an interface reference type, you can use
a different implementing class without running
the risk of breaking subsequent lines of code:

When creating references, you should use the most generic


type possible. This means that, for the object you are
instantiating, you should declare the reference to be of an
interface type or of a parent class type. By doing this, all
usage of the reference is not tied to a particular
implementing class and, if need be, you could use a
different implementing class. By using an interface that
several classes implement as the reference type, you have
the freedom to change the implementation without Interface Inheritances
affecting your code. An EmployeeDAOMemoryImpl Interfaces are used for a form of inheritance that is
typed reference could be used to invoke a method that referred to as interface inheritance. Java allows multiple
appears only in the EmployeeDAOMemoryImpl class. interface inheritance but only single class inheritance.
References typed to a specific class cause your code to be
more tightly coupled to that class and potentially cause
Extending an Implementing Class
greater refactoring of your code when changing If you write a class that extends a class that implements an
implementations. interface, the class you authored also implements the
interface. For example, AmphibiousCar extends
BasicCar. BasicCar implements Car; therefore,
Implementing and Extending AmphibiousCar also implements Car.

Classes can extend a parent class and implement


Interfaces Extending Interfaces
An interface can extend another interface. For example,
an interface:
the interface MotorizedBoat can extend the Boat
interface. If the AmphibiousCar class implements
You can also implement multiple interfaces: MotorizedBoat, then it must implement all methods
from Boat and MotorizedBoat.
Duplicate Methods
When you have a class that implements multiple
interfaces, directly or indirectly, the same method
signature may appear in different implemented interfaces.
Extends First If the signatures are the same, there is no conflict and only
If you use both extends and implements, extends one implementation is required.
must come first.

Quiz
Extending Interfaces A class can implement multiple interfaces.
Interfaces can extend interfaces: a. True
b. False
Answer: a
By implementing MotorizedBoat, the
persistence logic, it becomes easier for you to replace your
Design Patterns and Interfaces persistence implementation.
One of the principles of object-oriented design is
to: Program to an interface, not an
implementation.
Before the DAO Pattern
This is a common theme in many design patterns. Notice the persistence methods mixed in with the business
This principle plays a role in: methods.
- The DAO design pattern
- The Factory design pattern

Object-Oriented Design Principles


Program to an interface, not an implementation is a
practice that was popularized in the book Design Patterns:
Elements of Reusable Object-Oriented Software.
You can learn more about object-oriented design
principles and design patterns in the Java Design Patterns
course.

DAO Pattern
The Data Access Object (DAO) pattern is used when
creating an application that must persist information. The
DAO pattern:
Separates the problem domain from the
persistence mechanism
Uses an interface to define the methods used for
persistence. An interface allows the persistence Before the DAO Pattern
implementation to be replaced with:
- Memory-based DAOs as a temporary The Single-Responsibility Principle
solution The Employee class shown in the slide has methods that
- File-based DAOs for an initial release focus on two different principles or concerns. One set of
- JDBC-based DAOs to support database methods focuses on manipulating the representation of a
persistence person, and the other deals with persisting Employee
- Java Persistence API (JPA)-based DAOs objects. Because these two sets of responsibilities may be
to support database persistence modified at different points in the lifetime of your
applications, it makes sense to split them up into different
Why Separate Business and classes.
Persistence Code?
Just as the required functionality of an application will
influence the design of your classes, so will other
After the DAO Pattern
concerns. A desire for ease of maintenance and for the The DAO pattern moves the persistence logic out of the
ability to enhance an application also influences its design. domain classes and into separate classes.
Modular code that is separated by functionality is easier to
update and maintain.
By separating business and persistence logic, applications
become easier to implement and maintain at the expense
of additional classes and interfaces. Often these two types
of logic have different maintenance cycles. For example,
the persistence logic might need to be modified if the
database used by the application was migrated from
MySQL to Oracle 11g.
If you create interfaces for the classes containing the
This pattern eliminates direct constructor calls in favor of
invoking a method. A factory is often used when
implementing the DAO pattern.
In the example in the slide, you have no idea what type of
persistence mechanism is used by EmployeeDAO
because it is just an interface. The factory could return a
DAO implementation that uses files or a database to store
and retrieve data. As a developer, you want to know what
type of persistence is being used because it factors into the
performance and reliability of your application. But you
After Refactoring to the DAO Pattern do not want the majority of the code you write to be
tightly coupled with the type of persistence.
DAO Implementations
If you think that you might need to change your DAO The Factory
implementation at a later time to use a different
persistence mechanism, it is best to use an interface to The implementation of the factory is the only point in the
define the contract that all DAO implementations must application that should depend on concrete DAO classes.
meet.
Your DAO interfaces outline methods to create, read,
update, and delete data, although the method names can
vary. When you first implement the DAO pattern, you will
not see the benefit immediately. The payoff comes later,
when you start modifying or replacing code. In the lesson
titled Building Database Applications with JDBC, we
discuss replacing the memory-based DAO with file- and
For simplicity, this factory hardcodes the name of a
database-enabled DAOs.
concrete class to instantiate. You could enhance this
factory by putting the class name in an external source
The Need for the Factory Pattern such as a text file and use the java.lang.Class class
to instantiate the concrete subclass. A basic example of
The DAO pattern depends on using interfaces to define an using the java.lang.Class is the following:
abstraction. Using a DAO implementations constructor String name =
ties you to a specific implementation. "com.example.dao.EmployeeDAOMemoryImpl"
;
Class clazz = Class.forName(name);
EmployeDAO dao = (EmployeeDAO)
clazz.newInstance();

The DAO and Factory Together

Using the Factory Pattern


Using a factory prevents your application from being
tightly coupled to a specific DAO implementation.
Method Implementations Located Across Different
Classes

Clients Depending only on Abstract DAOs Limitations with Inheritance


Java supports only single class inheritance, which
Quiz eliminates the possibility of inheriting different
implementations of a method with the same signature.
A typical singleton implementation contains a factory Multiple interface inheritance does not pose the same
method. problem as class inheritance because there can be no
a. True conflicting method implementations in interfaces.
b. False
Answer: a
Composition
Code Reuse Object composition allows you to create more complex
objects.
Code duplication (copy and paste) can lead to maintenance To implement composition, you:
problems. You do not want to fix the same bug multiple 1. Create a class with references to other classes.
times. 2. Add same signature methods that forward to the
Dont repeat yourself! (DRY principle) referenced objects.
Reuse code in a good way:
- Refactor commonly used routines into
libraries.
- Move the behavior shared by sibling
classes into their parent class.
- Create new combinations of behaviors by
combining multiple types of objects
together (composition).
Copying and pasting code is not something that must
always be avoided. If duplicated code serves as a starting
point and is heavily modified, that may be an acceptable
situation for you to copy and paste lines of code. You
should be aware of how much copying and pasting is
Combining Multiple Classes Methods Through Composition
occurring in a project. Besides performing manual code and Forwarding
audits, there are tools you can use to detect duplicated
code. For one such example, refer to http:// Delegation
pmd.sourceforge.net/cpd.html.
Method delegation and method forwarding are two terms
that are often used interchangeably. Method forwarding is
Design Difficulties when you write a method that does nothing except pass
execution over to another method. In some cases,
Class inheritance allows for code reuse but is not very delegation may imply more than simple forwarding. For
modular. more on the difference between the two, refer to page 20
How do you create a SpyCarWithSunRoof? of the book Design Patterns: Elements of Reusable
Object-Oriented Software.
Composition Implementation

Composition with Interfaces to Support Polymorphism


Each delegate class that you use in a composition should
have an interface defined. When creating the composing
IDE Wizards Make Implementing class, you declare that it implements all of the delegate
interface types. By doing this, you create an object that is
Composition Easy a composition of other objects and has many types.
To implement composition with the NetBeans IDE, use Now we can say:
addCar(new SpyCarWithSunRoof());
the Insert Code tool as follows:
1. Right-click within the braces of the complex class
and choose Insert Code. Quiz
2. Select Delegate Method. The Generate
Delegate Methods dialog box appears. Method delegation is required to create complex objects
3. Select the method calls that you want to forward. using:
The methods are inserted for you. a. Polymorphism
Repeat these steps for each delegate class. b. Composition
Answer: b

Polymorphism and Composition


Polymorphism should enable us to pass any type of Car to
Summary
the addCar method. Composition does not enable In this lesson, you should have learned how to:
polymorphism unless. Model business problems by using interfaces
Define a Java interface
Choose between interface inheritance and class
inheritance
Extend an interface
Refactor code to implement the DAO pattern

Practice 6-1 Overview: Implementing


A Complex Car Object that Cannot be Passed to a Method an Interface
Expecting a Simple Car This practice covers the following topics:
Writing an interface
Code Reuse Implementing an interface
The ability to use the addCar method for any type of Creating references of an interface type
Car, no matter how complex, is another form of code Casting to interface types
reuse. We cannot currently say the following:
addCar(new SpyCarWithSunRoof());
Use interfaces for all delegate classes to support Practice 6-2 Overview: Applying the
polymorphism. DAO Pattern
This practice covers the following topics:
Rewriting an existing domain object with a
memory-based persistence implementation using
the DAO pattern
Leveraging an abstract factory to avoid
depending on concrete implementations

(Optional) Practice 6-3 Overview:


Implementing Composition
This practice covers the following topics:
Rewriting an existing application to better
support code reuse through composition
Using interfaces to enable polymorphism
Chapter 7
Generics and Collections

Objectives
After completing this lesson, you should be able to:
Create a custom generic class To create a generic version of the CacheAny class, a
Use the type inference diamond to create an variable named T is added to the class definition
object surrounded by angle brackets. In this case, T stands for
Create a collection without using generics type and can represent any type. As the example shows,
Create a collection by using generics the code has changed to use t instead of a specific type
Implement an ArrayList information. This change allows the CacheAny class to
Implement a Set store any type of object.
Implement a HashMap
T was chosen not by accident but by convention. A
Implement a stack by using a deque number of letters are commonly used with generics.
Use enumerated types
Note: You can use any identifier you want. The following
values are merely strongly suggested.
Generics Here are the conventions:
T: Type
Provide flexible type safety to your code E: Element
Move many common errors from runtime to K: Key
compile time V: Value
Provide cleaner, easier-to-write code S, U: Used if there are second types, third types,
Reduce the need for casting with collections or more
Are used heavily in the Java Collections API

Generics in Action
Simple Cache Class Without Generics
Compare the type-restricted objects to their generic
alternatives.

Note how the one generic version of the class can replace
any number of type-specific caching classes. The add()
The two examples in the slide show very simple caching
classes. Even though each class is very simple, a separate and get() functions work exactly the same way. In fact,
class is required for any object type. if the myMessage declaration is changed to generic, no
changes need to be made to the remaining code.
The example code can be found in the Generics project in
Generic Cache Class the TestCacheAny.java file.
The Collections API relies heavily on generics for
its implementation.
Generics with Type Inference A collection is a single object that manages a group of
Diamond objects. Objects in the collection are called elements.
Various collection types implement standard data
Syntax structures including stacks, queues, dynamic arrays, and
- There is no need to repeat types on the hashes. All the collection objects have been optimized for
right side of the statement. use in Java applications.
- Angle brackets indicate that type Note: The Collections classes are all stored in the
parameters are mirrored. java.util package. The import statements are not
Simplifies generic declarations shown in the following examples, but the import
Saves typing statements are required for each collection type:
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

The type inference diamond is a new feature in JDK 7. In Collection Types


the generic code, notice how the right-side type definition
is always equivalent to the left-side type definition. In
JDK 7, you can use the diamond to indicate that the right
type definition is equivalent to the left. This helps to avoid
typing redundant information over and over again.
Example: TestCacheAnyDiamond.java
Note: In a way, it works in an opposite way from a
normal Java type assignment. For example, Employee
emp = new Manager(); makes emp object an
instance of Manager.
But in the case of generics:
ArrayList<Manager> managementTeam = new
ArrayList<>();
It is the left side of the expression (rather than the right
side) that determines the type.

Quiz The diagram in the slide shows all the collection types that
descend from Collection. Some sample methods are
Which of the following is not a conventional abbreviation provided for both Collection and List. Note the use
for use with generics? of generics.
a. T: Table Characteristics of Implementation Classes
b. E: Element HashSet: A collection of elements that contains
c. K: Key no duplicate elements
d. V: Value TreeSet: A sorted collection of elements that
Answer: a contains no duplicate elements
ArrayList: A dynamic array implementation
Deque: A collection that can be used to
Collections implement a stack or a queue
A collection is a single object designed to manage Note: The Map interface is a separate inheritance tree and
a group of objects: is discussed later in the lesson.
- Objects in a collection are called
elements.
- Primitives are not allowed in a collection. List Interface
Various collection types implement many
common data structures: List is an interface that defines generic list
- Stack, queue, dynamic array, hash behavior.
- An ordered collection of elements what order. If an assumption were made that the list was
List behaviors include: only for Integer objects, a runtime error would occur
- Adding elements at a specific index on line 12.
- Adding elements to the end of the list On lines 10-16, with a non-generic collection, an
- Getting an element based on an index Iterator is used to iterate through the list of items.
- Removing an element based on an index Notice that a lot of casting is required to get the objects
- Overwriting an element based on an index back out of the list so you can print the data.
- Getting the size of the list In the end, there is a lot of needless syntactic
Use List as a reference type to hide sugar (extra code) working with collections in this way.
implementation details. If the line that adds the String to the ArrayList is
The List interface is the basis for all Collections classes commented out, the program produces the following
that exhibit list behavior. output:
Part number: 1111
Part number: 2222
ArrayList Implementation Class Part number: 3333
Is a dynamically growable array
- The list automatically grows if elements
exceed initial size. Generic ArrayList
Has a numeric index
- Elements are accessed by index.
- Elements can be inserted based on index.
- Elements can be overwritten.
Allows duplicate items

An ArrayList implements a List collection. The


implementation exhibits characteristics of a dynamically
growing array. A to-do list application is a good example
of an application that can benefit from an ArrayList.
With generics, things are much simpler. When the
ArrayList Without Generics ArrayList is initialized on line 3, any attempt to add an
invalid value (line 8) results in a compile-time error.
Note: On line 3, the ArrayList is assigned to a List
type. Using this style enables you to swap out the List
implementation without changing other code.

Generic ArrayList: Iteration and


Boxing

In the example in the slide, a part number list is created The enhanced for loop, or for-each loop,
using an ArrayList. Using syntax prior to Java version provides cleaner code.
1.5, there is no type definition. So any type can be added No casting is done because of autoboxing and
to the list as shown on line 8. So it is up to the unboxing.
programmer to know what objects are in the list and in Using the for-each loop is much easier and provides
much cleaner code. No casts are done because of the A set has no index.
autounboxing feature of Java. Duplicate elements are not allowed in a set.
You can iterate through elements to access them.
TreeSet provides sorted implementation.
Autoboxing and Unboxing As an example, a set can be used to track a list of unique
part numbers.
Simplifies syntax
Produces cleaner, easier-to-read code
Set Interface: Example
A set is a collection of unique elements.

Lines 9 and 10 show a traditional method for moving


between objects and primitives. Lines 12 and 13 show
boxing and unboxing.
Autoboxing and Unboxing
Autoboxing and unboxing are Java language features that A set is a collection of unique elements. This example uses
enable you to make sensible assignments without formal a TreeSet, which sorts the items in the set. If the
casting syntax. Java provides the casts for you at compile program is run, the output is as follows:
time. Item: one
Note: Be careful when using autoboxing in a loop. There Item: three
is a performance cost to using this feature. Item: two

Quiz Map Interface


Assuming a valid Employee class, and given this A collection that stores multiple key-value pairs
fragment: - Key: Unique identifier for each element in
a collection
- Value: A value stored in the element
associated with the key
Called associative arrays in other languages
Key Value

Key Value
What change is required to allow this code to compile? 101 Blue Shirt
a. Line 1: The (3) needs to be (4) 102 Black Shirt
b. Line 8: Need to cast elements.next() to 103 Gray Shirt
Employee before invoking getName()
c. Line 1: Object needs to be Employee A Map is good for tracking things like part lists and their
d. Line 5: The 3 needs to be 4 descriptions (as shown in the slide).
Answer: c

Map Types
Set Interface
A set is a list that contains only unique elements.
Deque Interface
A collection that can be used as a stack or a queue
Means double-ended queue (and is pronounced
deck)
A queue provides FIFO (first in, first out)
operations
- add(e) and remove() methods
A stack provides LIFO (last in, first out)
operations
- push(e) and pop() methods
Deque is a child interface of Collection (just like
Set and List).
A queue is often used to track asynchronous message
requests so they can be processed in order. A stack can be
very useful for traversing a directory tree or similar
The Map interface does not extend the Collection structures.
interface because it represents mappings and not a
collection of objects. Some of the key implementation
classes include: Stack with Deque: Example
TreeMap: A map where the keys are
automatically sorted.
HashTable: A classic associative array
implementation with keys and values.
HashTable is synchronized.
HashMap: An implementation just like
HashTable except that it accepts null keys and
values. Also, it is not synchronized.

Map Interface: Example

A deque (pronounced deck) is a doubled-ended queue.


Essentially this means that a deque can be used as a queue
(first in, first out [FIFO] operations) or as a stack (last in,
first out [LIFO] operations).

Ordering Collections
The Comparable and Comparator interfaces
are used to sort collections.
- Both are implemented using generics.
Using the Comparable interface:
The example shows how to create a Map and perform - Overrides the compareTo method
standard operations on it. The output from the program is: - Provides only one sort option
=== Part List === Using the Comparator interface:
Part#: 111111 Blue Polo Shirt - Is implemented by using the compare
Part#: 222222 Black T-Shirt method
Part#: 333333 Duke Hat - Enables you to create multiple
Comparator classes
- Enables you to create and use numerous
sorting options Negative number: s comes before the current
The Collections API provides two interfaces for ordering element.
elements: Comparable and Comparator. Positive number: s comes after the current
The Comparable interface is implemented in a class and element.
provides a single sorting option for the class. Zero: s is equal to the current element.
The Comparator interface enables you to create In cases where the collection contains equivalent values,
multiple sorting options. You plug in the designed option replace the code that returns zero with additional code that
whenever you want. returns a negative or positive number.
Both interfaces can be used with sorted collections, such
as TreeSet and TreeMap.
Comparable Test: Example
Comparable Interface
Using the Comparable interface:
Overrides the compareTo method
Provides only one sort option

In the example in the slide, an ArrayList of


ComparableStudent elements is created. After the list
is initialized, it is sorted using the Comparable
interface. The output of the program is as follows:
Name: George Washington ID: 3333
The slide shows how the ComparableStudent class GPA:3.4
relates to the Comparable interface and TreeSet. Name: John Adams ID: 2222 GPA:3.9
Name: Thomas Jefferson ID: 1111 GPA:3.8
Note: The ComparableStudent class has overridden
Comparable: Example the toString() method.

Comparator Interface
Using the Comparator interface:
Is implemented by using the compare method
Enables you to create multiple Comparator
classes
Enables you to create and use numerous sorting
options

This example in the slide implements the Comparable


interface and its compareTo method. Notice that
because the interface is designed using generics, the angle The slide shows two Comparator classes that can be
brackets define the class type that is passed into the used with the Student class. The example in the next
compareTo method. The if statements are included to slide shows how to use Comparator with an unsorted
demonstrate the comparisons that take place. You can also interface like ArrayList by using the Collections
merely return a result. utility class.
The returned numbers have the following meaning.
Notes
Comparator: Example The Collections utility class provides a
number of useful methods for various collections.
Methods include min(), max(), copy(), and
sort().
The Student class has overridden the
toString() method.

Quiz
Which interface would you use to create multiple sort
options for a collection?
a. Comparable
b. Comparison
c. Comparator
d. Comparinator
The example in the slide shows the Comparator classes Answer: c
that are created to sort based on Name and GPA. For the
name comparison, the if statements have been simplified.
Summary
In this lesson, you should have learned how to:
Comparator Test: Example Create a custom generic class
Use the type inference diamond to create an
object
Create a collection without using generics
Create a collection by using generics
Implement an ArrayList
Implement a Set
Implement a HashMap
Implement a stack by using a deque
Use enumerated types

Practice 7-1 Overview: Counting Part


Numbers by Using a HashMap
This practice covers the following topics:
The example in the slide shows how the two Creating a map to store a part number and count
Comparator objects are used with a collection. Creating a map to store a part number and
Note: Some code has been commented out to save space. description
Notice how the Comparator objects are initialized on Processing the list of parts and producing a report
lines 4 and 5. After the sortName and sortGpa
variables are created, they can be passed to the sort()
method by name. Running the program produces the Practice 7-2 Overview: Matching
following output. Parentheses by Using a Deque
Name: George Washington ID: 3333
GPA:3.4 This practice covers processing programming statements
Name: John Adams ID: 2222 GPA:3.9 to ensure that the number of parentheses matches.
Name: Thomas Jefferson ID: 1111 GPA:3.8
Name: John Adams ID: 2222 GPA:3.9
Name: Thomas Jefferson ID: 1111 GPA:3.8 Practice 7-3 Overview: Counting
Name: George Washington ID: 3333 Inventory and Sorting with
GPA:3.4
Comparators
This practice covers processing inventory transactions that
generate two reports sorted differently using
Comparators.
method as strings, regardless of their intended type. If an
application requires command-line arguments other than
type String (for example, numeric values), the
Chapter 8 application should convert the string arguments to their
respective types using the wrapper classes, such as the
String Processing Integer.parseInt method, which can be used to
convert the string argument that represents the numeric
integer to type int.
Objectives
After completing this lesson, you should be able to: Properties
Read data from the command line The java.util.Properties class is used to
Search strings load and save key-value pairs in Java.
Parse strings Can be stored in a simple text file:
Create strings by using a StringBuilder
Search strings by using regular expressions
Parse strings by using regular expressions
Replace strings by using regular expressions File name ends in .properties.
File can be anywhere that compiler can find it.
The benefit of a properties file is the ability to set values
Command-Line Arguments for your application externally. The properties file is
typically read at the start of the application and is used for
Any Java technology application can use default values. But the properties file can also be an
command-line arguments. integral part of a localization scheme, where you store the
These string arguments are placed on the values of menu labels and text for various languages that
command line to launch the Java interpreter after your application may support.
the class name: The convention for a properties file is
<filename>.properties, but the file can have any
Each command-line argument is placed in the extension you want. The file can be located anywhere that
args array that is passed to the static main the application can find it.
method:

When a Java program is launched from a terminal Loading and Using a Properties File
window, you can provide the program with zero or more
command-line arguments.
These command-line arguments enable the user to specify
the configuration information for the application. These
arguments are strings: either stand-alone tokens (such as
arg1) or quoted strings (such as "another arg").

In the code fragment, you create a Properties object.


Then, using a try statement, you open a file relative to
Example execution: the source files in your NetBeans project. When it is
loaded, the name-value pairs are available for use in your
application.
Properties files enable you to easily inject configuration
information or other application data into the application.

Command-line arguments are always passed to the main


Loading Properties from the
Command Line
Property information can also be passed on the
command line.
Use the -D option to pass key-value pairs:

For example, pass one of the previous values

Get the Properties data from the System


object: You can perform the printf format using both the String
class and any output stream. The slide shows several
Property information can also be passed on the command different string formatting examples. See the Java API
line. The advantage to passing properties from the documentation for details about all the options.
command line is simplicity. You do not have to open a file %s: String
and read from it. However, if you have more than a few %d: Decimal
parameters, a properties file is preferable. %f: Float
The program output is the following:
We have 002 Blue Polo shirts that cost
PrintWriter and the Console $24.99.
The PrintWriter class writes characters instead of We have 002 Blue Polo shirts that cost
bytes. The class implements all of the print methods found $24.99.
in PrintStream. We have 002 Blue Polo shirts that cost
$24.99.
We have 002 Blue Polo shirts that cost
$24.99.

Quiz
Which two of the following are valid formatted print
statements?
a. System.out.printf("%s Polo shirts
The PrintStream class converts characters into bytes cost $%3.2f.\n", "Red", "35.00");
using the platform's default character encoding. b. System.out.format("%s Polo shirts
cost $%3.2f.\n", "Red", "35.00");
Unlike the PrintStream class, if automatic flushing is
c. System.out.println("Red Polo
enabled it will be done only when one of the println, shirts cost $35.00.\n");
printf, or format methods is invoked, rather than d. System.out.print("Red Polo shirts
whenever a newline character is included in the output. cost $35.00.\n");
The example in the slide shows how to create the object Answer: a, b
using the autoFlush option. The true option is
required to force PrintWriter to flush each line
printed to the console. String Processing
StringBuilder for constructing string
printf format Built-in string methods
- Searching
Java provides many ways to format strings: - Parsing
printf and String.format - Extracting substring
Parsing with StringTokenizer
The first part of this section covers string functions that
are not regular expressions. When you perform simple
string manipulations, there are a number of very useful
built-in methods.
StringBuilder and
StringBuffer
StringBuilder and StringBuffer are the
preferred tools when string concatenation is
nontrivial.
- More efficient than +
Concurrency
- StringBuilder (not thread-safe)
- StringBuffer (thread-safe)
Set capacity to the size you actually need.
The code in the slide demonstrates some of the more
- Constant buffer resizing can also lead to
useful string methods of the String class.
performance problems.
equals(): Tests the equality of the contents of
The StringBuilder and StringBuffer classes are
two strings. This is preferable to ==, which tests
the preferred way to concatenate strings.
whether two objects point to the same reference.
contains(): Searches a string to see if it
StringBuilder: Example contains the string provided.
replace(): Searches for the string provided
and replaces all instances with the target string
provided. There is a replaceFirst() method
for replacing only the first instance.
substring(): Returns a string based on its
position in the string.
Running the programs in the slide returns the following
output:
It was found
It zwas the zworst of times
s the w

Using the split() Method

The example in the slide shows some common


StringBuilder methods. You can use
StringBuilder to insert text in position. Chaining
append calls together is a best practice for building strings.
The output from the program is as follows:
It was a dark and stormy night, the
lightning flashed and the thunder
rumbled.
The lightning struck...
[ 1 2 3 4 5 6 7 8 9 10 ] times
The simplest way to parse a string is using the split()
method. Call the method with the character (or characters)
Sample String Methods that will split the string apart. The result is captured in an
array.
Note: The delimiter can be defined using regular
expressions.
The output of the program in the slide is as follows:
Blue Shirt
Red Shirt
Black Shirt object can be iterated over based on a specific type. In this
Maroon Shirt case, a float is used.
The output from this code segment is as follows:
Values found: 1.1 2.2 3.3
Parsing with StringTokenizer FSum: 6.6000004

Regular Expressions
A language for matching strings of text
- Very detailed vocabulary
- Search, extract, or search and replace
With Java, the backslash (\) is not fun.
Java objects
- Pattern
- Matcher
- PatternSyntaxException
- java.util.regex
The StringTokenizer class does the same thing as
split() but takes a different approach. You must iterate
the tokens to get access to them. Also note that the Pattern and Matcher
delimiter , in this case means use both commas and
spaces as delimiters. Thus, the result from parsing is the Pattern: Defines a regular expression
following: Matcher: Specifies a string to search
Blue
Shirt
Red
Shirt
Black
Shirt
Maroon
Shirt

Scanner
A Scanner can tokenize a string or a stream. The Pattern and Matcher objects work together to
provide a complete solution.
The Pattern object defines the regular expression that
will be used for the search. As shown in the example, a
regular expression can be as simple as a word or phrase.
The Matcher object is then used to select the target
string to be searched. A number of methods are available
for matcher. They are covered in the following slides.
When run, the example produces the following output:
Found match!

Character Classes

A Scanner can be used to tokenize an input stream or a


Character Description
string. In addition, a Scanner can be used to tokenize
. Matches any single
numbers and convert them into any primitive number type.
character (letter, digit, or
Note how the Scanner is defined on line 7. The resulting
special character), except
end-of-line markers
[abc] Would match any a, b,
or c in that position
[^abc] Would match any character
that is not a, b, or c in
that position
[a-c] A range of characters (in
this case, a, b, and c)
| Alternation; essentially an
or indicator

Character classes enable you to match one character in a


number of ways.
The example in the slide shows two ways to find was
and a way to find times.
Character Class: Examples To make this happen in Java:
1. Create a Pattern object to store the regular
expression that you want to search with.
Target String It was the best of times 2. Create a Matcher object by passing the text to
be searched to your Pattern object and
returning a Matcher.
3. Call Matcher.find() to search the text with
the Pattern you defined.
Pattern Description Text Matched
4. Call Matcher.group() to display the
w.s Any sequence that It was the best of
characters that match your pattern.
starts with a w times
followed by any
character followed
by s.
Predefined Character Classes
w[abc]s Any sequence that It was the best of
starts with a w times
followed by a,
b, or c and
then s.
t[^aeo]mes Any sequence that It was the best of
starts with a t times
followed any A number of character classes are used repeatedly. These
character that is classes are turned into predefined character classes.
not a, e, or o Classes exist to identify digits, word characters, and white
followed by space.
mes.
White-Space Characters
\t: Tab character
The code for this example can be found in the
\n: New-line character
StringExamples project in the
\r: Carriage return
CustomCharClassExamples.java file.
\f: Form feed
\x0B: Vertical tab
Character Class Code: Examples
Predefined Character Class: Examples

Target String Jo told me 20 ways to San


Jose in 15 minutes. {m,} The previous character
appears m or more times.
(xx){n} This group of characters
repeats n times.
Pattern Description Text Matched
\\d\\d Find any two Jo told me 20 Quantifiers enable you to easily select a range of
digits.** ways to San Jose characters in your queries.
in 15 minutes.
\\sin\\s Find in Jo told me 20
surrounded by two ways to San Jose Quantifier: Examples
spaces and then in 15 minutes.
the next three
characters.
Target String Longlonglong ago, in a
\\Sin\\S Find in Jo told me 20 galaxy far far away
surrounded by two ways to San Jose
non-space in 15 minutes.
characters and
then the next three
characters. Pattern Description Text Matched
ago.* Find ago and Longlonglong ago,
** If there are additional matches in the current line, then 0 or all the in a galaxy far far
additional calls to find() will return the next match on characters away
that line. remaining on the
line.
Example:
Pattern p1 = Pattern.compile("\\d\\d"); gal.{3} Match gal plus Longlonglong ago,
Matcher m1 = p1.matcher(t); the next three in a galaxy far far
characters. This away
while (m1.find()){
replaces ... as
System.out.println("Found: " + used in a previous
m1.group()); example.
} (long){2} Find long Longlonglong ago,
Produces: repeated twice. in a galaxy far far
Found: 20 away
Found: 15
The code for this example can be found in the The code for this example can be found in the
StringExamples project in the StringExamples project in the
PredefinedCharClassExample.java file. QuantifierExample.java file.

Quantifiers Greediness
A regular expression always tries to grab as many
characters as possible.
Quantifier Description Use the ? operator to limit the search to the
* The previous character is shortest possible match.
repeated zero or more times.
+ The previous character is Target String Longlonglong ago, in a
repeated one or more times. galaxy far far away.
? The previous character must
appear once or not at all.
{n} The previous character
appears exactly n times. Pattern Description Text Matched
{m,n} The previous character ago.*far A regular Longlonglong ago,
appears from m to n times. expression always in a galaxy far far
grabs the most away. ^it.*?times The sequence that it was the best of
characters starts a line with times or it was the
possible. it followed by worst of times
ago.*?far The ? character Longlonglong ago, some characters
essentially turns in a galaxy far far and times, with
off greediness. away. greediness off.
\\sit.*times$ The sequence that it was the best of
A regular expression always tries to match the characters starts with it times or it was the
that return the most characters. This is known as the followed by some worst of times
greediness principle. Use the ? operator to limit the characters and
result to the fewest characters needed to match the pattern. ends the line with
The code for this example can be found in the times.
StringExamples project in the \\bor\\b.{3} Find or it was the best of
GreedinessExample.java file. surrounded by times or it was the
word boundaries, worst of times
plus the next three
Quiz characters.

Which symbol means that the character is repeated one or The code for this example can be found in the
more times? StringExamples project in the
a. *
BoundaryCharExample.java file.
b. +
c. .
d. ?
Answer: b
Quiz
Which symbol matches the end of a line?
a. *
Boundary Matchers b. +
c. $
d. ^
Answer: c
Anchor Description
^ Matches the beginning of a
line Matching and Groups
$ Matches the end of a line
\b Matches the start or the end
of a word
\B Does not match the start or
end of a word

Boundary characters can be used to match different parts


of a line.

Boundary: Examples
With regular expressions, you can use parentheses to
identify parts of a string to match. This example matches
the component parts of an email address. Notice how each
Target String it was the best of times or pair of parentheses is numbered. In a regular expression,
it was the worst of times group(0) or group() matches all the text matched
when groups are used. Here is the source code for the
example:
public class MatchingExample {
Pattern Description Text Matched public static void main(String[]
args){
String email = This practice covers using the String.split()
"george.washington@example.com"; method to parse text.
Pattern p1 = Pattern.compile
("(\\S+?)\\.(\\S+?)@(\\S+)");
Matcher m1 = p1.matcher(email); Practice 8-2 Overview: Creating a
if (m1.find()){
System.out.println("First:
Regular Expression Search Program
" + m1.group(1)); This practice covers creating a program that searches
System.out.println("Last: " through a text file using a regular expression.
+ m1.group(2));
System.out.println("Domain:
" + m1.group(3)); Practice 8-3 Overview: Transforming
System.out.println HTML by Using Regular Expressions
("Everything Matched: " + m1.group(0));
} This practice covers transforming the HTML of a file by
} using several regular expressions.
}

Using the replaceAll Method


Using the replaceAll method, you can search and
replace.

You can do a search-and-replace by using the


replaceAll method after performing a find. The output
from the program is as follows:
<p>This is an H1</p>

Summary
In this lesson, you should have learned how to:
Read data from the command line
Search strings
Parse strings
Create strings by using a StringBuilder
Search strings by using regular expressions
Parse strings by using regular expressions
Replace strings by using regular expressions

Practice 8-1 Overview: Parsing Text


with split()
Exception Handling in Java
Chapter 9 When using Java libraries that rely on external resources,
the compiler will require you to handle or declare the
Exceptions and Assertions exceptions that might occur.
Handling an exception means you must add in a
code block to handle the error.
Objectives Declaring an exception means you declare that a
method may fail to execute successfully.
After completing this lesson, you should be able to:
Define the purpose of Java exceptions The Handle or Declare Rule
Use the try and throw statements
Many libraries that you use will require knowledge of
Use the catch, multi-catch, and finally
exception handling. They include:
clauses
File IO (NIO: java.nio)
Autoclose resources with a try-with-resources
Database access (JDBC: java.sql)
statement
Handling an exception means you use a try-catch
Recognize common exception classes and
categories statement to transfer control to an exception-handling
Create custom exceptions and auto-closeable block when an exception occurs. Declaring an exception
resources means to add a throws clause to a method declaration,
Test invariants by using assertions indicating that the method may fail to execute in a specific
way. To state it another way, handling means it is your
problem to deal with and declaring means that it is
Error Handling someone elses problem to deal with.

Applications will encounter errors while executing.


Reliable applications should handle errors as gracefully as The try-catch Statement
possible.
Errors: The try-catch statement is used to handle exceptions.
Should be the exception and not the expected
behavior
Must be handled to create reliable applications
Can occur as the result of application bugs
Can occur because of factors beyond the control
of the application
- Databases becoming unreachable
- Hard drives failing

Returning a Failure Result


Some programming languages use the return value of a
method to indicate whether or not a method completed
successfully. For instance, in the C example int x =
The catch Clause
printf("hi");, a negative value in x would indicate a When an exception occurs inside of a try block,
failure. Many of Cs standard library functions return a execution will transfer to the attached catch block. Any
negative value upon failure. The problem is that the lines inside the try block that appear after exception are
previous example could also be written as printf skipped and will not execute. The catch clause should be
("hi"); where the return value is ignored. In Java, you used to:
also have the same concern; any return value can be Retry the operation
ignored. Try an alternate operation
When a method you are writing in the Java language fails Gracefully exit or return
to execute successfully, consider using the exception- Avoid having an empty catch block. Silently swallowing
generating and handling features available in the language an exception is a bad practice.
instead of using return values.
Exception Objects Dealing with Exceptions
A catch clause is passed a reference to a When an Exception object is generated and passed to a
java.lang.Exception object. The catch clause, it will be instantiated from a class that
java.lang.Throwable class is the parent class for represents the specific type of problem that occurred.
Exception and it outlines several methods that you may These exception-related classes can be divided into two
use. categories: checked and unchecked.
Unchecked Exceptions
java.lang.RuntimeException and
java.lang.Error and their subclasses are categorized
as unchecked exceptions. These types of exceptions
should not normally occur during the execution of your
application. You may use a try-catch statement to help
discover the source of these exceptions, but when an
application is ready for production use, there should be
Logging Exceptions little code remaining that deals with
RuntimeException and its subclasses. The Error
When things go wrong in your application, you will often
subclasses represent errors that are beyond your ability to
want to record what happened. Java developers have a
correct, such as the JVM running out of memory.
choice of several logging libraries including Apaches
Common RuntimeExceptions that you may have to
Log4j and the built-in java.util logging framework.
troubleshoot include:
While these logging libraries are beyond the scope of this
ArrayIndexOutOfBoundsException:
course, you may notice that IDEs such as NetBeans
Accessing an array element that does not exist
recommend that you should remove any calls to
NullPointerException: Using a reference
printStackTrace(). This is because production-
that does not point to an object
quality applications should use a logging library instead of
ArithmeticException: Dividing by zero
printing debug messages to the screen.

Exception Categories Quiz


1. A NullPointerException must be caught
The java.lang.Throwable class forms the basis of
by using a try-catch statement.
the hierarchy of exception classes. There are two main
categories of exceptions: a. True
Checked exceptions, which must be handled or b. False
declared Answer: b
Unchecked exceptions, which are not typically 2. Which of the following types are all checked
handled or declared exceptions (instanceof)?
a. Error
b. Throwable
c. RuntimeException
d. Exception
Answer: b, d

Handling Exceptions
You should always catch the most specific type of
exception. Multiple catch blocks can be associated with a
single try.
connections, you should always close them when they are
no longer needed. Attempting to close these resources
inside the try block can be problematic because you can
end up skipping the close operation. A finally block
always runs regardless of whether or not an error occurred
during the execution of the try block. If control jumps to
a catch block, the finally block will execute after the
catch block.
Sometimes the operation that you want to perform in your
finally block may itself cause an Exception to be
generated. In that case, you may be required to nest a
try-catch inside of a finally block. You may also
Checked Exceptions nest a try-catch inside of try and catch blocks.
Every class that is a subclass of Exception except
RuntimeException and its subclasses falls into the
category of checked exceptions. You must handle or
The try-with-resources Statement
declare these exceptions with a try or throws Java SE 7 provides a new try-with-resources statement
statement. The HTML documentation for the Java API that will autoclose resources.
(Javadoc) will describe which checked exceptions may be
generated by a method or constructor and why.
Catching the most specific type of exception enables you
to write catch blocks that are targeted at handling very
specific types of errors. You should avoid catching the
base type of Exception, because it is difficult to create
a general purpose catch block that can deal with every
possible error.
Note: Exceptions thrown by the Java Persistence API
(JPA) extend RuntimeException and as such they are
categorized as unchecked exceptions. These exceptions
may need to be handled or declared in production-ready
code, even though you are not required to do so by the
Closeable Resources
compiler. The try-with-resources statement can eliminate
the need for a lengthy finally block. Resources opened
using the try-with-resources statement are always closed.
The finally Clause Any class that implements the
java.lang.AutoCloseable can be used as a
resource. If a resource should be autoclosed, its reference
must be declared within the try statements parentheses.
Multiple resources can be opened if they are separated by
semicolons. If you open multiple resources, they will be
closed in the opposite order in which you opened them.

Suppressed Exceptions
If an exception occurs in the try block of a try-with-
resources statement and an exception occurs while closing
the resources, the resulting exceptions will be suppressed.

Closing Resources
When you open resources such as files or database
Resource Exceptions
If an exception occurs while creating the
AutoCloseable resource, control will immediately The Benefits of multi-catch
jump to a catch block. Sometimes you want to perform the same action
If an exception occurs in the body of the try block, all regardless of the exception being generated. The new
resources will be closed before the catch block runs. If multi-catch clause reduces the amount of code you must
an exception is generated while closing the resources, it write, by eliminating the need for multiple catch clauses
will be suppressed. with the same behaviors.
If the try block executes with no exceptions, but an Another benefit of the multi-catch clause is that it makes
exception is generated during the closing of a resource, it less likely that you will attempt to catch a generic
control will jump to a catch block. exception. Catching Exception prevents you from
noticing other types of exceptions that might be generated
by code that you add later to a try block.
The AutoCloseable Interface The type alternatives that are separated with vertical bars
Resource in a try-with-resources statement must cannot have an inheritance relationship. You may not list
implement either: both a FileNotFoundException and an
java.lang.AutoCloseable IOException in a multi-catch clause.
- New in JDK 7 File I/O and object serialization are covered in the lesson
- May throw an Exception titled Java I/O Fundamentals.
java.io.Closeable
- Refactored in JDK7 to extend
AutoCloseable Declaring Exceptions
- May throw an IOException You may declare that a method throws an exception
instead of handling it.

AutoCloseable vs. Closeable


The Java API documentation has the following to say
about AutoCloseable: Note that unlike the close
method of Closeable, this close method is not required
to be idempotent. In other words, calling this close method
more than once may have some visible side effect, unlike Using the throws clause, a method may declare that it
Closeable.close, which is required to have no effect throws one or more exceptions during execution. If an
if called more than once. However, implementers of this exception is generated while executing the method, the
interface are strongly encouraged to make their close method will stop executing and the exception will be
methods idempotent. thrown to the caller. Overridden methods may declare the
same exceptions, fewer exceptions, or more specific
exceptions, but not additional or more generic exceptions.
Catching Multiple Exceptions A method may declare multiple exceptions with a comma-
Java SE 7 provides a new multi-catch clause. separated list.
public static int readByteFromFile()
throws FileNotFoundException,
IOException {
try (InputStream in = new Precise Rethrow
FileInputStream(a.txt)) {
System.out.println(File open); Java SE 7 supports rethrowing the precise exception type.
return in.read(); The following example would not compile with Java SE 6
} because the catch clause receives an Exception, but
} the method throws an IOException. For more about
Technically you do not need to declare the new precise rethrow feature, see http://
FileNotFoundException, because it is a subclass of download.oracle.com/javase/7/docs/technotes/guides/
IOException, but it is a good practice to do so. language/catchmultiple. html#rethrow.
public static int readByteFromFile()
throws IOException {
try {
Handling Declared Exceptions InputStream in = new
The exceptions that methods may throw must still be FileInputStream(a.txt);
handled. Declaring an exception just makes it someone System.out.println(File open);
elses job to handle them. return in.read();
} catch (Exception e) {
e.printStackTrace();
throw e; }
}

Custom Exceptions
You can create custom exception classes by extending
Exception or one of its subclasses.
Handling Exceptions
Your application should always handle its exceptions.
Adding a throws clause to a method just delays the
handling of the exception. In fact, an exception can be
thrown repeatedly up the call stack. A standard Java SE
application must handle any exceptions before they are
thrown out of the main method; otherwise, you risk
having your program terminate abnormally. It is possible
to declare that main throws an exception, but unless you
are designing programs to terminate in a nongraceful
fashion, you should avoid doing so. Custom exceptions are never thrown by the standard Java
class libraries. To take advantage of a custom exception
class, you must throw it yourself. For example:
Throwing Exceptions throw new DAOException();
You can rethrow an exception that has already been A custom exception class may override methods or add
caught. Note that there is both a throws clause and a new functionality. The rules of inheritance are the same,
throw statement. even though the parent class type is an exception.
Because exceptions capture information about a problem
that has occurred, you may need to add fields and methods
depending on the type of information that needs to be
captured. If a string can capture all the necessary
information, you can use the getMessage() method
that all Exception classes inherit from Throwable.
Any Exception constructor that receives a string will
store it to be returned by getMessage().

Quiz
Which keyword would you use to add a clause to a A file-based DAO must deal with IOExceptions and a
method stating that the method might produce an JDBC-based DAO must deal with SQLExceptions. If
exception? these types of exceptions were thrown by a DAO, any
a. throw clients would be tied to an implementation instead of an
b. thrown abstraction. By modifying the DAO interface and
c. throws implementing classes to throw a wrapper exception
d. assert (DAOException), you can preserve the abstraction and
Answer: c let clients know when a DAO implementation encounters
a problem.

Wrapper Exceptions
To hide the type of exception being generated without Assertions
simply swallowing the exception, use a wrapper Use assertions to document and verify the
exception. assumptions and internal logic of a single
method:
- Internal invariants
- Control flow invariants
- Postconditions and class invariants
Inappropriate uses of assertions. Assertions can
be disabled at run time; therefore:
- Do not use assertions to check the
parameters of a public method.
- Do not use methods that can cause side
effects in the assertion check.

Why Use Assertions


Getting the Cause
You can use assertions to add code to your applications
The Throwable class contains a getCause() method that ensures that the application is executing as expected.
that can be used to retrieve a wrapped exception. Using assertions, you test for various conditions failing; if
try { they do, you terminate the application and display
debugging-related information. Assertions should not be
//... used if the checks to be performed should always be
} catch (DAOException e) { executed because assertion checking may be disabled.
Throwable t = e.getCause();
} Assertion Syntax
Syntax of an assertion is:
Revisiting the DAO Pattern assert <boolean_expression> ;
assert <boolean_expression> :
The DAO pattern uses abstraction (an interface) to allow <detail_expression> ;
implementation substitution. A file or database DAO must If <boolean_expression> evaluates
deal with exceptions. A DAO implementation may use a false, then an AssertionError is thrown.
wrapper exception to preserve the abstraction and avoid The second argument is converted to a string and
swallowing exceptions. used as descriptive text in the
AssertionError message.

The assert Statement


Assertions combine the exception-handling mechanism of
Java with conditionally executed code. The following is a
pseudo-code example of the behavior of assertions:
if (AssertionsAreEnabled) {
if (condition == false) throw new
DAO Exceptions AssertionError();
} fast as if the check were never there.
AssertionError is a subclass of Error and, Assertion checks are disabled by default. Enable
therefore, falls in the category of unchecked exceptions. assertions with either of the following commands:

Internal Invariants
Assertion checking can be controlled on class,
The problem is: package, and package hierarchy basis. See: http://
download.oracle.com/javase/7/docs/technotes/
guides/language/assert.html

The solution is: Quiz


Assertions should be used to perform user-input
validation?
a. True
b. False
Answer: b

Control Flow Invariants


Summary
Example:
In this lesson, you should have learned how to:
Define the purpose of Java exceptions
Use the try and throw statements
Use the catch, multi-catch, and finally
clauses
Autoclose resources with a try-with-resources
statement
Recognize common exception classes and
categories
Create custom exceptions and auto-closeable
resources
Test invariants using assertions

Postconditions and Class Invariants


Practice 9-1 Overview: Catching
Example:
Exceptions
This practice covers the following topics:
Adding try-catch statements to a class
Handling exceptions

Practice 9-2 Overview: Extending


Exception
This practice covers the following topics:
Adding try-catch statements to a class
Handling exceptions
Extending the Exception class
Controlling Runtime Evaluation of Creating a custom auto-closeable resource
Assertions Using a try-with-resources statement
Throwing exceptions using throw and throws
If assertion checking is disabled, the code runs as
In this practice, you update a DAO pattern implementation
to use a custom wrapper exception.
A stream is a flow of data. A stream can come from a
source or can be generated to a sink.
A source stream initiates the flow of data, also
Chapter 10 called an input stream.
A sink stream terminates the flow of data, also
Java I/O Fundamentals called an output stream.
Sources and sinks are both node streams. Types of node
streams are files, memory, and pipes between threads or
processes.
Objectives
After completing this lesson, you should be able to:
Describe the basics of input and output in Java
I/O Application
Read data from and write data to the console Typically, there are three ways a developer may use input
Use streams to read and write files and output:
Read and write objects by using serialization

Java I/O Basics


The Java programming language provides a
comprehensive set of libraries to perform input/output (I/
O) functions.
Java defines an I/O channel as a stream.
An I/O Stream represents an input source or an
output destination.
A stream can represent many different kinds of
sources and destinations, including disk files,
devices, other programs, and memory arrays.
Streams support many different kinds of data, An application developer typically uses I/O streams to
including simple bytes, primitive data types, read and write files, to read and write information to and
localized characters, and objects. from some output device, such as the keyboard (standard
Some streams simply pass on data; others manipulate and in) and the console (standard out). Finally, an application
transform the data in useful ways. may need to use a socket to communicate with another
application on a remote system.

I/O Streams Data Within Streams


A program uses an input stream to read data from
a source, one item at a time. Java technology supports two types of streams:
character and byte.
Input and output of character data is handled by
readers and writers.
Input and output of byte data is handled by input
streams and output streams:
- Normally, the term stream refers to a byte
A program uses an output stream to write data to stream.
a destination (sink), one item at time. - The terms reader and writer refer to
character streams.

Stream Byte Streams Character


Streams
Source streams InputStream Reader
Sink streams OutputStream Writer
No matter how they work internally, all streams presentthe
same simple model to programs that use them: A stream is
Java technology supports two types of data in streams: raw
a sequence of data.
bytes and Unicode characters. Typically, the term stream from the stream.
refers to byte streams and the terms reader and writer The markSupported(), mark (), and reset()
refer to character streams. methods perform push-back operations on a stream, if
More specifically, byte input streams are implemented by supported by that stream. The markSupported()
subclasses of the InputStream class and byte output method returns true if the mark() and reset()
streams are implemented by subclasses of the methods are operational for that particular stream. The
OutputStream class. Character input streams are mark(int) method indicates that the current point in the
implemented by subclasses of the Reader class and stream should be noted and a buffer big enough for at least
character output streams are implemented by subclasses of the specified argument number of bytes should be
the Writer class. allocated. The parameter of the mark(int) method
Byte streams are best applied to reading and writing or specifies the number of bytes that can be re-read by calling
raw bytes (such as image files, audio files, and objects). reset () . After subsequent read() operations, calling the
Specific subclasses provide methods to provide specific reset() method returns the input stream to the point
support for each of these stream types. you marked. If you read past the marked buffer, reset()
Character streams are designed for reading characters has no meaning.
(such as in files and other character? based streams).

Byte Stream OutputStream


Byte Stream InputStream Methods Methods
The three basic read methods are:
The three basic write methods are:

Other methods include:


Other methods include:

OutputStream Methods
As with input, always try to write data in the largest
InputStream Methods practical block.
The read() method returns an int, which contains
either a byte read from the stream, or a -1, which Byte Stream Example
indicates the end-of-file condition. The other two read
methods read the stream into a byte array and return the
number of bytes read. The two int arguments in the third
method indicate a subrange in the target array that needs to
be filled.
Note: For efficiency, always read data in the largest
practical block, or use buffered streams.
When you have finished with a stream, close it. If you
have a stack of streams, use filter streams to close the
stream at the top of the stack. This operation also closes
the lower streams.
Note: In Java SE 7, InputStream implements
AutoCloseable, which means that if you use an
InputStream (or one of its subclasses) in a try-with-
resources block, the stream is automatically closed at the
end of the try.
The available method reports the number of bytes that This example copies one file to another by using a byte
are immediately available to be read from the stream. An array. Note that FileinputStream and
actual read operation following this call might return more FileOutputStream are meant for streams of raw
bytes. bytes like image files.
The skip method discards the specified number of bytes
Note: The available() method, according to the
Javadocs, reports an estimate of the number of remaining
bytes that can be read (or skipped over) from this input
stream without blocking.

Character Stream Reader Methods


The three basic read methods are:

Other methods include:

Similar to the byte stream example, this application copies


one file to another by using a character array instead of a
Reader Methods byte array. FileReader and FileWriter are classes
designed to read and write character streams, such as text
The first method returns an int, which contains either a files.
Unicode character read from the stream, or a -1, which
indicates the end-of-file condition. The other two methods
read into a character array and return the number of bytes I/O Stream Chaining
read. The two int arguments in the third method indicate
a subrange in the target array that needs to be filled.

Character Stream Writer Methods


The basic write methods are:

Other methods include:

Writer Methods
The methods are analogous to the OutputStream A program rarely uses a single stream object. Instead, it
methods. chains a series of streams together to process the data. The
first figure in the slide demonstrates an example of input
stream; in this case, a file stream is buffered for efficiency
Character Stream Example and then converted into data (Java primitives) items. The
second figure demonstrates an example of output stream;
in this case, data is written, then buffered, and finally
written to a file.

Chained Streams Example


Counting LineNumberReade LineNumberInput
r Stream
Peeking ahead PushbackReader PushbackInputStre
am
Printing PrintWriter PrintStream

A processing stream performs a conversion on another


stream. You choose the stream type that you want based on
the functionality that you need for the final stream.

Console I/O
The System class in the java.lang package has three
Here is the copy application one more time. This version static instance fields: out, in, and err.
illustrates the use of a BufferedReader chained to the The System.out field is a static instance of a
FileReader that you saw before. PrintStream object that enables you to write
The flow of this program is the same as before. Instead of to standard output.
reading a character buffer, this program reads a line at a The System.in field is a static instance of an
time using the line variable to hold the String returned InputStream object that enables you to read
by the readLine method, which provides greater from standard input.
efficiency. The reason is that each read request made of a The System.err field is a static instance of a
Reader causes a corresponding read request to be made PrintStream object that enables you to write
of the underlying character or byte stream. A to standard error.
BufferedReader reads characters from the stream into
a buffer (the size of the buffer can be set, but the default Console I/O Using System
value is generally sufficient.) System.out is the standard output stream. This
stream is already open and ready to accept output
data. Typically, this stream corresponds to display
Processing Streams output or another output destination specified by
the host environment or user.
System.in is the standard input stream. This
Functionality Character Byte Streams stream is already open and ready to supply input
Streams data. Typically, this stream corresponds to
keyboard input or another input source specified
Buffering (Strings) BufferedReader BufferedInputStre
by the host environment or user.
BufferedWriter am
System.err is the standard error output stream.
BufferedOutputStr
This stream is already open and ready to accept
eam
output data. Typically, this stream corresponds to
Filtering FilterReader FilterInputStream display output or another output destination
FilterWriter specified by the host environment or user. By
FilterOutputStrea convention, this output stream is used to display
m error messages or other information that should
Conversion (byte InputStreamReade come to the immediate attention of a user even if
to character) r the principal output stream, the value of the
OutputStreamWrit variable out, has been redirected to a file or other
er destination that is typically not continuously
Object ObjectInputStream monitored.
serialization
ObjectOutputStrea
m java.io.Console
Data conversion DataInputStream
In addition to the PrintStream objects, System can
DataOutputStream also access an instance of the java.io.Console
object:
Reading from Standard Input

Note that you should pass the username and


password to an authentication process.
The Console object represents the character-based
console associate with the current JVM. Whether a virtual
machine has a console depends on the underlying platform
and also upon the manner in which the virtual machine is
invoked. The try-with-resources statement on line 6 opens
NetBeans, for example, does not have a console. To run BufferedReader, which is chained to an
the example in the project SystemConsoleExample, InputStreamReader, which is chained to the static
use the command line. standard console input System.in.
Note: This example is just to illustrate the methods of the
If the string read is equal to xyz, then the program exits.
console class. You should ensure that the lifetime of the
The purpose of the trim() method on the String
fields userTyped and pwdTyped are as short as
returned by in.readLine is to remove any whitespace
possible and pass the received credentials to some type of
characters.
authentication service. See the Java Authentication and
Authorization Service (JAAS) API for more information: Note: A null string is returned if an end of stream is
http://download.oracle.com/javase/6/docs/technotes/ reached (the result of a user pressing Ctrl-C in Windows,
guides/security/jaas/JAASRefGuide.html for example) thus the test for null on line 13.

Writing to Standard Output Channel I/O


The println and print methods are part of Introduced in JDK 1.4, a channel reads bytes and
the java.io.PrintStream class. characters in blocks, rather than one byte or character at a
time.
The println methods print the argument and a
newline character (\n).
The print methods print the argument without a
newline character.
The print and println methods are
overloaded for most primitive types (boolean,
char, int, long, float, and double)
and for char [], Object, and String.
The print(Object) and println
(Object) methods call the toString method
on the argument.

Print Methods
In this example, a file can be read in its entirety into a
Note that there is also a formatted print method, printf. buffer, and then written out in a single operation.
You saw this method in the lesson titled String Channel I/O was introduced in the java.nio package in
Processing.
JDK 1.4.
Practice 10-1 Overview:Writing a
Simple Console I/O Application
This practice covers the following topics:
Writing a main class that accepts a file name as
an argument.
Using System console I/O to read a search
string.
Using stream chaining to use the appropriate
method to search for the string in the file and
report the number of occurrences.
Continuing to read from the console until an exit
sequence is entered.
In this practice, you will write the code necessary to read a
file name as an application argument, and use the System
console to read from standard input until a termination Object Graphs
character is typed in. Serialization traverses the object graph and writes that data
to the file (or other output stream) for each node of the
graph.
Persistence
Saving data to some type of permanent storage is called
persistence. An object that is persistent-capable, can be Transient Fields and Objects
stored on disk (or any other storage device), or sent to Some object classes are not serializable because
another machine to be stored there. they represent transient operating system-specific
A nonpersisted object exists only as long as the information.
Java Virtual Machine is running. If the object graph contains a nonserializable
Java serialization is the standard mechanism for reference, a NotSerializableException
saving an object as a sequence of bytes that can is thrown and the serialization operation fails.
later be rebuilt into a copy of the object. Fields that should not be serialized or that do not
To serialize an object of a specific class, the class need to be serialized can be marked with the
must implement the keyword transient.
java.io.Serializable interface.
The java.io.Serializable interface defines no
methods, and serves only as a marker to indicate that the
class should be considered for serialization.

Serialization and Object Graphs


When an object is serialized, only the fields of the
object are preserved.
When a field references an object, the fields of
the referenced object are also serialized, if that
objects class is also serializable.
The tree of an objects fields constitutes the
object graph.

Transient
If a field containing an object reference is encountered that
is not marked as serializable (implement
java.io.Serializable), a
NotSerializableException is thrown and the
entire serialization operation fails. To serialize a graph If a serializable class does not explicitly declare a
containing fields that reference objects that are not seriaiVersionUIO, then the serialization run time will
serializable, those fields must be marked using the calculate a default seriaiVersionUIO value for that class
keyword transient. based on various aspects of the class, as described in the
Java(TM) Object Serialization Specification. However, it
is strongly recommended that all serializable classes
Transient: Example explicitly declare seriaiVersionUIO values, since the
default seriaiVersionUIO computation is highly sensitive
to class details that may vary depending on compiler
implementations, and can thus result in unexpected
lnvalidCiassExceptions during deserialization. Therefore,
to guarantee a consistent seriaiVersionUIO value across
different java compiler implementations, a serializable
class must declare an explicit seriaiVersionUIO value. It is
also strongly advised that explicit seriaiVersionUIO
declarations use the private modifier where possible, since
The field access modifier has no effect on the such declarations apply only to the immediately declaring
data field being serialized. class--seriaiVersionUIO fields are not useful as inherited
The values stored in static fields are not members. Array classes cannot declare an explicit
serialized. seriaiVersionUIO, so they always have the default
When the object is deserialized, the values of computed value, but the requirement for matching
static fields are set to the values declared in the seriaiVersionUIO values is waived for array classes.
class. The value of non-static transient fields is
set to the default value for the type.
When an object is deserialized, the values of static Serialization Example
transient fields are set to the values defined in the class In this example, a Portfolio is made up of a set of Stocks.
declaration. The values of non-static fields are set to the During serialization, the current price is not
default value of their type. So in the example shown in the serialized, and is therefore marked transient.
slide, the value of BASE will be 100, per the class However, we do want the current value of the
declaration. The value of non-static transient fields, stock to be set to the current market price upon
inputFile and totalValue, are set to their default deserialization.
values, null and 0, respectively.

Serial Version UID


During serialization, a version number,
seriaiVersionUID, is used to associate the
serialized output with the class used in the
serialization process.
Upon deserialization, the seriaiVersionUID is
checked to verify that the classes loaded are Writing and Reading an Object Stream
compatible with the object being deserialized.
If the receiver of a serialized object has loaded
classes for that object with different
seriaiVersionUID, deserialization will result in an
InvalidClassException.
A serializable class can declare its own
seriaiVersionUID by explicitly declaring a field
named serialversionUID as a static final
and of type long:
private static long
serialVersionUID = 42Li
Note: The documentation for
java.io.Serializable states the following:
During deserialization, the readObject method is
invoked on the object being deserialized (if present in the
class file of the object). The signature of the method is
important.
private void readObject
(ObjectinputStream ois) throws
ClassNotFoundExceptionr IOException
{ois.defaultReadObject();
// Print the date this object was
serialized
System.out.println (Restored from
date: + (java.util.Date)
ois.readObject())); }

The SerializeStock class.


Line 6-8: A FileOutputStream is chained to readObject Example
an ObjectOutputStream. This allows the
raw bytes generated by the
ObjectOutputStream to be written to a file
through the writeObject method. This
method walks the objects graph and writes the
data contained in the non-transient and non-static
fields as raw bytes.
Line 12-14: To restore an object from a file, a
FileinputStream is chained to an
ObjectinputStream. The raw bytes read by
the readObject method restore an Object
containing the non-static and non-transient data
fields. This Object must be cast to expected
type.
In the Stock class, the readObject method is provided,
Serialization Methods to ensure that the stocks currPrice is set (by the
setStockPrice method) after deserialization of the
An object being serialized (and deserialized) can control Stock object.
the serialization of its own fields.
Note: The signature of the readObject method is
critical for this method to be called during deserialization.

Summary
In this lesson, you should have learned how to:
Describe the basics of input and output in Java
For example, in this class the current time is Read data from and write data to the console
written into the object graph. Use streams to read and write files
During deserialization a similar method is Write and read objects by using serialization
invoked:

The writeObject method is invoked on the object


Quiz
being serialized. If the object does not contain this 1. The purpose of chaining streams together is to:
method, the defaultWriteObject method is invoked a. Allow the streams to add functionality
instead. b. Change the direction of the stream
This method must also be called once and only c. Modify the access of the stream
once from the objects writeObject method. d. Meet the requirements of JDK 7
Answer: a private(line 3)
Chaining one stream to another allows you to add d. Use readString instead of
functionality to the stream (for example, readObject (line 6)
converting data from bytes to characters, from Answer: c
characters to a buffered character stream, and so The signature of the method must be:
on). private void readObject
2. To prevent the serialization of operating system- (ObjectinputStream ois) throws
specific fields, you should mark the field: IOException,
a. private ClassNotFoundException
b. static in order to be invoked during serialization.
c. transient
d. final
Answer: c Practice 10-2 Overview: Serializing
a. Access modifiers have no effect on and Deserializing a Shoppingcart
serialization of a field.
b. Although static fields are not serialized, This practice covers the following topics:
this is not recommended, because Creating an application that serializes a
marking a field static also changes Shoppingcart object that is composed of an
the fields access. ArrayList of Item objects.
c. final has no effect on the serialization Using the transient keyword to prevent the
of the field and also changes the serialization of the Shoppingcart total. This
meaning of the field, making it will allow items to vary their cost.
immutable. Use the writeobject method to store todays
3. Given the following fragments: date on the serialized stream.
Use the readobject method to recalculate the
total cost of the cart after deserialization and print
the date that the object was serialized.

Assuming no other changes to the data, what is


the value of name and keyword fields after
deserialization of the mc object instance?
a. Zim,
b. Zim, null
c. Zim, xyzzy
d. , null
Answer: b
The field keyword is marked transient, and thus
will not be serialized. Upon deserialization, the
value of the keyword is set to its default value
of a String: null.
4. Given the following fragment:

What is required to properly deserialize an


instance of MyClass from the stream containing
this object?
a. Make the field keyword static
b. Change the field access modifier to
public
c. Make the readObject method
Allows support for non-native file systems, to be
plugged in to the platform

Chapter 11
Limitations of java.io.File
Java File I/O (NIO.2)

Objectives
After completing this lesson, you should be able to:
Use the Path interface to operate on file and
directory paths
Use the Files class to check, delete, copy, or
move a file or directory
Use Files class methods to read and write files
using channel I/O and stream I/O
Read and change file and directory attributes
Recursively access a directory tree
Find a file by using the PathMatcher class The Java I/O File API (java. io. File) presented
challenges for developers.
Many methods did not throw exceptions when
New File I/O API (NI0.2) they failed, so it was impossible to obtain a useful
error message.
Several operations were missing (file copy, move,
and so on).
The rename method did not work consistently
across platforms.
There was no real support for symbolic links.
More support for metadata was desired, such as
file permissions, file owner, and other security
attributes.
Accessing file metadata was inefficient-every call
for metadata resulted in a system call, which
made the operations very inefficient.
Many of the File methods did not scale.
NIO API in JSR 51 established the basis for NIO in Java, Requesting a large directory listing on a server
focusing on buffers, channels, and charsets. JSR 51 could result in a hang.
delivered the first piece of the scalable socket I/Os into the It was not possible to write reliable code that
platform, providing a non-blocking, multiplexed I/O API, could recursively walk a file tree and respond
thus allowing the development of highly scalable servers appropriately if there were circular symbolic
vvithout having to resort to native code. links.
For many developers, the most significant goal of JSR 203 Further, the overall I/O was not written to be extended.
is to address issues with java.io.File by developing Developers had requested the ability to develop their own
a new file system interface. file system implementations. For example, by keeping a
The new API: pseudofile system in memory, or by formatting files as zip
Works more consistently across platforms files.
Makes it easier to write programs that gracefully
handle the failure of file system operations
Provides more efficient access to a larger set of File Systems, Paths, Files
file attributes In NI0.2, both files and directories are represented by a
Allows developers of sophisticated applications path, which is the relative or absolute location of the file
to take advantage of platform-specific features or directory.
when absolutely necessary
system.

Symbolic Links

File Systems
Prior to the NI0.2 implementation in JDK 7, files were
represented by the java.io.File class.
File system objects are most typically directories or files.
In NI0.2, instances of java.nio.file.Path objects are
Everyone is familiar with these objects. But some file
used to represent the relative or absolute location of a file
systems also support the notion of symbolic links. A
or directory.
symbolic link is also referred to as a symlink or a soft
File systems are hierarchical (tree) structures. File systems link.
can have one or more root directories. For example,
A symbolic link is a special file that serves as a reference
typical Windows machines have at least two disk root
to another file. A symbolic link is usually transparent to
nodes: C:\ and D:\.
the user. Reading or writing to a symbolic link is the same
Note that file systems may also have different as reading or writing to any other file or directory.
characteristics for path separators, as shown in the slide.
In the slides diagram, logFile appears to the user to be
a regular file, but it is actually a symbolic link to dir/
Relative Path Versus Absolute Path logs/homeLogFile. homeLogFile is the target of
the link.
A path is either relative or absolute.
An absolute path always contains the root
element and the complete directory list required Java NI0.2 Concepts
to locate the file.
Example: Prior to JDK 7, the java.io.File class was the
entry point for all file and directory operations. With
NI0.2, there is a new package and classes:
java.nio.file.Path: Locates a file or a
A relative path must be combined with another directory by using a system-dependent path
path in order to access a file. java.nio.file.Files: Using a Path,
Example: performs operations on files and directories
java.nio.file.FileSystem: Provides an
interface to a file system and a factory for
creating a Path and other objects that access a
file system
A path can either be relative or absolute. An absolute path
All the methods that access the file system throw
always contains the root element and the complete
IOException or a subclass.
directory list required to locate the file. For example, /
home/peter/statusReport is an absolute path. All Java NI0.2
the information needed to locate the file is contained in the
path string. A significant difference between NI0.2 and
A relative path must be combined with another path in java.io.File is the architecture of access to the file
order to access a file. For example, clarence/foo is a system. With the java.io.File class, the methods
relative path. Without more information, a program cannot used to manipulate path information are in the same class
reliably locate the clarence/foo directory in the file with methods used to read and write files and directories.
In NI0.2, the two concerns are separated. Paths are created To access the components of a path:
and manipulated using the Path interface, while operations - getFileName,
on files and directories is the responsibility of the Files getParent,getRoot,
class, which operates only on Path objects. getNameCount
Finally, unlike java.io.File, Files class methods that To operate on a path:
operate directly on the file system, throw an - normalize, toUri,
IOException (or a subclass). Subclasses provide toAbsolutePath, subpath,
details on what the cause of the exception was. resolve, relativize
To compare paths:
- startsWith, endsWith, equals
Path Interface
Path Objects Are Like string
The java.nio.file.Path interface provides the
entry point for the NI0.2 file and directory manipulation. Objects
To obtain a Path object, obtain an instance of It is best to think of Path objects in the same way you
the default file system, and then invoke the think of String objects. Path objects can be created
getPath method: from a single text string, or a set of components:
A root component, that identifies the file system
hierarchy
The java.nio.file package also provides a
A name element, farthest from the root element,
static final helper class called Paths to perform
that defines the file or directory the path points to
getDefault:
Additional elements may be present as well,
separated by a special character or delimiter that
identify directory names that are part of the
hierarchy
The entry point for the NI0.2 file and directory Path objects are immutable. Once created, operations on
manipulation is an instance of the Path interface. The Path objects return new Path objects.
provider (in this case, the default provider) creates an
object that implements this class and handles all the
operations to be performed on a file or a directory in a file Path: Example
system.
Path objects are immutable-once they are created, they
cannot be changed.
Note that if you plan to use the default file system-that is,
the file system that the JVM is running on for the Path
operations-the Paths utility is the shorter method.
However, if you wanted to perform Path operations on a
file system other than the default, you would get an
instance of the file system that you wanted and use the
first approach to build Path objects.
Note: The windows file system uses a backward slash by
default. However, Windows can accept both backward and
forward slashes in applications (except the command
shell). Further, backward slashes in Java must be escaped.
In order to represent a backward slash in a string, you
must type the backward slash twice. Because this looks Unlike the java.io.File class, files and directories
ugly, and Windows uses both forward and backward are represented by instances of Path objects in a system-
slashes, the examples shown in this course will use the dependentway.
forward slash in strings. The Path interface provides several methods for
reporting information about the path:
Path getFileName: The end point of this
Path Interface Features Path, returned as a Path object
The Path interface defines the methods used to locate a Path getParent: The parent path or null.
file or a directory in a file system. These methods include: Everything in Path up to the file name (file or
directory) subpath using the subpath method:
int getNameCount: The number of name
elements that make up this path The element returned by endindex is one less
Path getRoot: The root component of this that the endindex value.
Path Example:
boolean isAbsolute: true if this path
contains a system-dependent root element.
Note: Because this example is being run on a
Windows machine, the system-dependent root
element contains a drive letter and colon. On a
UNIX-based OS, isAbsolute returns true for
any path that begins with a slash. The element name closest to the root has index 0.
Path toAbsolutePath: Returns a path The element farthest from the root has index count-1.
representing the absolute path of this path Note: The returned Path object has the name elements
java.net.URI toUri: Returns an absolute that begin at beginindex and extend to the element at
URI. index endindex-1.
Note: A Path object can be created for any path. The
actual file or directory need not exist.
Joining Two Paths
The resolve method is used to combine two
Removing Redundancies from a Path paths.
Example:
Many file systems use . notation to denote the
current directory and .. to denote the parent
directory. Passing an absolute path to the resolve method
The following examples both include returns the passed-in path.
redundancies:
The resolve method is used to combine paths. It
The normalize method removes any redundant accepts a partial path, which is a path that does not include
elements, which includes any . or a root element, and that partial path is appended to the
directoryI .. occurrences. original path.
Example:
Creating a Path Between Two Paths
The relativize method enables you to
Many file systems use . notation to denote the current
construct a path from one location in the file
directory and ..to denote the parent directory. You might
system to another location.
have a situation where a Path contains redundant directory
The method constructs a path originating from the
information. Perhaps a server is configured to save its log
original path and ending at the location specified
files in the/ dir /logs/. directory, and you want
by the passed-in path.
to delete the trailing/. notation from the path.
The new path is relative to the original path.
The normalize method removes any redundant Example:
elements, which includes any. or directory/..
occurrences. The slide examples would be normalized to /
home/clarence/foo.
It is important to note that normalize does not check A common requirement when you are writing file I/O code
the file system when it cleans up a path. It is a purely is the capability to construct a path from one location in
syntactic operation. In the second example, if peter were the file system to another location. You can accomplish
a symbolic link, removing peter/.. might result in a this by using the relativize method. This method
path that no longer locates the intended file. constructs a path originating from the original path and
ending at the location specified by the passed-in path. The
new path is relative to the original path.
Creating a Subpath
A portion of a path can be obtained by creating a
coursefiles/JDK711);
Working with Links and the statement:
Path sub = p.subPath (X,y);
Path interface is link aware.
What values for x andy will produce a Path that
Every Path method either:
contains
- Detects what to do when a symbolic link documents/coursefiles?
is encountered, or a. X= 3, y = 4
- Provides an option enabling you to b. X= 3, y = 5
configure the behavior when a symbolic c. X= 4, y = 5
link is encountered d. X= 4, y = 6
Answer: b
3. Given this code fragment:
Path pl = Paths.get(D:/temp/
foo/);
Path p2 = Paths.get(../bar/
documents);
The java.nio.file package and the Path interface Path p3 = pl.resolve
in particular are link aware. Every Path method either (p2).normalize();
detects what to do when a symbolic link is encountered, or System.out.println(p3);
it provides an option enabling you to configure the What is the result?
behavior when a symbolic link is encountered. a. Compiler error
Some file systems also support hard links. Hard links are b. IOException
more restrictive than symbolic links, as follows: c. D:\temp\foo\documents
The target of the link must exist. d. D:\temp\bar\documents
Hard links are generally not allowed on e. D:\temp\foo\..\bar
directories. \documents
Hard links are not allowed to cross partitions or Answer: d
volumes. Therefore, they cannot exist across file
systems.
A hard link looks, and behaves, like a regular file, File Operations
so they can be hard to find.
A hard link is, for all intents and purposes, the
same entity as the original file. They have the
same file permissions, time stamps, and so on. All
attributes are identical.
Because of these restrictions, hard links are not used as
often as symbolic links, but the Path methods work
seamlessly with hard links.

Quiz
1. Given a Path object with the following path:
/export/home/heimer/../
williams/./documents
What Path method would remove the redundant The java.nio.file.Files class is the primary entry
elements? point for operations on Path objects.
a. normalize Static methods in this class read, write, and manipulate
b. relativize files and directories represented by Path objects.
c. resolve The Files class is also link awaremethods detect
d. toAbsolutePath symbolic links in Path objects and automatically manage
Answer: a links or provide options for dealing with links.
2. Given the following path:
Path p = Paths.get
(/home/export/tom/documents/ Checking a File or Directory
A Path object represents the concept of a file or a sensitive applications.
directory location. Before you can access a file or
directory, you should first access the file system to
determine whether it exists using the following Files Creating Files and Directories
methods: Files and directories can be created using one of the
exists(Path p, following methods:
LinkOption...option)
Tests to see whether a file exists. By default,
symbolic links are followed.
notExists(Path p, LinkOption...
option)
Tests to see whether a file does not exist. By The createDirectories method can be
default, symbolic links are followed. used to create directories that do not exist, from
Example: top to bottom:

Recall that Path objects may point to files or directories The Files class also has methods to create temporary
that do not exist. The exists() and notExists() files and directories, hard links, and symbolic links.
methods are used to determine whether the Path points to
a legitimate file or directory, and the particulars of that file
or directory. Deleting a File or Directory
When testing for the existence of a file, there are three
You can delete files, directories, or links. The Files class
outcomes possible:
The file is verified to exist. provides two methods:
The file is verified to not exist. delete(Path)
The files status is unknown. This result can occur deleteifExists(Path)
when the program does not have access to the
file.
Note: !Files.exists(path) is not equivalent to
Files.notExists(path). If both exists and
notExists return false, the existence of the file or
directory cannot be determined. For example, in Windows,
it is possible to achieve this by requesting the status of an
off-line drive, such as a CD-ROM drive. The delete(Path) method deletes the file or throws an
To verify that a file can be accessed, the Files class exception if the deletion fails. For example, if the file does
provides the following boolean methods. not exist, a NoSuchFileException is thrown.
isReadable(Path) The deleteifExists(Path) method also deletes the
isWritable(Path) file, but if the file does not exist, no exception is thrown.
isExecutable(Path) Failing silently is useful when you have multiple threads
Note that these tests are not atomic with respect to other deleting files and you do not want to throw an exception
file system operations. Therefore, the results of these tests just because one thread did so first.
may not be reliable once the methods complete.
The isSameFile(Path,Path) method tests
to see whether two paths point to the same file. Copying a File or Directory
This is particularly useful in file systems that
You can copy a file or directory by using the
support symbolic links.
copy (Path, Path, CopyOption...)
The result of any of these tests is immediately outdated
method.
once the operation completes. According to the
When directories are copied, the files inside the
documentation: Note that result of this method is
directory are not copied.
immediately outdated. There is no guarantee that a
subsequent attempt to open the file for writing will
succeed (or even that it will access the same file). Care
should be taken when using this method in security-
Example: a socket, or some other type of stream.

You can copy a file or directory by using the copy Moving a File or Directory
(Path, Path, CopyOption ... ) method. The You can move a file or directory by using the
copy fails if the target file exists, unless the move (Path, Path, CopyOption ... )
REPLACE_EXISTING option is specified. method.
Directories can be copied. However, files inside the Moving a directory will not move the contents of
directory are not copied, so the new directory is empty the directory.
even when the original directory contains files.
When copying a symbolic link, the target of the link is
copied. If you want to copy the link itself, and not the
contents of the link, specify either the
NOFOLLOW_LINKS or REPLACE_EXISTING option. Example:
The following StandardCopyOption and
LinkOption enums are supported:
REPLACE_EXISTING: Performs the copy Guidelines for moves:
even when the target file already exists. If the If the target path is a directory and that directory
target is a symbolic link, the link itself is copied is empty, the move succeeds if REPLACE
(and not the target of the link). If the target is a EXISTING is set.
non-empty directory, the copy fails with the If the target directory does not exist, the move
FileAlreadyExistsException exception. succeeds. Essentially, this is a rename of the
COPY_ATTRIBUTES: Copies the file attributes directory.
associated with the file to the target file. The If the target directory exists and is not empty, a
exact file attributes supported are file system- and DirectoryNotEmptyException is thrown.
platform-dependent, but last?modified-time is If the source is a file and the target is a directory
supported across platforms and is copied to the that exists, and REPLACE_EXISTING is set, the
target file. move will rename the file to the intended
NOFOLLOW_LINKS: Indicates that symbolic directory name.
links should not be followed. If the file to be To move a directory containing files to another directory,
copied is a symbolic link, the link is copied (and essentially you need to recursively copy the contents of
not the target of the link). the directory, and then delete the old directory.
You can also perform the move as an atomic file operation
using ATOMIC_MOVE.
Copying Between a Stream and Path If the file system does not support an atomic
You may also want to be able to copy (or write) from a move, an exception is thrown. With an
Stream to file or from a file to a Stream. The Files ATOMIC_MOVE you can move a file into a
class provides two methods to make this easy: directory and be guaranteed that any process
watching the directory accesses a complete file.

Listing a Directorys Contents


An interesting use of the first method is copying The DirectoryStream class provides a mechanism to
from a web page and saving to a file: iterate over all the entries in a directory.

The alternative to the stream to path copy is a path to


stream method. This method may be used to write a file to
Channels and ByteBuffers
Stream I/O reads a character at a time, while
channel I/O reads a buffer at a time.
The ByteChannel interface provides basic
read and write functionality.
A SeekableByteChannel is a
ByteChannel that has the capability to
maintain a position in the channel and to change
that position.
DirectoryStream scales to support very The two methods for reading and writing channel
large directories. I/O are:
The Files class provides a method to return a
DirectoryStream, which can be used to iterate over
The capability to move to different points in the
all the files and directories from any Path(root) directory.
file and then read from or write to that location
DirectoryiteratorException is thrown ifthere is makes random access of a file possible.
an I/O errorwhile iterating over the entries in the specified NI0.2 supports channel and buffered stream I/O.
directory. While stream I/O reads a character at a time, channel I/O
PatternSyntaxException is thrown when the reads a buffer at a time. The ByteChannel interface
pattern provided (second argument of the method) is provides basic read and write functionality. A
invalid. SeekableByteChannel is a ByteChannel that has
the capability to maintain a position in the channel and
query the file for its size.
Reading/Writing All Bytes or Lines The capability to move to different points in the file and
from a File then read from or write to that location makes random
access of a file possible.
The readAllBytes or readAllLines
There are two methods for reading and writing channel I/
method reads entire contents of the file in one
O:
pass.
newByteChannel(Path,
Example:
OpenOption... )
newByteChannel(Path, Set<?
extends OpenOption>,
Use write method(s) to write bytes, or lines, to FileAttribute<?> ... )
a file. Note: The newByteChannel methods return an
instance of a SeekableByteChannel. With a default
file system, you can cast this seekable byte channel to a
FileChannel providing access to more advanced
If you have a small file and you would like to read its features such as mapping a region of the file directly into
entire contents in one pass, you can use the memory for faster access, locking a region of the file so
readAllBytes(Path) or read.AllLines other processes cannot access it, or reading and writing
(Path,Charset) method. These methods take care of bytes from an absolute position without affecting the
most of the work, such as opening and closing the stream, channels current position. Refer to the I/O
but because they bring the entire file into memory at once, Fundamentals lesson for an example of using
they are not intended for handling large files. FileChannel.
You can use one of the write methods to write bytes, or
lines, to a file.
write(Path, byte[], Random Access Files
OpenOption...)
Random access files permit non-sequential, or
write(Path, Iterable<? extends
random, access to a files contents.
CharSequence>, Charset,
To access a file randomly, open the file, seek a
OpenOption...)
particular location, and read from or write to that
file.
Random access functionality is enabled by the
SeekableByteChannel interface.

To create a file, append to a file, or write to a file,


use the newOutputStream method.

Random access files permit non-sequential, or random,


access to a files contents. To access a file randomly, you Managing Metadata
open the file, seek a particular location, and read from or
write to that file.
This functionality is possible with the
SeekableByteChannel interface. The
SeekableByteChannel interface extends channel I/O
with the notion of a current position. Methods enable you
to set or query the position, and you can then read the data
from, or write the data to, that location. The API consists
of a few, easy to use, methods:
position(): Returns the channels current position
position(long): Sets the channels position
read(ByteBuffer): Reads bytes into the buffer
from the channel
write(ByteBuffer): Writes bytes from the buffer
to the channel
truncate(long): Truncates the file (or other If a program needs multiple file attributes around the same
entity) connected to the channel time, it can be inefficient to use methods that retrieve a
single attribute. Repeatedly accessing the file system to
retrieve a single attribute can adversely affect
Buffered I/O Methods for Text Files performance. For this reason, the Files class provides
two read.Attributes methods to fetch a files
The newBufferedReader method opens a attributes in one bulk operation.
file for reading. read.Attributes(Path, String,
LinkOption...)
read.Attributes(Path, Class<A>,
The newBufferedWriter method writes to a LinkOption...)
file using a BufferedWriter.

File Attributes (DOS)


File attributes can be read from a file or directory
Reading a File by Using Buffered in a single call:
Stream I/O
The newBufferedReader(Path/Charset) DOS file systems can modify attributes after file
method opens a file for reading, returning a creation:
BufferedReader that can be used to read text from a
file in an efficient manner.
The setAttribute types (for DOS) extend the
BasicFileAttributeView and view the standard
Byte Streams four bits on file systems that support DOS attributes:
NI0.2 also supports methods to open byte dos:hidden
dos:readonly
streams.
dos:system
dos:archive
Other supported attribute views include:
BasicFileAttributeView: Provides a set
of basic attributes supported by all file system
implementations.
PosixFileAttributeView: Extends the
BasicFileAttributeView with attributes
that support the POSIX family of standards, such
as UNIX.
FileOwnerAttributeView: Is supported by File systems that implement the Portable Operating
any file system implementation that supports the System Interface (POSIX) standard can create files and
concept of a file owner. directories with their initial permissions set. This solves a
AclFileAttributeView: Supports reading common problem in I/O programming where a file is
or updating a files Access Control List (ACL). created. Permissions on that file may be changed before
The NFSv4 ACL model is supported. the next execution to set permissions.
UserDefinedFileAttributeView: Permissions can be set only for POSIX-compliant file
Enables support of user-defined metadata. systems, such as MacOS, Linux, and Solaris. Windows
(DOS-based) is not POSIX compliant. DOS-based files
and directories do not have permissions, but rather file
DOS File Attributes: Example attributes.
Note: You can determine whether or not a file system
supports POSIX programmatically by looking for what
file attribute views are supported. For example:
boolean unixFS = false;
Set<String> views =
FileSystems.getDefault
().supportedFileAttributeViews();
for (String s : views) {
if (s.equals(posix)) unixFS = true;
}

Quiz
1. Given the following fragment:
The code fragment in the slide illustrates the use of the
DosFileAttributes class. In the one call to the
read.Attributes method, the attributes of the file (or If the peter2 directory does not exist, and the
directory) are returned. peter directory is populated with subfolders
and files, what is the result?
a. DirectoryNotEmptyException
POSIX Permissions b. NotDirectoryException
c. Directory peter2 is created.
With NI0.2, you can create files and directories on POSIX d. Directory peter is copied to peter2.
file systems with their initial permissions set. e. Directory peter2 is created and
populated with files and directories from
peter.
Answer: e
2. Given the fragment:

Assuming source and target are not


directories, how can you prevent this copy
operation from generating The FileVisitor interface includes methods that are
FileAlreadyExistsException? invoked as each node in a file tree is visited:
a. Delete the target file before the copy. preVisitDirectory: Invoked on a directory
b. Use the move method instead. before the entries in the directory are visited
c. Use the copyExisting method visitFile: Invoked for a file in a directory
instead. postVisitDirectory: Invoked after all the
d. Add the REPLACE_EXISTING option entries in a directory and their descendants have
to the method. been visited
Answer: a, d visitFileFailed: Invoked for a file that
3. Given this fragment: could not be visited
The return result from each of the called methods
determines actions taken after a node is reached (pre or
Assuming there are no exceptions, what is the post). These are enumerated in the FileVisitResult
result? class:
a. The contents of mcginn are copied to CONTINUE: Continue to the next node
heimer. SKIP_SIBLINGS: Continue without visiting the
b. HelloWorld.java is copied to / siblings of this file or directory
export/home. SKIP_SUBTREE: Continue without visiting the
c. HelloWorld. java is coped to / entries in this directory
export/home/heimer. TERIVliNATE
d. The contents of heimer are copied to Note: There is also a class, SimpleFileVisitor, that
mcginn. implements each method in FileVisitor with a return
Answer: c type of FileVisitResult.CONTINUE or rethrows
any IOException. If you plan on using only some of
the methods in the FileVisitor interface, this class is
Practice 11-1 Overview: Writing a File easier to extend and override just the methods that you
need.
Merge Application
In this practice, use the Path interface and Files class
to open a letter template form, and substitute the name in FileVisitor Method Order
the template with a name from a file containing a list of
names.
Use the Path interface to create a new file name
for the custom letter.
Use the Files class to read all of the strings
from both files into List objects.
Use the Matcher and Pattern classes to
search for the token to replace in the template.

Recursive Operations
The Files class provides a method to walk the file tree
for recursive operations, such as copies and deletes.
walkFileTree(Path start,
FileVisitor<T>)
Example:

FileVisitor
Starting at the first directory node, and at every
subdirectory encountered, the preVisitDirectory
(Path/BasicFileAttributes) method is invoked
on the class passed to the walkFileTree method.
Assuming that the return type from the invocation of
preVisitDirectory() returns Example: WalkFileTreeExample
FileVisitResult.CONTINUE, the next node is
explored.
Note: The file tree traversal is depth-first with the given
FileVisitor invoked for each file encountered. File
tree traversal completes when all accessible files in the
tree have been visited, or a visit method returns a result of
TERMINATE. Where a visit method terminates due an
IOException, an uncaught error, or a runtime
exception, the traversal is terminated and the error or
exception is propagated to the caller of this method.

In this example, the PrintTree class implements each


of the methods in FileVisitor and prints out the type,
name, and size of the directory and file at each node.
Using the diagram shown in the slide, the resulting output
(on Windows) is shown below:
When a file is encountered in the tree the
preVisitDirectory: Directory: D:\Test
walkFileTree method attempts to read its
(0 bytes)
BasicFileAttributes. If the file is not a directory,
preVisitDirectory: Directory: D:\Test
the visitFile method is invoked with the file \bar (0 bytes)
attributes. If the file attributes cannot be read, due to an I/ postVisitDirectory: Directory: D:\Test
O exception,the visitFileFailed method is invoked \bar
with the I/O exception. visitFile: Regular file: D:\Test\filel
(328 bytes)
preVisitDirectory: Directory: D:\Test
\foo (0 bytes)
preVisitDirectory: Directory: D:\Test
\foo\a (0 bytes)
visitFile: Regular file: D:\Test\foo\a
\file2 (22 bytes)
postVisitDirectory: Directory: D:\Test
\foo\a
visitFile: Regular file: D:\Test\foo
\file3 (12 bytes)
postVisitDirectory: Directory: D:\Test
\foo
After reaching all the children in a node, the postVisitDirectory: Directory: D:\Test
postVisitDirectory method is invoked on each of The complete code for this example is in the examples/
the directories. WalkFileTreeExample project.
Note: The progression illustrated here assumes that
FileVisitResult return type is CONTINUE for each
of the FileVisitor methods. Finding Files
To find a file, typically, you would search a directory. You
could use a search tool, or a command, such as:
The backslash character(\) is used to escape
characters that would otherwise be interpreted as
This command will recursively search the special characters. The expression \\ matches a
directory tree, starting from where you are for all single backslash and \ { matches a left brace for
files that contain the .java extension. example.
The java.nio.file.PathMatcher The [] characters are a bracket expression that
interface includes a match method to determine matches a single character of a name component
whether a Path object matches a specified out of a set of characters. For example, [abc]
search string. matches a, b, or c. The hyphen (-) may be used
Each file system implementation provides a to specify a range, so [a-z] specifies a range
PathMatcher that can be retrieved by using that matches from a through z (inclusive). These
the FileSystems factory: forms can be mixed so [abce-g] matches a, b,
c, e, f, or g. If the character after the [ is a !, then
it is used for negation, so [!a- c] matches any
character except a, b, or c.
PathMatcher Syntax and Pattern Within a bracket expression, the*,? and\
characters match themselves. The(-) character
The syntaxAndPattern string is of the form: matches itself if it is the first character within the
syntax:pattern brackets, or the first character after the ! if
Where syntax can be glob and regex. negating.
The glob syntax is similar to regular expressions, The {}characters are a group of subpatterns,
but simpler: where the group matches if any subpattern in the
group matches. The, character is used to
Pattern Example Matches separate the subpatterns. Groups cannot be
*.java A path that represents a nested.
file name ending Leading period/dot characters in a file name are
in .java treated as regular characters in match operations.
For example, the* glob pattern matches file
*.* Matches file names
name .login. The Files. isHidden
containing a dot
(java. nio. file. Path) method may
*.{java,class} Matches file names
be used to test whether a file is considered
ending with .java
hidden.
or .class All other characters match themselves in an
foo.? Matches file names implementation-dependent manner. This includes
starting with foo. and characters representing any name separators.
a single character The matching of root components is highly
extension implementation-dependent and is not specified.
C:\\* Matches C:\foo and When the syntax is regex, the pattern component is a
C:\bar on the regular expression as defined by the Pattern class.
Windows platform (Note For both the glob and regex syntaxes, the matching details,
that the backslash is such as whether the matching is case-sensitive, are
escaped. As a string implementation-dependent and, therefore, not specified.
literal in the Java
Language, the pattern
would be C:\\\\*.) PathMatcher: Example
The following rules are used to interpret glob patterns:
The * character matches zero or more characters
of a name component without crossing directory
boundaries.
The * * characters matches zero or more
characters crossing directory boundaries.
The ? character matches exactly one character of
a name component.
can be used to report changes to registered Path
objects. WatchService can be used to identify
when files are added, deleted, or modified in a
directory.

The slide shows examples output from the


DiskUsageExample project and WatchDirExample
project.

In this code fragment in the slide (the complete example is


in the examples directory), two arguments are passed to Moving to NI0.2
the main.
The first argument is tested to see whether it is a directory. A method was added to the java.io.File class for
The second argument is used to create a PathMatcher JDK 7 to provide forward compatibility with NI0.2.
instance with a regular expression using the
FileSystems factory.
Finder is a class that implements the FileVisitor
interface, so that it can be passed to a walkFileTree This enables you to take advantage of NI0.2
without having to rewrite a lot of code.
method. This class is used to call the match method on
Further, you could replace your existing code to
each of the files visited in the tree.
improve future maintenance-for example, replace
file.delete(); with:
Finder Class
Conversely, the Path interface provides a method
to construct a java.io.File object:

Legacy java.io.File code


One of the benefits of the NI0.2 package is that you can
enable legacy code to take advantage of the new API.

Summary
In this lesson, you should have learned how to:
Use the Path interface to operate on file and
directory paths
Use the Files class to check, delete, copy, or
move a file or directory
The slide shows a portion of the Finder class. This class Use Files class methods to read and write files
is used to walk the tree and look for matches between file using channel I/O and stream I/O
and the file reached by the visitFile method. Read and change file and directory attributes
Recursively access a directory tree
Find a file by using the PathMatcher class
Other Useful NIO.2 Classes
The FileStore class is useful for providing
usage information about a file system, such as the Quiz
total, usable, and allocated disk space. 1. To copy, move, or open a file or directory using
NI0.2, you must first create an instance of:
a. Path
An instance of the watchService interface b. Files
c. FileSystem
d. Channel
Answer: a
2. Given any starting directory path, which
FileVisitor method(s) would you use to
delete a file tree?
a. preVisitDirectory()
b. postVisitDirectory()
c. visitFile()
d. visitDirectory()
Answer: b, c
You should use visitFile to delete a file
discovered in the directory.
postVisitDirectory can then delete the
empty directory.
3. Given an application where you want to count the
depth of a file tree (how many levels of
directories), which FileVisitor method should you
use?
a. preVisitDirectory()
b. postVisitDirectory()
c. visitFile()
d. visitDirectory()
Answer: a
preVisitDirectory is called only once per
directory, prior to visiting that node.

Practice 11-2 Overview: Recursive


Copy
This practice covers creating a class by implementing
FileVisitor to recursively copy one directory tree to
another location.
Allow the user of your application to decide to
overwrite an existing directory or not.

(Optional) Practice 11-3 Overview:


Using PathMatcher to Recursively
Delete
This practice covers the following topics:
Creating a class by implementing
FileVisitor to delete a file by using a
wildcard (That is, delete all the text files by using
*.txt.)
(Optional) Running the WatchDirExample in
the examples directory while deleting files from a
directory (or using the recursive copy application)
to watch for changes.
Multithreaded Servers
Even if you do not write code to create new threads of
Chapter 12 execution, your code might be run in a multithreaded
environment. You must be aware of how threads work and
Threading how to write thread-safe code. When creating code to run
inside of another piece of software (such as a middleware
or application server), you must read the products
Objectives documentation to discover whether threads will be created
automatically. For instance, in a Java EE application
After completing this lesson, you should be able to: server, there is a component called a Servlet that is used to
Describe operating system task scheduling handle HTTP requests. Servlets must always be thread-
Define a thread safe because the server starts a new thread for each HTTP
Create threads request.
Manage threads
Synchronize threads accessing shared data
Identify potential threading problems The Thread Class
The Thread class is used to create and start threads.
Task Scheduling Code to be executed by a thread must be placed in a class,
which does either of the following:
Modern operating systems use preemptive multitasking to Extends the Thread class
allocate CPU time to applications. There are two types of - Simpler code
tasks that can be scheduled for execution: Implements the Runnable interface
Processes: A process is an area of memory that - More flexible
contains both code and data. A process has a - extends is still free
thread of execution that is scheduled to receive
CPU time slices.
Thread: A thread is a scheduled execution of a Extending Thread
process. Concurrent threads are possible. All
threads for a process share the same data memory Extend java.lang.Thread and override the run
but may be following different paths through a method:
code section.

Preemptive Multitasking
Modern computers often have more tasks to execute than
CPUs. Each task is given an amount of time (called a time
slice) during which it can execute on a CPU. A time slice
is usually measured in milliseconds. When the time slice
has elapsed, the task is forcefully removed from the CPU
and another task is given a chance to execute.
The run Method
Why Threading Matters The code to be executed in a new thread of execution
should be placed in a run method. You should avoid
To execute a program as quickly as possible, you must
avoid performance bottlenecks. Some of these bottlenecks calling the run method directly. Calling the run method
are: does not start a new thread and the effect would be no
Resource Contention: Two or more tasks waiting different than calling any other method.
for exclusive use of a resource
Blocking I/O operations: Doing nothing while
waiting for disk or network data transfers
Starting a Thread
Underutilization of CPUs: A single-threaded After creating a new Thread, it must be started by
application uses only a single CPU calling the Threads start method:
Machine will invoke the run method in the Threads
associated Runnable.

A Runnable with Shared Data


Static and instance fields are potentially shared by threads.

The start Method


The start method is used to begin executing a thread.
The Java Virtual Machine will call the Threads run
method. Exactly when the run method begins executing
is beyond your control. A Thread can be started only
once.

Implementing Runnable
Implement java.lang.Runnable and implement the
run method: One Runnable: Multiple Threads
An object that is referenced by multiple threads can lead to
instance fields being concurrently accessed.

The run Method


Just as when extending Thread, calling the run method Multiple Threads with One
does not start a new thread. The benefit of implementing Runnable
Runnable is that you may still extend a class of your
choosing. It is possible to pass a single Runnable instance to
multiple Thread instances. There are only as many
Runnable instances as you create. Multiple Thread
Executing Runnable Instances instances share the Runnable instances fields.
Static fields can also be concurrently accessed by multiple
After creating a new Runnable, it must be passed to a
threads.
Thread constructor. The Threads start method
begins execution:
Quiz
Creating a new thread requires the use of:
a. java.lang.Runnable
b. java.lang.Thread
c. java.util.concurrent.Callable
Answer: b
The start Method
The Threads start method is used to begin executing
Problems with Shared Data
a thread. After the thread is started, the Java Virtual Shared data must be accessed cautiously. Instance and
static fields: Answer: a, c
Are created in an area of memory known as heap
space
Can potentially be shared by any thread Atomic Operations
Might be changed concurrently by multiple
Atomic operations function as a single operation. A single
threads
statement in the Java language is not always atomic.
- There are no compiler or IDE warnings.
i++;
- Safely accessing shared fields is your
- Creates a temporary copy of the value in
responsibility.
i
The preceding slides might produce the following:
- Increments the temporary copy
- Writes the new value back to i
l = 0xffff_ffff_ffff_ffff;
- 64-bit variables might be accessed using
two separate 32-bit operations.
What inconsistencies might two threads incrementing the
Debugging Threads same field encounter?
What if that field is long?
Debugging threads can be difficult because the frequency
and duration of time each thread is allocated can vary for Inconsistent Behavior
many reasons including:
Thread scheduling is handled by an operating One possible problem with two threads incrementing the
system and operating systems may use different same field is that a lost update might occur. Imagine if
scheduling algorithms both threads read a value of 41 from a field, increment the
Machines have different counts and speeds of value by one, and then write their results back to the field.
CPUs Both threads will have done an increment but the resulting
Other applications may be placing load on the value is only 42. Depending on how the Java Virtual
system Machine is implemented and the type of physical CPU
This is one of those cases where an application may seem being used, you may never or rarely see this behavior.
to function perfectly while in development, but strange However, you must always assume that it could happen.
problems might manifest after it is in production because If you have a long value of
of scheduling variations. It is your responsibility to 0x0000_0000_ffff_ffff and increment it by 1, the
safeguard access to shared variables. result should be 0x0000_0001_0000_0000. However,
because it is legal for a 64-bit field to be accessed using
two separate 32-bit writes, there could temporarily be a
Nonshared Data value of 0x0000_0001_ffff_ffff or even
0x0000_0000_0000_0000 depending on which bits
Some variable types are never shared. The following types are modified first. If a second thread was allowed to read a
are always thread-safe: 64-bit field while it was being modified by another thread,
Local variables an incorrect value could be retrieved.
Method parameters
Exception handler parameters

Shared Thread-Safe Data Out-of-Order Execution


Operations performed in one thread may not
Any shared data that is immutable, such as String appear to execute in order if you observe the
objects or final fields, are thread-safe because they can results from another thread.
only be read and not written. - Code optimization may result in out-of-
order operation.
- Threads operate on cached copies of
Quiz shared variables.
Variables are thread-safe if they are: To ensure consistent behavior in your threads,
a. local you must synchronize their actions.
b. static - You need a way to state that an action
c. final happens before another.
d. private - You need a way to flush changes to shared
variables back to main memory.

Synchronizing Actions
Every thread has a working memory in which it keeps its
own working copy of variables that it must use or assign.
As the thread executes a program, it operates on these
working copies. There are several actions that will
synchronize a threads working memory with main
memory:
A volatile read or write of a variable (the
volatile keyword)
Locking or unlocking a monitor (the
synchronized keyword)
The first and last action of a thread
Actions that start a thread or detect that a thread
has terminated

Quiz
Which of the following cause a thread to synchronize
variables?
a. Reading a volatile field
The Main Thread
b. Calling isAlive() on a thread The main method in a Java SE application is executed in
c. Starting a new thread a thread, sometimes called the main thread, which is
d. Completing a synchronized code block automatically created by the JVM. Just with any thread,
Answer: a, b, c, d when the main thread writes to the timeToQuit field, it
is important that the write will be seen by the t1 thread. If
the timeToQuit field was not volatile, there is no
The volatile Keyword guarantee that the write would be seen immediately. Note
that if you forget to declare a similar field as volatile,
A field may have the volatile modifier applied to it:
an application might function perfectly for you but
occasionally fail to quit for someone else.

Reading or writing a volatile field will cause


The synchronized Keyword
a thread to synchronize its working memory with The synchronized keyword is used to create thread-
main memory. safe code blocks. A synchronized code block:
volatile does not mean atomic. Causes a thread to write all of its changes to main
- If i is volatile, i++ is still not a memory when the end of the block is reached
thread-safe operation. - Similar to volatile
Because the manipulation of volatile fields may not Is used to group blocks of code for exclusive
be atomic, it is not sufficient to make anything other than execution
reads and writes of single variables thread-safe. A good - Threads block until they can get exclusive
example of using volatile is shown in the examples in access
the following slides about how to stop a thread. - Solves the atomic problem

Stopping a Thread synchronized Methods


A thread stops by completing its run method.
of synchronized methods to reduce the number of
lines that are exclusive to a single thread.
Use synchronization as little as possible for performance,
but as much as needed to guarantee reliability.

Object Monitor Locking


Each object in Java is associated with a monitor, which a
thread can lock or unlock.
synchronized methods use the monitor for
the this object.
static synchronized methods use the
classes monitor.
synchronized blocks must specify which
Synchronized Method Behavior objects monitor to lock or unlock.
In the example in the slide, you can call only one method
at a time in a ShoppingCart object because all its synchronized blocks can be nested.
methods are synchronized. In this example, the
synchronization is per ShoppingCart. Two Nested synchronized Blocks
ShoppingCart instances could be used concurrently.
A thread can lock multiple monitors simultaneously by
If the methods were not synchronized, calling using nested synchronized blocks.
removeItem while printCart is iterating through the
Item collection might result in unpredictable behavior.
An iterator may support fail-fast behavior. A fail-fast Detecting Interruption
iterator will throw a
java.util.ConcurrentModificationExcepti Interrupting a thread is another possible way to request
on, a subclass of RuntimeException,if the iterators that a thread stop executing.
collection is modified while being used.

synchronized Blocks

Interruption Does Not Mean Stop


When a thread is interrupted, it is up to you to decide what
action to take. That action could be to return from the run
method or to continue executing code.

Interrupting a Thread
Synchronization Bottlenecks
Every thread has an interrupt() and
Synchronization in multithreaded applications ensures isInterrupted() method.
reliable behavior. Because synchronized blocks and
methods are used to restrict a section of code to a single
thread, you are potentially creating performance
bottlenecks. synchronized blocks can be used in place
Quiz
A call to Thread.sleep(4000) will cause the
executing thread to always sleep for exactly 4 seconds:
a. True
b. False
Answer: b

Benefits of Interruption
Using the interruption features of Thread is a convenient
Additional Thread Methods
way to stop a thread. In addition to eliminating the need There are many more Thread and threading-
for you to write your own thread-stopping logic, it also related methods:
can interrupt a thread that is blocked. For more - setName(String), getName(), and
information, see getId()
http://download.java.net/jdk7/docs/api/java/lang/ - isAlive(): Has a thread finished?
Thread.html#interrupt(). - isDaemon() and setDaemon
(boolean): The JVM can quit while
daemon threads are running.
Thread.sleep() - join(): A current thread waits for
A Thread may pause execution for a duration of time. another thread to finish.
- Thread.currentThread():
Runnable instances can retrieve the
Thread instance currently executing.
The Object class also has methods related to
threading:
- wait(), notify(), and notifyAll
(): Threads may go to sleep for an
undetermined amount of time, waking only
when the Object they waited on receives
a wakeup notification.
How Long Will a Thread Sleep? Learning More
A request of Thread.sleep(4000) means that a Daemon threads are background threads that are less
thread wants to stop executing for 4 seconds. After that 4 important than normal threads. Because the main thread is
seconds elapse, the thread is scheduled for execution not a daemon thread, all threads that you create will also
again. This does not mean that the thread start up exactly 4 be nondaemon threads. Any nondaemon thread that is still
seconds after the call to sleep(), instead it means the running (alive) will keep the JVM from quitting even if
thread will begin executing 4 seconds or longer after it your main method has returned. If a thread should not
began to sleep. The exact sleep duration is affected by prevent the JVM from quitting, then it should be set as a
machine hardware, operating system, and system load. daemon thread. There are more multithreading concepts
and methods to learn about. For additional reading
Sleep Interrupted material, see http://download.oracle.com/javase/tutorial/
If you call interrupt() on a thread that is sleeping, essential/concurrency/further.html.
the call to sleep() will throw an
InterruptedException which must be handled.
How you should handle the exception depends on how
Methods to Avoid
your application is designed. If calling interrupt() is Some Thread methods should be avoided:
just meant to interrupt the sleep() call and not the setPriority(int) and getPriority()
execution of a thread, then you might swallow the - Might not have any impact or may cause
exception. Other cases might require you to rethrow the problems
exception or return from a run() method. The following methods are deprecated and should
never be used:
- destroy() A thread often acts in response to the action of another
- resume() thread. If the other threads action is also a response to the
- suspend() action of another thread, livelock may result. As with
- stop() deadlock, livelocked threads are unable to make further
progress. However, the threads are not blocked; they are
Deprecation simply too busy responding to each other to resume work.
Classes, interfaces, methods, variables, and other
components of any Java library may be marked as
deprecated. Deprecated components might cause
Summary
unpredictable behavior or simply might have not followed In this lesson, you should have learned how to:
proper naming conventions. You should avoid using any Describe operating system task scheduling
deprecated APIs in your applications. Deprecated APIs are Define a thread
still included in libraries to ensure backwards Create threads
compatibility, but could potentially be removed in future Manage threads
versions of Java. For more information about why the Synchronize threads accessing shared data
methods mentioned above are deprecated, refer to docs/ Identify potential threading problems
technotes/guides/concurrency/
threadPrimitiveDeprecation.html, which is available
online at Practice 12-1 Overview:
http://download.oracle.com/javase/7/ or as part of the
downloadable JDK documentation.
Synchronizing Access to Shared Data
This practice covers the following topics:
Printing thread IDs
Deadlock Using Thread.sleep()
Deadlock results when two or more threads are blocked Synchronizing a block of code
forever, waiting for each other. In this practice, you write a class that is added to an
existing multithreaded application. You must make your
class thread-safe.

Practice 12-2 Overview:


Implementing a Multithreaded
Program
This practice covers the following topics:
Implementing Runnable
Starvation and livelock are much less common a problem Starting a Thread
than deadlock, but are still problems that every designer of Checking the status of a Thread
concurrent software is likely to encounter. Interrupting a Thread
In this practice, you create, start, and interrupt basic
Starvation threads by using the Runnable interface.
Starvation describes a situation where a thread is unable to
gain regular access to shared resources and is unable to
make progress. This happens when shared resources are
made unavailable for long periods by greedy threads.
For example, suppose an object provides a synchronized
method that often takes a long time to return. If one thread
invokes this method frequently, other threads that also
need frequent synchronized access to the same object will
often be blocked.

Livelock
set operation there will be no need for locking when
executing the example shown. Other architectures may
require some form of internal locking.
Chapter 13
Concurrency The
java.util.concurrent.lock
s Package
Objectives
The java.util.concurrent.locks package is a
After completing this lesson, you should be able to: framework for locking and waiting for conditions that is
Use atomic variables distinct from built-in synchronization and monitors.
Use a ReentrantReadWriteLock
Use the java.util.concurrent collections
Describe the synchronizer classes
Use an ExecutorService to concurrently
execute tasks
Apply the Fork-Join framework

The java.util.concurrent
Package
Java 5 introduced the java.util.concurrent
package, which contains classes that are useful in Multi-Reader, Single Writer Lock
concurrent programming. Features include:
Concurrent collections One of the features of the
Synchronization and locking alternatives java.util.concurrent.locks package is an
Thread pools implementation of a multi-reader, single writer lock. A
- Fixed and dynamic thread count pools thread may not have or obtain a read lock while a write
available lock is in use. Multiple threads can concurrently acquire
- Parallel divide and conquer (Fork-Join) the read lock but only one thread may acquire the write
new in Java 7 lock. The lock is reentrant; a thread that has already
acquired the write lock may call additional methods that
also obtain the write lock without a fear of blocking.
The
java.util.concurrent.atom java.util.concurrent.lock
ic Package s
The java.util.concurrent.atomic package
contains classes that support lock-free thread-safe
programming on single variables.

Non-Blocking Operation
On CPU architectures that support a native compare and
b. False
Multiple Concurrent Reads Answer: b
In the example, all methods that are determined to be read-
only can add the necessary code to lock and unlock a read
lock. A ReentrantReadWriteLock allows
Synchronizers
concurrent execution of both a single read-only method The java.util.concurrent package provides five
and of multiple read-only methods. classes that aid common special-purpose synchronization
idioms.

Thread-Safe Collections Class Description


The java.util collections are not thread-safe. To use Semaphore Semaphore is a classic
collections in a thread-safe fashion: concurrency tool.
Use synchronized code blocks for all access to a CountDownLatch A very simple yet very
collection if writes are performed common utility for blocking
Create a synchronized wrapper using library until a given number of
methods, such as signals, events, or
java.util.Collections.synchronize conditions hold.
dList(List<T>) CyclicBarrier A resettable multiway
Use the java.util.concurrent collections synchronization point useful
Note: Just because a Collection is made thread-safe, in some styles of parallel
this does not make its elements thread-safe. programming.
Phaser Provides a more flexible
Concurrent Collections form of barrier that may be
used to control phased
The ConcurrentLinkedQueue class supplies an computation among
efficient scalable thread-safe nonblocking FIFO queue. multiple threads.
Five implementations in java.util.concurrent support the
Exchanger Allows two threads to
extended BlockingQueue interface, which defines
exchange objects at a
blocking versions of put and take: rendezvous point, and is
LinkedBlockingQueue, ArrayBlockingQueue, useful in several pipeline
SynchronousQueue, PriorityBlockingQueue, designs.
and DelayQueue.
Besides queues, this package supplies Collection The synchronizer classes allow threads to block until a
implementations designed for use in multithreaded certain state or action is reached.
contexts: ConcurrentHashMap, Semaphore: A Semaphore maintains a set of permits.
ConcurrentSkipListMap, Threads try to acquire permits and may block until other
ConcurrentSkipListSet, threads release permits.
CopyOnWriteArrayList, and CountDownLatch: A CountDownLatch allows one
CopyOnWriteArraySet. When many threads are or more threads to await (block) until completion of a
expected to access a given collection, a countdown. After the countdown is complete all awaiting
ConcurrentHashMap is normally preferable to a threads continue. A CountDownLatch cannot be reused.
synchronized HashMap, and a CyclicBarrier: Created with a party count. After the
ConcurrentSkipListMap is normally preferable to a number of parties (threads) have called await on the
synchronized TreeMap. A CopyOnWriteArrayList is CyclicBarrier they will be released (unblock). A
preferable to a synchronized ArrayList when the CyclicBarrier can be reused.
expected number of reads and traversals greatly Phaser: A more versatile version of a
outnumber the number of updates to a list. CyclicBarrier new to Java 7. Parties can register and
deregister over time causing the number of threads
required before advancement to change.
Quiz Exchanger: Allows two threads to swap a pair of
A CopyOnWriteArrayList ensures the thread-safety objects, blocking until an exchange takes place. It is a
of any object added to the List. bidirectional, memory efficient, alternative to a
a. True SynchronousQueue.
and synchronizers, there is another way to ensure that data
will not be incorrectly access by multiple threads: Simply
java.util.concurrent.Cycl do not allow multiple threads to process the same data. In
icBarrier some scenarios, it may be possible to create multiple
copies of your data in RAM and allow each thread to
The CyclicBarrier is an example of the synchronizer process a unique copy.
category of classes provided by
java.util.concurrent.
java.util.concurrent.Exec
utorService
An ExecutorService is used to execute tasks.
It eliminates the need to manually create and
manage threads.
Tasks might be executed in parallel depending on
the ExecutorService implementation.
Tasks can be:
- java.lang.Runnable
-
java.util.concurrent.Callable
Implementing instances can be obtained with
CyclicBarrier Behavior Executors.
In this example, if only one thread calls await() on the
barrier, that thread may block forever. After a second
thread calls await(), any additional call to await() The Behavior of an ExecutorService
will again block until the required number of threads is A cached thread pool ExecutorService:
reached. A CyclicBarrier contains a method, await Creates new threads as needed
(long timeout, TimeUnit unit), which will Reuses its threads (Its threads do not die after
block for a specified duration and throw a finishing their task.)
TimeoutException if that duration is reached. Terminates threads that have been idle for 60
seconds
Other types of ExecutorService implementations are
High-Level Threading Alternatives available:
Traditional Thread related APIs can be difficult to use int cpuCount = Runtime.getRuntime
properly. Alternatives include: ().availableProcessors();
java.util.concurrent.ExecutorServ ExecutorService es =
ice, a higher level mechanism used to execute Executors.newFixedThreadPool(cpuCount);
tasks A fixed thread pool ExecutorService:
- It may create and reuse Thread objects Contains a fixed number of threads
for you. Reuses its threads (Its threads do not die after
- It allows you to submit work and check on finishing their task.)
the results in the future. Queues up work until a thread is available
The Fork-Join framework, a specialized work- Could be used to avoid over working a system
stealing ExecutorService new in Java 7 with CPU-intensive tasks

Synchronization Alternatives
java.util.concurrent.Callable
Synchronized code blocks are used to ensure that data that
is not thread-safe will not be accessed concurrently by The Callable interface:
multiple threads. However the use of synchronized code Defines a task submitted to an
blocks can result in performance bottlenecks. Several ExecutorService
components of the java.util.concurrent package Is similar in nature to Runnable, but can:
provide alternatives to using synchronized code blocks. In - Return a result using generics
addition to leveraging the concurrent collections, queues, - Throw a checked exception
Quiz
An ExecutorService will always attempt to use all of
the available CPUs in a system.
a. True
java.util.concurrent.Futu b. False
re Answer: b

The Future interface is used to obtain the results from a


Callables V call() method. Concurrent I/O
Sequential blocking calls execute over a longer duration of
time than concurrent blocking calls.

Waiting on a Future
Because the call to Future.get() will block, you must
do one of the following:
Submit all your work to the
ExecutorService before calling any
Future.get() methods.
Be prepared to wait for that Future to obtain
the result. Wall Clock
Use a non-blocking method such as
Future.isDone() before calling There are different ways to measure time. In the graphic a
Future.get() or use Future.get(long sequence of five sequential calls to network servers will
timeout, TimeUnit unit), which will take approximately 10 seconds if each call takes 2
throw a TimeoutException if the result is seconds. On the right side of the graphic, five concurrent
not available within a given duration. calls to network servers may only take a little over 2
seconds if each call takes 2 seconds. Both examples use
approximately the same amount of CPU time, the amount
Shutting Down an of CPU cycles consumed, but have different overall
durations or wall clock time.
ExecutorService
Shutting down an ExecutorService is important
because its threads are nondaemon threads and will keep A Single-Threaded Network Client
your JVM from shutting down.
respond before attempting to communicate with another
server. About 2 seconds instead of 20 is required to
retrieve all the data.

A Multithreaded Network Client (Part


2)

Synchronous Invocation
In the example in this slide, we are trying to discover
which vendor offers the lowest price for an item. The
client will communicate with ten different network
servers; each server will take approximately two seconds A Multithreaded Network Client (Part
to look up the requested data and return it. There may be 3)
additional delays introduced by network latency.
This single-threaded client must wait for each server to
respond before moving on to another server. About 20
seconds is required to retrieve all the data.

A Multithreaded Network Client (Part


1)

A Multithreaded Network Client (Part


4)

Asynchronous Invocation
In the example in this slide, we are trying to discover
which vendor offers the lowest price for an item. The
client will communicate with ten different network
servers, each server will take approximately two seconds
to look up the requested data and return it. There may be
additional delays introduced by network latency. A Multithreaded Network Client (Part
This multithreaded client does not wait for each server to 5)
Parallelism
Modern systems contain multiple CPUs. Taking advantage
of the processing power in a system requires you to Setting the Stage
execute tasks in parallel on multiple CPUs. If you have a large amount of data to process but only one
Divide and conquer: A task should be divided into thread to process that data, a single CPU will be used. In
subtasks. You should attempt to identify those the slide's graphic, a large set of data (an array, possibly) is
subtasks that can be executed in parallel. be processed. The array processing could be a simple task
Some problems can be difficult to execute as such as finding the highest value in the array. In a four
parallel tasks. CPU system, there would be three CPUs sitting idle while
Some problems are easier. Servers that support the array was being processed.
multiple clients can use a separate task to handle
each client.
Be aware of your hardware. Scheduling too many Naive Parallelism
parallel tasks can negatively impact performance.
A simple parallel solution breaks the data to be processed
CPU Count into multiple sets. One data set for each CPU and one
thread to process each data set.
If your tasks are compute-intensive as opposed to I/O
intensive, the number of parallel tasks should not greatly
outnumber the number of processors in your system. You
can detect the number of processors easily in Java:
int count = Runtime.getRuntime
().availableProcessors();

Without Parallelism
Modern systems contain multiple CPUs. If you do not
leverage threads in some way, only a portion of your
systems processing power will be utilized.

Splitting the Data


In the slides graphic, a large set of data (an array,
possibly) is split into four subsets of data, one subset for
each CPU. A thread per CPU is created to process the data.
After processing, the subsets of data the results will have
to combined in a meaningful way. There are several ways
to subdivide the large dataset to be processed. It would be
overly memory-intensive to create a new array per thread
that contains a copy of a portion of the original array. Each
array can share a reference to the single large array but
access only a subset in a nonblocking thread-safe way.

The Need for the Fork-Join


Framework
Splitting datasets into equal sized subsets for each thread
to process has a couple of problems. Ideally all CPUs
should be fully utilized until the task is finished but:
CPUs may run a different speeds
Non-Java tasks require CPU time and may reduce
the time available for a Java thread to spend
executing on a CPU
The data being analyzed may require varying
amounts of time to process
Work Granularity
By subdividing the data to be processed until there are
more subsets than threads, we are facilitating work-
stealing. In work-stealing, a thread that has run out of
work can steal work (a data subset) from the processing
queue of another thread. You must determine the optimal
size of the work to add to each threads processing queue.
Overly subdividing the data to be processed can cause
unnecessary overhead, while insufficiently subdividing the
data can result in underutilization of CPUs.

A Single-Threaded Example

Work-Stealing
To keep multiple threads busy:
Divide the data to be processed into a large
number of subsets
Assign the data subsets to a threads processing
queue
Each thread will have many subsets queued
If a thread finishes all its subsets early, it can steal
subsets from another thread.

Parallel Potential
In this example there are two separate tasks that could be
executed in parallel. Initializing the array with random
values and searching the array for the largest possible
value could both be done in parallel.

java.util.concurrent.ForkJoinTask
A ForkJoinTask object represents a task to be Threshold)
executed.
A task contains the code and data to be processed.
Similar to a Runnable or Callable.
A huge number of tasks are created and processed
by a small number of threads in a Fork-Join pool.
- A ForkJoinTask typically creates
more ForkJoinTask instances until the
data to processed has been subdivided
adequately.
Developers typically use the following
subclasses:
- RecursiveAction: When a task does
not need to return a result
- RecursiveTask: When a task does
need to return a result

RecursiveTask Example compute Example (Above


Threshold)

compute Structure Memory Management


Notice that the same array is passed to every task but with
different start and end values. If the subset of values to be
processed were copied into a new array each time a task
was created, memory usage would quickly skyrocket.

ForkJoinPool Example
A ForkJoinPool is used to execute a
ForkJoinTask. It creates a thread for each CPU in the
system by default.

compute Example (Below


Use an ExecutorService to concurrently
execute tasks
Apply the Fork-Join framework

(Optional) Practice 13-1 Overview:


Using the
java.util.concurrent Package
Fork-Join Framework This practice covers the following topics:
Recommendations Using a cached thread pool
(ExecutorService)
Avoid I/O or blocking operations. Implementing Callable
- Only one thread per CPU is created by Receiving Callable results with a Future
default. Blocking operations would keep In this practice, you create a multithread network client.
you from utilizing all CPU resources.
Know your hardware.
- A Fork-Join solution will perform slower (Optional) Practice 13-2 Overview:
on a one-CPU system than a standard
sequential solution. Using the Fork-Join Framework
- Some CPUs increase in speed when only This practice covers the following topics:
using a single core, potentially offsetting Extending RecursiveAction
any performance gain provided by Fork- Creating and using a ForkJoinPool
Join. In this practice, you create a multithread network client.
Know your problem.
- Many problems have additional overhead
if executed in parallel (parallel sorting, for
example).

Parallel Sorting
When using Fork-Join to sort an array in parallel, you end
up sorting many small arrays and then having to combine
the small sorted arrays into larger sorted arrays. For an
example see the sample application provided with the JDK
in C:\Program Files\Java\jdk1.7.0\sample
\forkjoin\mergesort.

Quiz
Applying the Fork-Join framework will always result in a
performance benefit.
a. True
b. False
Answer: b

Summary
In this lesson, you should have learned how to:
Use atomic variables
Use a ReentrantReadWriteLock
Use the java.util.concurrent collections
Describe the synchronizer classes
JDBC URL, and name and password are
strings that the database will accept for a
connection.
Chapter 14 2. Use the Connection object (implemented by
some class that the vendor provided) to obtain a
Building Database Applications with reference to a Statement object through the
createStatement method. The typical
JDBC signature for this method is
createStatement () with no arguments.
3. Use the Statement object to obtain an instance
Objectives of a ResultSet through an executeQuery
(query) method. This method typically accepts
After completing this lesson, you should be able to:
a string (query) where query is a static string
Define the layout of the JDBC API
Connect to a database by using a JDBC driver SQL.
Submit queries and get results from the database
Specify JDBC driver information externally
Use transactions with JDBC
Using a Vendors Driver Class
Use the JDBC 4.1 RowSetProvider and The DriverManager class is used to get an instance of
RowSetFactory a Connection object, using the JDBC driver named in the
Use a Data Access Object Pattern to decouple JDBC URL:
data and business methods

Using the JDBC API


The URL syntax for a JDBC driver is:

Each vendor can implement its own subprotocol.


The URL syntax for an Oracle Thin driver is:
Example:

DriverManager
Any JDBC 4.0 drivers that are found in the class path are
automatically loaded. The
DriverManager.getConnectionmethod will
attempt to load the driver class by looking at the file
META_INF/services/java.sql.Driver. This
file contains the name of the JDBC driver's
The JDBC API is made up of some concrete classes, such
implementation of java.sql.Driver. For example,
as Date, Time, and SQLException, and a set of
the contents of METAINF/ services/
interfaces that are implemented in a driver class that is
provided by the database vendor. java.sql.driver file in the derbyclient.jar
Because the implementation is a valid instance of the contains
interface method signature, once the database vendor's org.apache.derby.jdbc.ClientDriver.
Driver classes are loaded, you can access them by Drivers prior to JDBC 4.0 must be loaded manually by
following the sequence shown in the slide: using:
1. Use the class DriverManager to obtain a try {
java.lang.Class.forName("<fully
reference to a Connection object using the
qualified path of the driver>");
getConnection method . The typical
} catch (ClassNotfoundException c) {
signature of this method is getConnection }
(url, name, password), where url is the Driver classes can also be passed to the interpreter on the
command line:
java -djdbc.drivers=<fully qualified Using a ResultSet Object
path to the driver> <class to run>

Key JDBC API Components


Each vendor's JDBC driver class also implements the key
API classes that you will use to connect to the database,
execute queries, and manipulate data:
java.sql.Connection: A connection that
represents the session between your Java
application and the database

java.sql.Statement: An object used to


execute a static SQL statement and return the
result ResultSet Objects
java.sql.ResultSet: A object representing ResultSet maintains a cursor to the returned
a database result set rows. The cursor is initially pointing before the
first row.
The ResultSet.next() method is called to
Connections, Statements, and position the cursor in the next row.
The default ResultSet is not updatable and has
ResultSets a cursor that points only forward.
It is possible to produce ResultSet objects that
The real beauty of the JDBC API lies in the way it
provides a flexible and portable way to communicate with are scrollable and/or updatable. The following
a database. code fragment, in which con is a valid
The JDBC driver that is provided by a database vendor Connection object, illustrates how to make a
implements each of these Java interfaces. Your Java code result set that is scrollable and insensitive to
can use the interface knowing that the database vendor updates by others, and that is updatable:
provided the implementation of each of the methods in the Statement stmt =
interface. con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIV
Connection is an interface that provides a session with
E, ResultSet.CONCUR_UPDATABLE);
the database. While the connection object is open, you can
ResultSet rs = stmt.executeQuery
access the database, create statements, get results, and ("SELECT a, b FROM TABLE2");
manipulate the database. When you close a connection, the
Note: Not all databases support scrollable result sets.
access to the database is terminated and the open
ResultSet has accessor methods to read the contents of
connection closed.
each column returned in a row. ResultSet has a
Statement is an interface that provides a class for
getter method for each type.
executing SQL statements and returning the results. The
Statement interface is for static SQL queries. There are
two other subinterfaces: PreparedStatement, which
extends Statement and CallableStatement,
Putting It All Together
which extends PreparedStatement.
ResultSet is an interface that manages the resulting
data returned from a Statement.
Note: SQL commands and keywords are case-insensitive-
that is, you can use SELECT, or Select. SQL table and
column names (identifiers) may be case-insensitive or
case-sensitive depending upon the database. SQL
identifiers are case-insensitive in the Derby database
(unless delimited).
with-resources statement on line 15.
This example is from the SimpleJDBCExample
project.
Output:
run:
Employee ID: 110
Employee Name: Troy Hammer
Birth Date: 1965-03-31
Salary: 102109.15

Writing Portable JDBC Code


In this slide and in the following slide, you see a complete The JDBC driver provides a programmatic "insulating"
example of a JDBC application, a simple one that reads all layer between your Java application and the database.
the rows from an Employee database and returns the However, you also need to consider SQL syntax and
results as strings to the console. semantics when writing database applications.
Line 15-16: Use a try-with-resources statement Most databases support a standard set of SQL
to get an instance of an object that implements the syntax and semantics described by the American
Connection interface. National Standards Institute (ANSI) SQL-92
Line 17: Use that object to get an instance of an Entry-level specification.
object that implements the Statement interface You can programmatically check for support for
from the Connection object. this specification from your driver:
Line 18: Create a ResultSet by executing the
string query using the Statement object.
Note: Hard coding the JDBC URL, username, and
password makes an application less portable. Instead, In general, you will probably write an application that
consider using java.io.Console to read the username leverages the capabilities and features of the database you
and password and/or some type of authentication service. are working with. However, if you want to write a portable
application, you need to consider what support each
database will provide for SQL types and functionality.
Fortunately, you can query the database driver
programmatically to determine what level of support the
driver provides. The DatabaseMetaData interface has
a set of methods that the driver developer uses to indicate
what the driver supports, including support for the entry,
intermediate, or full support for SQL-92.
The DatabaseMetaData interface also includes other
methods that determine what type of support the database
provides for queries, types, transactions, and more.

The SQLException Class


Lines 20-24: Get the results of each of the data SQLException can be used to report details about
fields in each row read from the Employee resulting database errors. To report all the exceptions
table. thrown, you can iterate through the SQLExceptions
Lines 25-28: Print the resulting data fields to the thrown:
system console.
Line 30: SQLException: This class extends
Exception thrown by the DriverManager,
Statement, and ResultSet methods. (More
about this exception class in the next slide.)
Line 32: This is the closing brace for the try-
invalidate any instances of ResultSet created
by the Statement object.
Resources held by the ResultSet, may not be
released until garbage is collected, so it is a good
practice to explicitly close ResultSet objects
when they are no longer needed.
When the close() method on ResultSet is
executed, external resources are released.
ResultSet objects are also implicitly closed
when an associated Statement object is re-
executed.
A SQLException is thrown from errors that In summary, it is a good practice to explicitly close JDBC
occur in one of the following types of actions: Connection, Statement and ResultSet objects
driver methods, methods that access the database, when you no longer need them.
or attempts to get a connection to the database. Note: A connection with the database can be an expensive
The SQLException class also implements operation. It is a good practice to either maintain
Iterable. Exceptions can be chained together Connection objects for as long as possible, or use a
and returned as a single object. connection pool.
SQLException is thrown if the database
connection cannot be made due to incorrect
username or password information or simply the The try-with-resources Construct
database is offline.
SQLException can also result by attempting to Given the following try-with-resources statement:
access a column name that is not part of the SQL
query.
SQLException is also subclassed, providing
granularity of the actual exception thrown.
Note: SQLState and SQLErrorCode values are
database dependent. For Derby, the SQLState values are The compiler checks to see that the object inside
defined here: the parentheses implements
http://download.oracle.com/javadb/10.8.1.2/ref/ java.lang.AutoCloseable.
rrefexcept71493.html. - This interface includes one method: void
close().
The close method is automatically called at the
Closing JDBC Objects end of the try block in the proper order (last
declaration to first).
Multiple closeable resources can be included in
the try block, separated by semicolons.
One of the JDK 7 features is the try-with-resources
statement. This is an enhancement that will automatically
close open resources.
With JDBC 4.1, the JDBC API classes including
ResultSet, Connection, and Statement,
implement java.lang.AutoCloseable. The
close() method of the ResultSet, Statement, and
Connection objects will be called in order in this
example.

try-with-resources: Bad Practice


Closing a Connection object will It might be tempting to write try-with-resources more
automatically close any Statement objects compactly:
created with this Connection.
Closing a Statement object will close and
executeUpdate(sqlString): For
INSERT, UPDATE, and DELETE statements,
However, only the close method of ResultSet returns an int (number of rows affected), or 0
is called, which is not a good practice. when the statement is a Data Definition Language
Always keep in mind which resources you need (DDL) statement, such as CREATE TABLE.
to close when using try-with-resources. execute(sqlString): For any SQL
statement, returns a boolean indicating if a
Avoid This try-with-resources Pitfall ResultSet was returned. Multiple SQL
statements can be executed with execute.
It may appear to be a time-saving way to write these three
statements, but the net effect is that the Connection
returned by the DriverManager is never explicitly Practice 14-1 Overview: Working with
closed after the end of the try block, which is not a good
practice. the Derby Database and JDBC
This practice covers the following topics:
Starting the JavaDB (Derby) database from
Writing Queries and Getting Results within NetBeans IDE
To execute SQL queries with JDBC, you must create a Populating the database with data (the Employee
SQL query wrapper object, an instance of the Statement table)
object. Running SQL queries to look at the data
Compiling and running the sample JDBC
application
In this practice, you will start the database from within
Use the Statement instance to execute a SQL NetBeans, populate the database with data, run some SQL
query: queries, and compile and run a simple application that
returns the rows of the Employee database table.
Note that there are three Statement execute
methods:
ResultSetMetaData
Method Returns Used for There may be a time where you need to dynamically
executeQuery ResultSet SELECT discover the number of columns and their type.
(sqlString) statement
executeUpdat int (rows INSERT,
e(sqlString) affected) UPDATE,
DELETE, or a
DDL
execute boolean (true if Any SQL
(sqlString) there was a command or
ResultSet) commands

A SQL statement is executed against a database using an


instance of a Statement object. The Statement object is a
wrapper object for a query. A Statement object is obtained The ResultSetMetaData class is obtained from a
through a Connection object-the database connection. So it ResultSet.
makes sense that from a Connection, you get an object that The getColumnCount returns the number of columns
you can use to write statements to the database. returned in the query that produced the ResultSet.
The Statement interface provides three methods for The getColumnName and getColumnTypeName
creating SQL queries and returning a result. Which one methods return strings. These could be used to perform a
you use depends upon the type of SQL statement you want dynamic retrieval of the column data.
to use: Note: These methods use 1 to indicate the first column,
executeQuery(sqlString): For a not 0.
SELECT statement, returns a ResultSet Given a query of "SELECT * FROM Employee" and the
object Employee data table from the practices, this fragment
produces this result: fetch size:
Number of columns returned: 5
Column names/types returned: Calls to rs.next() return the data in the cache
ID : INTEGER th
until the 26 row, at which time the driver will
FIRSTNAME : VARCHAR fetch another 25 rows.
LASTNAME : VARCHAR Note: Normally the most efficient fetch size is already the
BIRTHDATE : DATE default for the driver.
SALARY : REAL

Using PreparedStatement
Getting a Row Count
PreparedStatement is a subclass of Statement that
A common question when executing a query is: "How allows you to pass arguments to a precompiled SQL
many rows were returned?" statement.

In this code fragment, a prepared statement


returns all columns of all rows whose salary is
greater than $100,000.
PreparedStatement is useful when you
To use this technique, the ResultSet must be have a SQL statements that you are going to
scrollable. execute multiple times.
Note: Recall that to create a ResultSet that is PreparedStatement
scrollable, you must define the ResultSet type in the The SQL statement in the example in the slide is
createStatement method: precompiled and stored in the PreparedStatement
Statement stmt = con.createStatement object. This statement can be used efficiently to execute
(ResultSet.TYPE_SCROLL_INSENSITIVE, this statement multiple times. This example could be in a
ResultSet.CONCUR_UPDATABLE); loop, looking at different values.
There is another technique for non-scrollable ResultSets. Prepared statements can also be used to prevent SQL
Using the SQL COUNT function, one query determines injection attacks. For example, where a user is allowed to
the number of rows and a second reads the results. Be enter a string, that when executed as a part of a SQL
aware that this technique requires locking control over the statement, enables the user to alter the database in
tables to ensure the count is not changed during the unintended ways (like granting themselves permissions).
operation: Note: PreparedStatement setXXXX methods index
ResultSet rs = stmt.executeQuery parameters from 1, not 0. The first parameter in a prepared
("SELECT COUNT(*) FROM EMPLOYEE"); statement is 1, the second parameter is 2, and so on.
rs.next();
int count = rs.getInt(1);
rs.stmt.excuteQuery ("SELECT * FROM Using CallableStatement
EMPLOYEE");
// process results A CallableStatement allows non-SQL statements
(such as stored procedures) to be executed against the
database.
Controlling ResultSet Fetch Size
By default, the number of rows fetched at one time by a
query is determined by the JDBC driver. You may wish to
control this behavior for large data sets.
For example, if you wanted to limit the number of
rows fetched into cache to 25, you could set the
DriverManager.getConnection(url);
String query = "SELECT COUNT
(DISTINCT ID) " + "AS count FROM
Employee " + "WHERE Birthdate <= ?";
PreparedStatement ps =
con.prepareStatement(query);
Calendar now =
Calendar.getInstance();
now.add(Calendar.YEAR,
(age*-1));
Stored procedures are executed on the database. Date past = new Date
(now.getTimeInMillis());
Derby Stored Procedures ps.setDate(1, past);
ResultSet rs = ps.executeQuery
The Derby database uses the Java programming language
();
for its stored procedures. if (rs.next()) {
In the example shown in the slide, the stored procedure is count[0] = rs.getInt(1);
declared using the following syntax: } else {
CREATE PROCEDURE EmplAgeCount (IN age count[0] = 0;
INTEGER, OUT num INTEGER) }
DYNAMIC RESULT SETS 0 con.close();
LANGUAGE JAVA }
EXTERNAL NAME }
'DerbyStoredProcedure.countAge' Consult the Derby Reference Manual and Derby Tools and
PARAMETER STYLE JAVA Utilities Guide for more information on creating stored
READS SQL DATA;
procedures.
A Java class is loaded into the Derby database using the
following syntax:
CALL SQLJ.install_jar ('D:\temp What Is a Transaction?
\DerbyStoredProcedure.jar',
'PUBLIC.DerbyStoredProcedure', 0); A transaction is a mechanism to handle groups of
CALL operations as though they were one.
syscs_util.syscs_set_database_property Either all operations in a transaction occur or
('derby.database.classpath', none occur at all.
'PUBLIC.DerbyStoredProcedure'); The operations involved in a transaction might
The Java class stored in the Derby database that performs rely on one or more databases.
the stored procedure calculates a date that is age years in A classic example of when a transaction would be used is
the past based on today's date. The SQL query counts the as follows. Suppose that a client application needs to make
number of unique employees that are older (or equal to) a service request that might involve multiple read and
the number of years passed in and returns that count as the write operations to a database. If any one invocation is
second parameter of the stored procedure. The code in this unsuccessful, any state that is written (either in memory
example looks like this: or, more typically, to a database) must be rolled back.
import java.sql.Connection; Consider an interbank fund transfer application in which
import java.sql.Date; money is transferred from one bank to another.
import java.sql.DriverManager; The transfer operation requires the server to make the
import java.sql.PreparedStatement; following invocations:
import java.sql.ResultSet; 1. Invoking the debit method on one account at the
import java.sql.SQLException; first bank
import java.util.Calendar; 2. Invoking the credit method on another account at
the second bank
public class DerbyStoredProcedure { If the credit invocation on the second bank fails, the
public static void countAge (int banking application must roll back the previous debit
age, int[] count) throws SQLException { invocation on the first bank.
String url = Note: When a transaction spans multiple databases, more
"jdbc:default:connection"; complicated transaction services may be required.
Connection con =
specific object instance. The conversation can be
characterized by one or more of the following:
ACID Properties of a Transaction A. Data is cached in memory or written to a database
during or after each successive invocation.
A transaction is formally defined by the set of properties
that is known by the acronym ACID. B. Data is written to a database at the end of the
conversation.
Atomicity: A transaction is done or undone
completely. In the event of a failure, all C.The client application requires that the object maintains
operations and procedures are undone, and all an in-memory context between each invocation; each
data rolls back to its previous state. successive invocation uses the data that is maintained in
Consistency: A transaction transforms a system memory.
from one consistent state to another consistent D. At the end of the conversation, the client application
state. requires the capability to cancel all the database write
Isolation: Each transaction occurs independently operations that may have occurred during or at the end of
of other transactions that occur at the same time. the conversation.
Durability: Completed transactions remain Consider a shopping cart application. Users of the client
permanent, even during system failure. application browse an online catalog and make multiple
Transactions should have the following ACID properties: purchase selections. They proceed to check out and enter
Atomicity: All or nothing; all operations involved credit card information to make the purchase. If the credit
in the transaction are implemented or none are. card verification fails, the shopping application must
Consistency: The database must be modified cancel all the pending purchase selections in the shopping
from one consistent state to another. In the event cart or roll back the purchase transactions made during the
the system or database fails during the conversation.
transaction, the original state is restored (rolled
back).
Isolation: An executing transaction is isolated Successful Transfer with Transactions
from other executing transactions in terms of the Changes within a transaction are buffered. (A)
database records it is accessing. If a transfer is successful, changes are committed
Durability: After a transaction is committed, it (made permanent). (B)
can be restored to this state in the event of a
system or database failure.

Transferring Without Transactions


Successful transfer (A)
Unsuccessful transfer (Accounts are left in an
inconsistent state.) (B)

If the transaction is successful, the buffered changes are


committed, that is, made permanent.
Within the scope of one client invocation on an object, the
object performs multiple changes to the data in a database.
If one change fails, the object must roll back all the
changes. Consider a banking application. The client
invokes the transfer operation on a teller object. The
operation requires the teller object to make the following
Transactions are appropriate in the following scenarios. invocations on the bank database:
Each situation describes a transaction model that is 1. Invoking the debit method on one account
supported by the resource local transaction model 2. Invoking the credit method on another account
implementation in the EntityManager instance. If the credit invocation on the bank database fails, the
A client application must converse with an object that is banking application must roll back the previous debit
managed, and it must make multiple invocations on a invocation.
Statements are in a transaction context until
either the Connection commit or rollback
Unsuccessful Transfer with method is executed.
Transactions If the value of auto-commit is changed in the
middle of a transaction, the current transaction is
Changes within a transaction are buffered. (A) committed.
If a problem occurs, the transaction is rolled back In addition, the Derby driver documentation adds the
to the previous consistent state. (B) following:
A transaction context is associated with a single
Connection object (and database). A
transaction cannot span multiple Connections
(or databases).
Note: A sample application using transactions is in the
project file JDBCTransactionsExample in the
examples directory.

RowSet 1.1: RowSetProvider and


RowSetFactory
If the transaction is unsuccessful, the buffered changes are
thrown out and the database is rolled back to its previous The JDK 7 API specification introduces the new RowSet
consistent state. 1.1 API.
One of the new features of this API is
RowSetProvider.
JDBC Transactions javax.sql.rowset.RowSetProvider is
used to create a RowSetFactory object:
By default, when a Connection is created, it is in auto-
commit mode. The default RowSetFactory implementation
Each individual SQL statement is treated as a is:
transaction and automatically committed after it
is executed. RowSetFactory is used to create one of the
To group two or more statements together, you RowSet 1.1 RowSet object types.
must disable auto-commit mode.
RowSet 1.1
You must explicitly call the commit method to
complete the transaction with the database. New for JDK7 are the
javax.sql.rowset.RowSetProvider and
You can also programmatically roll back javax.sql.rowset.RowSetFactory classes.
transactions in the event of a failure. These two classes are used to construct instances of
RowSets as discussed in the next slide.
By default, JDBC auto-commits all SQL statements.
However, when you want to create an atomic operation
that involves multiple SQL statements, you must disable Using RowSet 1.1 RowSetFactory
auto-commit.
After auto-commit is disabled, no SQL statements are RowSetFactory is used to create instances of RowSet
committed to the database until you explicitly call the implementations:
commit method.
The other advantage of managing your own transactions is RowSet type Provides
the ability to rollback a set of SQL statements in the event CachedRowSet A container for rows of data
of a failure using the rollback method. that caches its rows in
Note: JDBC does not have an API to explicitly begin a memory
transaction. The JDBC JSR (221) provides the following FilteredRowSet A RowSet object that
guidelines: provides methods for
When auto-commit is disabled for a filtering support
Connection object, all subsequent JdbcRowSet A wrapper around ResultSet
to treat a result set as a required when describing a RowSet object in
JavaBeans component XML, and must be used by all standard
JoinRowSet A RowSet object that implementations of the WebRowSet interface to
provides mechanisms for ensure interoperability. In addition, the
combining related data from WebRowSet schema uses specific SQL/XML
different RowSet objects Schema annotations, thus ensuring greater cross-
WebRowSet A RowSet object that platform interoperability. This is an effort
supports the standard XML currently under way at the ISO organization.
document format required
when describing a RowSet
object in XML Example: Using JdbcRowSet
CachedRowSet: A CachedRowSet object is a
container for rows of data that caches its rows in
memory. This makes it possible to operate
without always being connected to its data
source. Further, it is a JavaBeans component and
is scrollable, updatable, and serializable. A
CachedRowSet object typically contains rows
from a result set, but it can also contain rows
from any file with a tabular format, such as a
spreadsheet. The reference implementation
supports getting data only from a ResultSet
object, but developers can extend the
SyncProvider implementations to provide
access to other tabular data sources.
FilteredRowSet: A JDBC FilteredRowSet In the code fragment in the slide, you create a
standard implementation implements the JdbcRowSet instance from
RowSet interfaces and extends the RowSetProviderFactory.
CachedRowSet class. The CachedRowSet You then treat the object like a RowSet JavaBean. You
class provides a set of protected cursor can use setter methods to set the url, username,
manipulation methods, which a and password, and then execute a SQL command and
FilteredRowSet implementation can obtain a ResultSet to retrieve the column values.
override to supply filtering support. This example is from the
JdbcRowSet: A JdbcRowSet is a wrapper SimpleJDBCRowSetExample project.
around a ResultSet object that makes it
possible to use the result set as a JavaBeans
component. Thus, a JdbcRowSet object can be Data Access Objects
one of the Beans that a tool makes available for
composing an application. Because a Consider an employee table like the one in the sample
JdbcRowSet is a connected rowset, that is, it JDBC code.
continually maintains its connection to a database
using a JDBC technology-enabled driver, it also
effectively makes the driver a JavaBeans
component.
JoinRowSet: The JoinRowSet interface
provides a mechanism for combining related data
from different RowSet objects into one
JoinRowSet object, which represents a SQL
JOIN. In other words, a JoinRowSet object
acts as a container for the data from the RowSet
objects that form a SQL JOIN relationship. By combining the code that accesses the database
WebRowSet: The WebRowSet interface with the "business" logic, the data access methods
describes the standard XML document format and the Employee table are tightly coupled.
Any changes to the table (such as adding a field) interface encourages additional separation
will require a complete change to the application. between the implementation of the methods
Employee data is not encapsulated within the required to support the DAO and references to
example application. EmployeeDAO objects.
3. The EmployeeDAOJDBCImpl implements the
The Employee Table EmployeeDAO interface. The implementation
In the SimpleJDBCExample application shown in the class can be replaced with a different
previous slide, there is tight coupling between the implementation without impacting the client
operations used to access the data and the Employee table application.
itself. Granted that the example is simple, but if you
imagine this type of access in a larger application, perhaps
with multiple tables with inter-table relationships, you can
Summary
see how directly accessing the database in the same class In this lesson, you should have learned how to:
as the business methods could create problems later if the Define the layout of the JDBC API
Employee table were to change. Connect to a database by using a JDBC driver
Further, because you are accessing the data directly, you Submit queries and get results from the database
do not have any way of passing the notion of an Employee Specify JDBC driver information externally
around. You need to treat an Employee as an object. Use transactions with JDBC
Use the JDBC 4.1 RowSetProvider and
RowSetFactory
The Data Access Object Pattern Use a Data Access Object Pattern to decouple
data and business methods

Quiz
1. Which Statement method executes a SQL
statement and returns the number of rows
affected?
a. stmt.execute(query);
b. stmt.executeUpdate(query);
c. stmt.executeQuery(query);
d. stmt.query(query);
Answer: b
The Data Access Object and Factory a: execute returns a boolean (true if there
Pattern is a ResultSet. This can be used with any SQL
statement).
The purpose of a Data Access Object (DAO) is to separate
c: executeQuery returns a ResultSet (used
database-related activities from the business model. In this
with a SELECT statement).
design pattern, there are two techniques to insure future
design flexibility. d: This is not a valid Statement method.
1. A factory is used to generate instances 2. When using a Statement to execute a query
(references) to an implementation of the that returns only one record, it is not necessary to
EmployeeDAO interface. A factory makes it use the ResultSet's next() method.
possible to insulate the developer using the DAO a. True
from the details about how a DAO b. False
implementation is instantiated. As you have seen, Answer: b (False)
this same pattern was used to create an A ResultSet's pointer is always pointing to just
implementation where the data was stored in before the first row, regardless of whether it is
memory. one row or multiple rows.
2. An EmployeeDAO interface is designed to 3. The following try-with-resources statement will
model the behavior that you want to allow on the properly close the JDBC resources:
Employee data. Note that this technique of
separating behavior from data demonstrates a
separation of concerns. The EmployeeDAO
a. True
b. False
Answer: a (True)
This illustrates a good practice: explicitly closing
the ResultSet in try-with-resources.
4. Given:

Assuming there is a valid Connection object and


the SQL query will produce at least one row, what
is the result?
a. Each itemCount value for customer
Bob Smith
b. Compiler error
c. A run time error
d. A SQLException
Answer: c
Notice on line15, the PreparedStatement
setObject method is called using the array
index, 0, instead of 1 for the first parameter. To
fix this code, you should replace line 15 with:
pStmt.setObject(i+1, params[i]);

Practice 14-2 Overview: Using the


Data Access Object Pattern
This practice covers the following topics:
Refactoring the memory-based DAO application
to use JDBC.
Using the interactive Employee client application,
test your code.
In this practice, you will refactor the existing memory-
based DAO from Exceptions and Assertions to use JDBC
instead. An interactive client is provided so you can
experiment with creating, reading, updating, and deleting
records by using JDBC.
Chapter 15
Localization

Objectives
After completing this lesson, you should be able to:
Describe the advantages of localizing an
application
Define what a locale represents In the remainder of this lesson, this simple text-based user
Read and set the locale by using the Locale interface will be localized for French, Simplified Chinese,
object and Russian. Enter the number indicated by the menu and
Build a resource bundle for each locale that menu option will be applied to the application. Enter
Call a resource bundle from an application q to exit the application.
Change the locale for a resource bundle
Format text for localization by using
NumberFormat and DateFormat Locale
A Locale specifies a particular language and country:
Language
Why Localize? - An alpha-2 or alpha-3 ISO 639 code
The decision to create a version of an application for - en for English, es for Spanish
international use often happens at the start of a - Always uses lowercase
development project. Country
Region- and language-aware software - Uses the ISO 3166 alpha-2 country code
Dates, numbers, and currencies formatted for or UN M.49 numeric area code
specific countries - US for United States, ES for Spain
Ability to plug in country-specific data without - Always uses uppercase
changing Code See The Java Tutorials for details of all standards
Localization is the process of adapting software for a used
specific region or language by adding locale-specific In Java, a locale is specified by using two values: language
components and translating text. and country. See the Java Tutorial for standards used:
In addition to language changes, culturally dependent http://download.oracle.com/javase/
elements, such as dates, numbers, currencies, and so on tutorial/i18n/locale/create.html
must be translated. Language Samples
The goal is to design for localization so that no coding de: German
changes are required. en: English
fr: French
zh: Chinese
A Sample Application Country Samples
DE: Germany
Localize a sample application: US: United States
Text-based user interface FR: France
Localize menus CN: China
Display currency and date localizations

Resource Bundle
The ResourceBundle class isolates locale-
specific data:
? Returns key/value pairs stored separately
? Can be a class or a .properties file
Steps to use:
- Create bundle files for each locale.
- Call a specific locale from your
application.
Design for localization begins by designing the application
so that all the text, sounds, and images can be replaced at
run time with the appropriate elements for the region and
culture desired. Resource bundles contain key/value pairs
that can be hard-coded within a class or located in
a .properties file.

Resource Bundle File


Properties file contains a set of key/value pairs.
- Each key identifies a specific application
component.
- Special file names use language and
country codes.
Default for sample application: The slide shows the resource bundle files for French and
- Menu converted into resource bundle Chinese. Note that the file names include both language
and country. The English menu item text has been
replaced with French and Chinese alternatives.

Quiz
Which bundle file represents a language of Spanish and a
country code of US?
a. MessagesBundle_ES_US.properties
b. MessagesBundle_es_es.properties
c. MessagesBundle_es_US.properties
d. MessagesBundle_ES_us.properties
Answer: c

The slide shows a sample resource bundle file for this


application. Each menu option has been converted into a Initializing the Sample Application
name/value pair. This is the default file for the application.
For alternative languages, a special naming convention is
used:
MessageBundle_xx_YY.properties
where xx is the language code and YY is the country code.

Sample Resource Bundle Files


Samples for French and Chinese

With the resource bundles created, you simply need to


load the bundles into the application. The source code in
the slide shows the steps. First, create a Locale object
that specifies the language and country. Then load the
resource bundle by specifying the base file name for the
bundle and the current Locale. Changing the Locale
Note that there are a couple of ways to define a Locale.
To change the Locale:
The Locale class includes default constants for some
Set currentLocale to the desired language.
countries. If a constant is not available, you can use the
Reload the bundle by using the current locale.
language code with the country code to define the
location. Finally, you can use the getDefault()
method to get the default location.

Sample Application: Main Loop


After the menu bundle is updated with the correct locale,
the interface text is output by using the currently selected
language.

Sample Interface with French


After the French option is selected, the updated user
interface looks like the following:

For this application, a run method contains the main loop.


The loop runs until the letter q is typed in as input. A
string switch is used to perform an operation based on the
number entered. A simple call is made to each method to
make locale changes and display formatted output.

The printMenu Method


The updated user interface is shown in the slide. The first
Instead of text, resource bundle is used. and last lines of the application could be localized as well.
messages is a resource bundle.
A key is used to retrieve each menu item.
Language is selected based on the Locale Format Date and Currency
setting.
Numbers can be localized and displayed in their
local format.
Special format classes include:
- DateFormat
- NumberFormat
Create objects using Locale.
Changing text is not the only available localization tool.
Dates and numbers can also be formatted based on local
standards.

Instead of printing text, the resource bundle (messages)


is called and the current Locale determines what Initialize Date and Currency
language is presented to the user. The application can show a local formatted date and
currency. The SimpleDateFormat class is a subclass of
The variables are initialized as follows: DateFormat and allows you a great deal of control over
the date output. See documentation for all the available
options.
In some cases, the number of letters can determine the
output. For example, with month:
MM 07
MMM Jul
MMMM July

Before any formatting can take place, date and number Displaying Currency
objects must be set up. Both todays date and a Double
object are used in this application. Format currency:
- Get a currency instance from
NumberFormat.
Displaying a Date - Pass the Double to the format method.
Format a date:
? Get a DateFormat object based on the
Locale.
? Call the format method passing the date Sample currency output:
1 000 000 ??. ru_RU
to format.
1 000 000,00 fr_FR
1,000,000.00 zh_CN
Create a NumberFormat object by using the selected
locale and get formatted output.
Sample dates:
20 juil. 2011 fr_FR
20.07.2011 ru_RU
Create a date format object by using the locale and the
Quiz
date is formatted for the selected locale. Which date format constant provides the most detailed
information?
a. LONG
Customizing a Date b. FULL
c. MAX
DateFormat constants include: d. COMPLETE
- SHORT: Is completely numeric, such as Answer: b
12.13.52 or 3:30pm
- MEDIUM: Is longer, such as Jan 12, 1952
- LONG: Is longer, such as January 12, Summary
1952 or 3:30:32pm
- FULL: Is completely specified, such as In this lesson, you should have learned how to:
Tuesday, April 12, 1952 AD or 3:30:42pm Describe the advantages of localizing an
PST application
SimpleDateFormat: Define what a locale represents
- A subclass of a DateFormat class Read and set the locale by using the Locale
object
Build a resource bundle for each locale
Call a resource bundle from an application
Change the locale for a resource bundle
Format text for localization by using
NumberFormat and DateFormat

The DateFormat object includes a number of constants Practice 15-1 Overview: Creating a
you can use to format the date output.
Localized Date Application
This practice covers creating a localized application that
displays dates in a variety of formats.

(Optional) Practice 15-2 Overview:


Localizing a JDBC Application
This practice covers creating a localized version of the
JDBC application from the previous lesson.
Querying data
Inserting, updating, and deleting rows in a table
Creating, replacing, altering, and dropping
Appendix A objects
Controlling access to the database and its objects
SQL Primer Guaranteeing database consistency and integrity
SQL unifies all of the preceding tasks in one consistent
language and enables you to work with data at a logical
level.
Objectives
After completing this lesson, you should be able to:
Describe the syntax of basic SQL-92/1999
SQL Statements
commands, including:
- SELECT
- INSERT
- UPDATE
- DELETE
- CREATE TABLE
- DROP TABLE
Define basic SQL-92/1999 data types

Using SQL to Query Your Database


Structured query language (SQL) is:
The ANSI standard language for operating
relational databases
Efficient, easy to learn, and use
Functionally complete (With SQL, you can
define, retrieve, and manipulate data in the
tables.)

SQL statements supported by Oracle comply with industry


standards. Oracle Corporation ensures future compliance
with evolving standards by actively involving key
personnel in SQL standards committees. The industry-
accepted committees are ANSI and International Standards
Organization (ISO). Both ANSI and ISO have accepted
SQL as the standard language for relational databases.

Statement Description
In a relational database, you do not specify the access SELECT Retrieves data from the
route to the tables, and you do not need to know how the INSERT database, enters new rows,
data is arranged physically. UPDATE changes existing rows, and
To access the database, you execute a structured query DELETE removes unwanted rows
language (SQL) statement, which is the American MERGE from tables in the database,
National Standards Institute (ANSI) standard language for respectively. Collectively
operating relational databases. SQL is a set of statements known as data manipulation
with which all programs and users access data in an Oracle language (DML)
Database. Application programs and Oracle tools often CREATE Sets up, changes, and
allow users access to the database without using SQL ALTER removes data structures
directly, but these applications, in turn, must use SQL DROP from tables. Collectively
when executing the users request. RENAME known as data definition
SQL provides statements for a variety of tasks, including: TRUNCATE language (DDL)
COMMENT
GRANT Provides or removes access Limiting the Rows That Are Selected
REVOKE rights to both the Oracle Restrict the rows that are returned by using the
Database and the structures WHEREclause:
within it
COMMIT Manages the changes made
ROLLBACK by DML statements.
SAVEPOINT Changes to the data can be The WHERE clause follows the FROM clause.
grouped together into You can restrict the rows that are returned from the query
logical transactions by using the WHERE clause. A WHERE clause contains a
condition that must be met and it directly follows the
FROM clause. If the condition is true, the row meeting the
condition is returned.
Basic SELECT Statement In the syntax:

WHERE Restricts the query to rows


that meet a condition
condition Is composed of column
names, expressions,
SELECT identifies the columns to be displayed. constants, and a comparison
FROM identifies the table containing those operator. A condition
columns. specifies a combination of
In its simplest form, a SELECT statement must include the one or more expressions and
following: logical (Boolean) operators,
A SELECT clause, which specifies the columns to and returns a value of
be displayed TRUE, FALSE, or
A FROM clause, which identifies the table UNKNOWN.
containing the columns that are listed in the
SELECT clause The WHERE clause can compare values in columns, literal,
In the syntax: arithmetic expressions, or functions. It consists of three
elements:
SELECT Is a list of one or more Column name
columns Comparison condition
* Selects all columns Column name, constant, or list of values
DISTINCT Suppresses duplicates
column|expression Selects the named column or
the expression Using the ORDER BY Clause
alias Gives the selected columns Sort the retrieved rows with the ORDER BY
different headings clause:
FROM table Specifies the table - ASC: Ascending order, default
containing the columns - DESC: Descending order
The ORDER BY clause comes last in the
Note: Throughout this course, the words keyword, clause, SELECT statement:
and statement are used as follows:
A keyword refers to an individual SQL element
for example, SELECT and FROM are keywords.
A clause is a part of a SQL statementfor
example, SELECT employee_id,
last_name, and so on.
A statement is a combination of two or more
clausesfor example, SELECT * FROM
Employees
The order of rows that are returned in a query result is
undefined. The ORDER BY clause can be used to sort the Note: This statement with the VALUES clause adds only
rows. However, if you use the ORDER BY clause, it must one row at a time to a table.
be the last clause of the SQL statement. Further, you can
specify an expression, an alias, or a column position as the
sort condition. UPDATE Statement Syntax
Syntax Modify existing values in a table with the
UPDATE statement:

SELECT expr
FROM table Update more than one row at a time (if required).
[WHERE condition(s)] You can modify the existing values in a table by using the
[ORDER BY {column, expr, UPDATE statement.
numeric_position} In the syntax:
[ASC|DESC]];
table Is the name of the table
In the syntax: column Is the name of the column in
the table to populate
ORDER BY specifies the order in which value Is the corresponding value
the retrieved rows are or subquery for the column
displayed condition Identifies the rows to be
ASC orders the rows in ascending updated and is composed of
order (This is the default column names, expressions,
order.) constants, subqueries, and
DESC orders the rows in comparison operators
descending order
Confirm the update operation by querying the table to
If the ORDER BY clause is not used, the sort order is display the updated rows.
undefined, and the Oracle server may not fetch rows in the Note: In general, use the primary key column in the
same order for the same query twice. Use the ORDER BY WHERE clause to identify a single row for update. Using
clause to display the rows in a specific order. other columns can unexpectedly cause several rows to be
Note: Use the keywords NULLS FIRST or NULLS updated. For example, identifying a single row in the
LAST to specify whether returned rows containing null EMPLOYEES table by name is dangerous, because more
values should appear first or last in the ordering sequence. than one employee may have the same name.

INSERT Statement Syntax DELETE Statement


Add new rows to a table by using the INSERT You can remove existing rows from a table by using the
statement: DELETE statement:

With this syntax, only one row is inserted at a


time.
You can add new rows to a table by issuing the INSERT
statement.
In the syntax:
DELETE Statement Syntax
You can remove existing rows from a table by using the
table Is the name of the table DELETE statement.
column Is the name of the column in In the syntax:
the table to populate
value Is the corresponding value table Is the name of the table
for the column condition Identifies the rows to be
deleted, and is composed of
column names, expressions, Column-level constraint syntax:
constants, subqueries, and
comparison operators Table-level constraint syntax:

The slide gives the syntax for defining constraints when


CREATE TABLE Statement creating a table. You can create constraints at either the
column level or table level. Constraints defined at the
You must have:
column level are included when the column is defined.
- The CREATE TABLE privilege
Table-level constraints are defined at the end of the table
- A storage area
definition and must refer to the column or columns on
which the constraint pertains in a set of parentheses. It is
You specify: mainly the syntax that differentiates the two; otherwise,
- The table name functionally, a column-level constraint is the same as a
- The column name, column data type, and table-level constraint.
column size NOT NULL constraints must be defined at the column
level.
Constraints that apply to more than one column must be
defined at the table level.
In the syntax:

schema Is the same as the owners


name
You create tables to store data by executing the SQL table Is the name of the table
CREATE TABLE statement. This statement is one of the DEFAULT expr Specifies a default value to
DDL statements that are a subset of the SQL statements be used if a value is omitted
used to create, modify, or remove Oracle Database in the INSERT statement
structures. These statements have an immediate effect on column Is the name of the column
the database and they also record information in the data
datatype Is the columns data type
dictionary.
and length
To create a table, a user must have the CREATE TABLE
column_constraint Is an integrity constraint as
privilege and a storage area in which to create objects. The
part of the column definition
database administrator (DBA) uses data control language
table_constraint Is an integrity constraint as
(DCL) statements to grant privileges to users.
In the syntax: part of the table definition

schema Is the same as the owners Example of a column-level constraint:


name
table Is the name of the table
DEFAULT expr Specifies a default value if a
value is omitted in the Example of a table-level constraint:
INSERT statement
column Is the name of the column
datatype Is the columns data type
and length
Constraints are usually created at the same time as the
table. Constraints can be added to a table after its creation
and also be temporarily disabled.
Defining Constraints Both examples in the slide create a primary key constraint
Syntax: on the EMPLOYEE_ID column of the EMPLOYEES table.
1. The first example uses the column-level syntax to
define the constraint.
2. The second example uses the table-level syntax to
define the constraint.
More details about the primary key constraint are provided
later in this lesson. Data Types

Including Constraints
Data Type Description
Constraints enforce rules at the table level. VARCHAR2(size) Variable-length character
Constraints prevent the deletion of a table if there data
are dependencies. CHAR(size) Fixed-length character data
The following constraint types are valid: NUMBER(p,s) Variable-length numeric
- NOT NULL
data
- UNIQUE
- PRIMARY KEY DATE Date and time values
- FOREIGN KEY LONG Variable-length character
- CHECK data (up to 2 GB)
CLOB Character data (up to 4 GB)
RAW and LONG RAW Raw binary data
BLOB Binary data (up to 4 GB)
BFILE Binary data stored in an
external file (up to 4 GB)
Constraints ROWID A base-64 number system
The Oracle server uses constraints to prevent invalid data representing the unique
entry into tables. address of a row in its table
You can use constraints to do the following:
Enforce rules on the data in a table whenever a When you identify a column for a table, you need to
row is inserted, updated, or deleted from that provide a data type for the column. There are several data
table. The constraint must be satisfied for the types available:
operation to succeed.
Prevent the deletion of a table if there are Data Type Description
dependencies from other tables. VARCHAR2(size) Variable-length character
Provide rules for Oracle tools, such as Oracle data (A maximum size must
Developer. be specified: minimum size
is 1; maximum size is
Data Integrity Constraints 4,000.)
CHAR [(size)] Fixed-length character data
NOT NULL Specifies that the column of length size bytes (Default
cannot contain a null value and minimum size is 1;
UNIQUE Specifies a column or maximum size is 2,000.)
combination of columns NUMBER [(p,s)] Number having precision p
whose values must be and scale s (Precision is the
unique for all rows in the total number of decimal
table digits and scale is the
PRIMARY KEY Uniquely identifies each number of digits to the right
row of the table of the decimal point;
FOREIGN KEY Establishes and enforces a precision can range from 1
referential integrity between to 38, and scale can range
the column and a column of from -84 to 127.)
the referenced table such DATE Date and time values to the
that values in one table nearest second between
match values in another January 1, 4712 B.C., and
table. December 31, 9999 A.D.
CHECK Specifies a condition that LONG Variable-length character
must be true data (up to 2 GB)
CLOB Character data (up to 4 GB)
RAW(size) Raw binary data of length Guidelines
size (A maximum size must All the data is deleted from the table.
be specified: maximum size Any views and synonyms remain, but are invalid.
is 2,000.) Any pending transactions are committed.
LONG RAW Raw binary data of variable Only the creator of the table or a user with the
length (up to 2 GB) DROP ANY TABLE privilege can remove a
BLOB Binary data (up to 4 GB) table.
BFILE Binary data stored in an
external file (up to 4 GB)
ROWID A base-64 number system Summary
representing the unique In this lesson, you should have learned how to:
address of a row in its table
Describe the syntax of basic SQL-92/1999
commands, including:
- SELECT
Guidelines - INSERT
A LONG column is not copied when a table is - UPDATE
created using a subquery. - DELETE
A LONG column cannot be included in a GROUP - CREATE TABLE
BY or an ORDER BY clause. - DROP TABLE
Only one LONG column can be used per table. Define basic SQL-92/1999 data types
No constraints can be defined on a LONG column.
You might want to use a CLOB column rather
than a LONG column.

Dropping a Table
Moves a table to the recycle bin
Removes the table and all its data entirely if the
PURGE clause is specified
Invalidates dependent objects and removes object
privileges on the table

The DROP TABLE statement moves a table to the recycle


bin or removes the table and all its data from the database
entirely. Unless you specify the PURGE clause, the DROP
TABLE statement does not result in space being released
back to the tablespace for use by other objects, and the
space continues to count toward the users space quota.
Dropping a table invalidates the dependent objects and
removes object privileges on the table.
When you drop a table, the database loses all the data in
the table and all the indexes associated with it.

Syntax
DROP TABLE table [PURGE]
In the syntax, table is the name of the table.