D67238GC20 sg1
D67238GC20 sg1
D67238GC20 sg1
D67238GC20
Edition 2.0
November 2011
D74996
Java SE 7 Programming
Authors
Michael Williams
Tom McGinn
Disclaimer
Technical Contributors
and Reviewers
Lee Klement
Steve Watts
Brian Earl
Vasily Strelnikov
Andy Smith
Nancy K.A.N
Chris Lamb
Todd Lowry
Ionut Radu
Joe Darcy
Brian Goetz
Alan Bateman
David Holmes
Editors
Richard Wallis
Daniel Milne
Vijayalakshmi Narasimhan
Graphic Designer
James Hans
Publishers
Syed Imtiaz Ali
Sumesh Koshy
Matt Heimer
Introduction
Course Goals 1-2
Course Objectives 1-3
Audience 1-5
Prerequisites 1-6
Class Introductions 1-7
Course Environment 1-8
Java Programs Are Platform-Independent 1-9
Java Technology Product Groups 1-10
Java SE Platform Versions 1-11
Downloading and Installing the JDK 1-12
Java in Server Environments 1-13
The Java Community 1-14
The Java Community Process (JCP) 1-15
OpenJDK 1-16
Oracle Java SE Support 1-17
Additional Resources 1-18
Summary 1-19
iii
Contents
Summary 3-22
Quiz 3-23
Practice 3-1 Overview: Creating Subclasses 3-27
(Optional) Practice 3-2 Overview: Adding a Staff to a Manager 3-28
Quiz 6-15
Design Patterns and Interfaces 6-16
DAO Pattern 6-17
Before the DAO Pattern 6-18
After the DAO Pattern 6-19
The Need for the Factory Pattern 6-20
Using the Factory Pattern 6-21
The Factory 6-22
The DAO and Factory Together 6-23
Quiz 6-24
Code Reuse 6-25
Design Difficulties 6-26
Composition 6-27
Composition Implementation 6-28
Polymorphism and Composition 6-29
Quiz 6-31
Summary 6-32
Practice 6-1 Overview: Implementing an Interface 6-33
Practice 6-2 Overview: Applying the DAO Pattern 6-34
(Optional) Practice 6-3 Overview: Implementing Composition 6-35
String Processing
Objectives 8-2
Command-Line Arguments 8-3
Properties 8-5
Loading and Using a Properties File 8-6
Loading Properties from the Command Line 8-7
PrintWriter and the Console 8-8
printf format 8-9
Quiz 8-10
String Processing 8-11
StringBuilder and StringBuffer 8-12
StringBuilder: Example 8-13
Sample String Methods 8-14
Using the split() Method 8-15
Parsing with StringTokenizer 8-16
Scanner 8-17
Regular Expressions 8-18
Pattern and Matcher 8-19
Character Classes 8-20
Character Class: Examples 8-21
Character Class Code: Examples 8-22
Predefined Character Classes 8-23
Predefined Character Class: Examples 8-24
Quantifiers 8-25
viii
Summary 9-30
Practice 9-1 Overview: Catching Exceptions 9-31
Practice 9-2 Overview: Extending Exception 9-32
xi
12 Threading
Objectives 12-2
Task Scheduling 12-3
Why Threading Matters 12-4
The Thread Class 12-5
Extending Thread 12-6
Starting a Thread 12-7
Implementing Runnable 12-8
Executing Runnable Instances 12-9
A Runnable with Shared Data 12-10
One Runnable: Multiple Threads 12-11
Quiz 12-12
Problems with Shared Data 12-13
Nonshared Data 12-14
Quiz 12-15
Atomic Operations 12-16
Out-of-Order Execution 12-17
Quiz 12-18
The volatile Keyword 12-19
Stopping a Thread 12-20
The synchronized Keyword 12-22
synchronized Methods 12-23
synchronized Blocks 12-24
Object Monitor Locking 12-25
Detecting Interruption 12-26
Interrupting a Thread 12-27
Thread.sleep() 12-28
Quiz 12-29
Additional Thread Methods 12-30
Methods to Avoid 12-31
Deadlock 12-32
Summary 12-33
Practice 12-1 Overview: Synchronizing Access to Shared Data 12-34
Practice 12-2 Overview: Implementing a Multithreaded Program 12-35
xii
xiii
13 Concurrency
Objectives 13-2
The java.util.concurrent Package 13-3
The java.util.concurrent.atomic Package 13-4
The java.util.concurrent.locks Package 13-5
java.util.concurrent.locks 13-6
Thread-Safe Collections 13-7
Quiz 13-8
Synchronizers 13-9
java.util.concurrent.CyclicBarrier 13-10
High-Level Threading Alternatives 13-11
java.util.concurrent.ExecutorService 13-12
java.util.concurrent.Callable 13-13
java.util.concurrent.Future 13-14
Shutting Down an ExecutorService 13-15
Quiz 13-16
Concurrent I/O 13-17
A Single-Threaded Network Client 13-18
A Multithreaded Network Client (Part 1) 13-19
A Multithreaded Network Client (Part 2) 13-20
A Multithreaded Network Client (Part 3) 13-21
A Multithreaded Network Client (Part 4) 13-22
A Multithreaded Network Client (Part 5) 13-23
Parallelism 13-24
Without Parallelism 13-25
Naive Parallelism 13-26
The Need for the Fork-Join Framework 13-27
Work-Stealing 13-28
A Single-Threaded Example 13-29
java.util.concurrent.ForkJoinTask<V> 13-30
RecursiveTask Example 13-31
compute Structure 13-32
compute Example (Below Threshold) 13-33
compute Example (Above Threshold) 13-34
ForkJoinPool Example 13-35
Fork-Join Framework Recommendations 13-36
Quiz 13-37
Summary 13-38
(Optional) Practice 13-1 Overview: Using the java.util.concurrent Package 13-39
(Optional) Practice 13-2 Overview: Using the Fork-Join Framework 13-40
15 Localization
Objectives 15-2
Why Localize? 15-3
A Sample Application 15-4
Locale 15-5
Resource Bundle 15-6
xiv
A SQL Primer
Objectives A-2
Using SQL to Query Your Database A-3
SQL Statements A-4
Basic SELECT Statement A-5
Limiting the Rows That Are Selected A-7
Using the ORDER BY Clause A-8
INSERT Statement Syntax A-9
UPDATE Statement Syntax A-10
DELETE Statement A-11
CREATE TABLE Statement A-12
Defining Constraints A-13
Including Constraints A-16
Data Types A-18
Dropping a Table A-20
Summary A-21
xv
Introduction
Course Goals
This course covers the core APIs that you use to design
object-oriented applications with Java. This course also
covers writing database programs with JDBC.
Use this course to further develop your skills with the Java
language and prepare for the Oracle Certified
Professional, Java SE 7 Programmer Exam.
Java SE 7 Programming 1 - 2
Java SE 7 Programming 1 - 3
Course Objectives
(continued)
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
Java SE 7 Programming 1 - 4
Course Objectives
Java SE 7 Programming 1 - 5
Audience
Prerequisites
Java SE 7 Programming 1 - 6
To
Java SE 7 Programming 1 - 7
Class Introductions
Course Environment
Classroom PC
Additional Tools
Firefox
Java DB
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 offering.
Java DB: Java DB is Oracle's supported distribution of the open-source Apache Derby
100% Java technology database. It is fully transactional, secure, easy-to-use,
standards-based SQL, JDBC API, and Java EE yet small, only 2.5 MB.
Java SE 7 Programming 1 - 8
Core Apps
JDK 7
NetBeans 7.0.1
Platform-Independent Programs
Java technology applications are written in the Java programming language and compiled to
Java bytecode. Bytecode is executed on the Java platform. The software 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 source code to Java
bytecode.
Java SE 7 Programming 1 - 9
Java SE 7 Programming 1 - 10
Year
Developer
Version (JDK)
Platform
1996
1.0
1997
1.1
1998
1.2
2000
1.3
2002
1.4
2004
1.5
2006
1.6
2011
1.7
Java SE 7 Programming 1 - 11
1.
2.
3.
4.
5.
Go to http://www.oracle.com/technetwork/java/javase/downloads/index.html.
Choose the Java Platform, Standard Edition (Java SE) link.
Download the version that is appropriate for your operation system.
Follow the installation instructions.
Set your PATH.
Java SE 7 Programming 1 - 12
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 implementing enterprise applications. Java SE is only the starting point
in your path to becoming a Java developer. Depending on the needs of your organization, you
may be required to develop applications that run inside Java EE application servers or other
types of Java middleware.
Often, you will also need to manipulate information stored inside relational databases such as
MySQL or Oracle Database. This course introduces you to the fundamentals of database
programming.
Java SE 7 Programming 1 - 13
Java SE 7 Programming 1 - 14
Mobile &
Embedded
JCP.next
The JCP produces the JSRs that outline the standards of the Java platform. The behavior of
the JCP itself is also defined and improved through the JSR process. The JCP is evolving and
its improvements are defined in JSR-348. JSR-348 introduces changes in the areas of
transparency, participation, agility, and governance.
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.
Participation: Individuals and Java User Groups are encouraged to become active in
the JCP.
Agility: Slow-moving JSRs are now actively discouraged.
Governance: The SE and ME expert groups are merging into a single body.
Java SE 7 Programming 1 - 15
Java SE 7 Programming 1 - 16
OpenJDK
Still Free
Java (Oracle JDK) is freely available at no cost. Oracle offers advanced commercial solutions
at cost. The previously offered Java for Business program has been replaced by Oracle
Java SE Support, which provides access to Oracle Premier Support and the Oracle Java SE
Advanced and Oracle Java SE Suite binaries. For more information, visit
http://www.oracle.com/us/technologies/java/java-se-suite-394230.html.
Java SE 7 Programming 1 - 17
Topic
Website
http://education.oracle.com
Product Documentation
http://www.oracle.com/technology/documentation
Product Downloads
http://www.oracle.com/technology/software
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.com
http://www.oracle.com/technetwork/java/index.html
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.
Java SE 7 Programming 1 - 18
Additional Resources
Java SE 7 Programming 1 - 19
Summary
Objectives
Java SE 7 Programming 2 - 2
Java SE 7 Programming 2 - 3
Class Structure
package <package_name>;
import <other_packages>;
<constructor method(s)>;
<other methods>;
}
A Java class is described in a text file with a .java extension. In the example shown, the
Java keywords are highlighted in bold.
The package keyword defines where this class 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.
The import keyword defines other classes or groups of classes that you are using in
your class. 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 class. The name of the class and the file
name must match when the class is declared public (which is a good practice).
However, the keyword public in front of the class keyword is a modifier and is not
required.
Variables, or the data associated with programs (such as integers, strings, arrays, and
references to other objects), are called instance fields (often shortened to fields).
Constructors are functions called during the creation (instantiation) of an object (a
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 methods.
Java SE 7 Programming 2 - 4
A Simple Class
A simple Java class with a main method:
public class Simple{
}
}
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.
Java SE 7 Programming 2 - 5
Code Blocks
Example:
public class SayHello {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
Java fields (variables) and methods have a class scope defined by the opening left curly
brace and ending at the closing right curly brace.
Class scope allows any method in the class to call or invoke any other method in the class.
Class scope also allows any method to access any field in the class.
Code blocks are always defined using braces {}. A block is executed by executing each of
the statements defined within the block in order from first to last (left to right).
The Java compiler ignores all white space. Line indentation is not required but makes code
much more readable. In this course, the line indentation is four spaces, which is the default
line indentation used by the NetBeans IDE.
Java SE 7 Programming 2 - 6
{ }
Integer
Floating
Point
Character
True
False
byte
short
int
long
float
double
char
boolean
1, 2, 3, 42
07
0xff
3.0F
.3337F
4.022E23
'a'
'\u0061'
'\n'
true
false
0.0f
'\u0000'
false
Integer
Java provides four different integer types to accommodate different size numbers. All the
numeric types are signed, which means that they can hold positive or negative numbers.
The integer types have the following ranges:
int range is 2,147,483,648 to +2,147,483,647. The most common integer type is int.
Number of bits = 32.
Java SE 7 Programming 2 - 7
Character
The char type is used for individual characters, as opposed to a string of characters (which is
implemented as a String object). Java supports Unicode, an international standard for
representing a character in any written language in the world in a single 16-bit value. The first
256 characters coincide with the ISO Latin 1 character set, part of which is ASCII.
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.
Java SE 7 Programming 2 - 8
Boolean
The boolean type can hold either true or false.
Note: true and false may appear to be keywords, but they are technically boolean literals.
Prior to an F or L suffix
Java SE 7 Programming 2 - 9
Binary literals are Java int values. Java byte and short values require a cast to prevent a
precision loss warning from the compiler.
Java SE 7 Programming 2 - 10
Operators
Arithmetic operators
+
*
/
%
Unary operators
+ Unary plus operator; indicates positive
Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean
Copyright 2011, Oracle and/or its affiliates. All rights reserved.
Because numbers have been introduced, the slide shows a list of common operators. Most
are common to any programming language, and a description of each is provided in the slide.
The binary and bitwise operators have been omitted for brevity. For details about those
operators, refer to the Java Tutorial:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
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 Programming 2 - 11
The code in the slide demonstrates how text characters are represented in Java. Single
characters can be represented with the char type. However, Java also includes a String
type for representing multiple characters. Strings 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:
Output: HelloWorld a
Caution: Strings should always be initialized using the 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.
Java SE 7 Programming 2 - 12
Strings
Java SE 7 Programming 2 - 13
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
Java SE 7 Programming 2 - 14
if else
Logical Operators
Equality and relational operators
==
!=
>
>=
<
<=
Equal to
Not equal to
Greater than
Greater than or equal to
Less than
Less than or equal to
Conditional operators
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for if-then-else statement)
The slide shows a summary of the logic and conditional operators in Java.
Java SE 7 Programming 2 - 15
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
Name: Red Shirt
Name: Black Shirt
Number: 100
Number: 200
Number: 300
Note: Arrays are also objects by default. All arrays support the methods of the class Object.
You can always obtain the size of an array using its length field.
Java SE 7 Programming 2 - 16
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 is met, the loop exits. Here is the sample
output for this program.
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
Java SE 7 Programming 2 - 17
for Loop
The while loop performs a test and continues if the expression evaluates to true. The
while loop, shown here, iterates through an array using a counter. Here is the output from
the code in the slide:
Number: 100
Number: 200
Number: 300
Note: There is also a do-while loop, where the test after the expression has run at least
once:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count <= 11);
}
}
Java SE 7 Programming 2 - 18
while Loop
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 SE 7 Programming 2 - 19
Class names should be nouns in mixed case, with the first letter uppercase and the first
letter of each internal word capitalized. This is approach is termed "upper camel case."
Methods should be verbs in mixed case, with the first letter lowercase and the first letter
of each internal word capitalized. This is termed "lower camel case."
Variable names should be short but meaningful. 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.
For the complete Code Conventions for the Java Programming Language document, go to
http://www.oracle.com/technetwork/java/codeconv-138413.html.
Java SE 7 Programming 2 - 20
1 package com.example.domain;
2 public class Employee { class declaration
3
public int empId;
4
public String name;
fields
5
public String ssn;
6
public double salary;
7
8
public Employee () { a constructor
9
}
10
11
public int getEmpId () {
a method
12
return empId;
13
}
14 }
Copyright 2011, Oracle and/or its affiliates. All rights reserved.
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 method in this class creates an instance of an object called Employee.
A constructor method is unique in Java because the return type of the method is an instance
of the class, so constructors always have the same name as the class and do not declare a
return type. You can declare more than one constructor, as you will see in the lesson titled
Java Class Design.
Java SE 7 Programming 2 - 21
1 package com.example.domain;
2 public class Employee {
3
public int empId;
4
// other fields...
5
public void setEmpId(int empId) {
6
this.empId = empId;
Often a pair of methods
7
}
to set and get the
current field value.
8
public int getEmpId() {
9
return empId;
10
}
11
// getter/setter methods for other fields...
12 }
Java SE 7 Programming 2 - 22
Java SE 7 Programming 2 - 23
Constructors
Java SE 7 Programming 2 - 24
package Statement
The package keyword is used in Java to group classes
together. A package is implemented as a folder and, like a
folder, provides a namespace to a class.
folder view
com.example.domain
Employee
Manager
+com
|_+example
|_+domain
|_+Employee.java
|_+Manager.java
Packages
In Java, a package is a group of (class) types. There can be only one package declaration
for a class.
Packages are more than just a convenience. Packages create a namespace, a logical
collection of things, like a directory hierarchy.
It is a good practice to always use a package declaration. The package declaration is
always at the top of the class.
Java SE 7 Programming 2 - 25
namespace view
import Statements
The import keyword is used to identify classes you want to
reference in your class.
The import statement provides a convenient way to
identify classes that you want to reference in your class.
import java.util.*;
import java.util.Date;
import java.util.Calendar;
Imports
You could refer to a class using its fully qualified namespace in your applications, as in the
following example:
java.util.Date date = new java.util.Date();
But that would quickly lead to a lot of typing! Instead, Java provides the import statement to
allow you to declare that you want to reference a class in another package.
Note: It is a good practice to use the specific, fully qualified package and class name to avoid
confusion when 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.
Java SE 7 Programming 2 - 26
import java.util.Date;
More on import
package com.example.domain;
import com.example.domain.Manager; // unused import
Details about this package and its classes are covered later in the course.
Java SE 7 Programming 2 - 27
Java Is Pass-By-Value
The Java language (unlike C++) uses pass-by-value for all
parameter passing.
To visualize this with primitives, consider the following:
y
copy the value of x
The Java language uses pass-by-value for all assignment operations. This means that the
argument on the right side of the equal sign is evaluated, and the value of the argument is
assigned to the left side of the equal sign.
For Java primitives, this is straightforward. Java does not pass a reference to a primitive (such
as an integer), but rather a copy of the value.
Java SE 7 Programming 2 - 28
int x = 3;
int y = x;
y = x;
memory address = 42
Employee
object
42
For Java objects, the value of an object reference is the memory pointer to the instance of the
Employee object 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 the reference.
Note: An object is a class instance or an array. The reference values (references) are
pointers to these objects, and a special null reference, which refers to no object.
Java SE 7 Programming 2 - 29
42
Employee
object
99
Employee
object
Whenever a new value is created, such as the e = new Employee(); statement in the
foo method, a new object is created and the value of the parameter is changed to the new
value.
The value of x is simply copied into the parameter for the method, so x remains unchanged
during and after the execution of the foo method.
What is the value returned from x.getSalary(); after the call foo(x);?
As illustrated, the value of the reference x is unchanged, and the value returned would be the
same as before the call. This is because you used the new keyword to construct a new object
and assigned that object instance to e. Whatever value e had before (the reference to x) is
now overwritten.
The setSalary method is operating on the reference e, not on the object reference passed
in to the method.
If you were to remove the statement, e = new Employee();, then the e.setSalary
method would be operating on the x reference, and the employee represented by the variable
x would be making a lot of money!
Note: The memory locations 42 and 99 are simply for illustrative purposes!
Java SE 7 Programming 2 - 30
CLASSPATH
The CLASSPATH variable is used by both the Java compiler and the Java interpreter
(runtime).
The classpath can include:
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 putting classpath information in the command window or even in the
Java command, rather than hard-coding it in the environment.
Java SE 7 Programming 2 - 31
To run the application, you use the interpreter and the fully
qualified classname:
Example
Consider the following simple class in a file named HelloWorld.java in the
D:\test\com\example directory:
package com.example;
public class HelloWorld {
public static void main (String [] args) {
if (args.length < 1) {
System.out.println("Hello World!");
} else {
System.out.println("Hello " + args[0] + "!");
}
}
}
Java SE 7 Programming 2 - 32
Typically, the use of the class loader is completely invisible to you. You can see the results of
the class loader by using the -verbose flag when you run your application. For example:
java verbose classpath D:\test com.example.HelloWorld
[Loaded java.lang.Object from shared objects file]
[Loaded java.io.Serializable from shared objects file]
[Loaded java.lang.Comparable from shared objects file]
[Loaded java.lang.CharSequence from shared objects file]
[Loaded java.lang.String from shared objects file]
[Loaded java.lang.reflect.GenericDeclaration from shared objects
file]
[Loaded java.lang.reflect.Type from shared objects file]
[Loaded java.lang.reflect.AnnotatedElement from shared objects file]
[Loaded java.lang.Class from shared objects file]
[Loaded java.lang.Cloneable from shared objects file]
[Loaded java.lang.ClassLoader from shared objects file]
... and many more
Java SE 7 Programming 2 - 33
Garbage Collection
Java's garbage collection scheme can be tuned depending on the type of application you are
creating. For more information, consider taking the Oracle University course Java
Performance Tuning and Optimization (D69518GC10).
Java SE 7 Programming 2 - 34
Summary
In this lesson, you should have learned how to:
Create simple Java classes
Java SE 7 Programming 2 - 35
Quiz
package com.oracle.test;
public class BrokenClass {
public boolean valid = "false";
public String s = new String ("A new string");
public int i = 40_000.00;
public BrokenClass() { }
}
a.
b.
c.
d.
e.
f.
Java SE 7 Programming 2 - 36
Quiz
a. Fred
b. Bob
c. null
d. empty String
Copyright 2011, Oracle and/or its affiliates. All rights reserved.
Java SE 7 Programming 2 - 37
Quiz
a.
b.
c.
d.
100
150.33
166.67
200
Java SE 7 Programming 2 - 38
Java SE 7 Programming 2 - 39
Java SE 7 Programming 3 - 2
Objectives
The term encapsulation is defined by the Java Technology Reference Glossary as follows:
The localization of knowledge within a module. Because objects encapsulate data and
implementation, the user of an object can view the object as a black box that provides
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 continue
to use it without being rewritten.
An analogy for encapsulation is the steering wheel of a car. When you drive a car, whether it
is your car, a friend's car, or a rental car, you probably never worry about how 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.
Java SE 7 Programming 3 - 3
Encapsulation
Encapsulation: Example
Employee ID
Name
Social Security Number
Salary
Set Name
Raise Salary
A Simple Model
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?
Employee ID: You can use this as a unique identifier for the employee.
Name: Humanizing an employee is always a good idea!
Social Security Number: For United States employees only. You may want some other
identification for non-U.S. employees.
Salary: How much the employee makes is always good to record.
What operations might you allow on the employee object?
Change Name: If the employee gets married or divorced, there could be a name
change.
Raise Salary: Increases based on merit
After an employee object is created, you probably do not want to allow changes to the
Employee ID or Social Security fields. Therefore, you need a way to create an employee
without alterations except through the allowed methods.
Java SE 7 Programming 3 - 4
In this example, the fields custID, name, and amount are now marked private, making
them invisible outside of the methods in the class itself.
Java SE 7 Programming 3 - 5
Java SE 7 Programming 3 - 6
Revisiting Employee
The Employee class currently uses public access for all of
its fields. To encapsulate the data, make the fields private.
Encapsulation step 1:
Hide the data (fields).
Java SE 7 Programming 3 - 7
package come.example.model;
public class Employee {
private int empId;
private String name;
private String ssn;
private double salary;
//... constructor and methods
}
Java SE 7 Programming 3 - 8
1 package com.example.domain;
2 public class Employee {
3
// private fields ...
4
public Employee () {
5
}
6
// Remove all of the other setters
7
public void setName(String newName) {
Encapsulation step 2:
8
if (newName != null) {
These method names
9
this.name = newName;
make sense in the
context of an
10
}
Employee.
11
}
12
13
public void raiseSalary(double increase) {
14
this.salary += increase;
15
}
16 }
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 employee's salary.
To refine the Employee class, the first step is to remove 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.
Java SE 7 Programming 3 - 9
1 package com.example.domain;
Encapsulation step 3:
2 public class Employee {
Remove the default
constructor; implement
3
// private fields ...
a constructor to set
4
// Create an employee object
the value of all fields.
5
public Employee (int empId, String name,
6
String ssn, double salary) {
7
this.empId = empId;
8
this.name = name;
9
this.ssn = ssn;
10
this.salary = salary;
11
}
12
13
public void setName(String newName) { ... }
14
15
public void raiseSalary(double increase) { ... }
16 }
Java SE 7 Programming 3 - 10
Creating Subclasses
1 package com.example.domain;
2 public class Manager {
3
private int empId;
4
private String name;
5
private String ssn;
6
private double salary;
7
private String deptName;
8
public Manager () { }
9
// access and mutator methods...
10 }
Java SE 7 Programming 3 - 11
Subclassing
In an object-oriented language like Java, subclassing is used to
define a new class in terms of an existing one.
Java SE 7 Programming 3 - 12
superclass: Employee
("parent" class)
1 package com.example.domain;
2 public class Manager extends Employee {
3
private String deptName;
4
public Manager (int empId, String name,
5
String ssn, double salary, String dept) {
6
super (empId, name, ssn, salary);
7
this.deptName = dept;
The super keyword is used to
call the constructor of the parent
8
}
class. It must be the first
9
statement in the constructor.
10
public String getDeptName () {
11
return deptName;
12
}
13
// Manager also gets all of Employee's public methods!
14 }
Java SE 7 Programming 3 - 13
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.
Java SE 7 Programming 3 - 14
Using super
To construct an instance of a subclass, it is often easiest to call
the constructor of the parent class.
In its constructor, Manager calls the constructor of
Employee.
The Manager class declares its own constructor and calls the constructor of the parent class
using the super keyword.
Note: The super call of the parent's constructor must appear first in the constructor.
The super keyword can also be used to explicitly call the methods of the parent class or
access fields.
Java SE 7 Programming 3 - 15
mgr.raiseSalary (10000.00);
Even though the Manager.java file does not contain all of the methods from the
Employee.java class (explicitly), they are included in the definition of the object. Thus, after
you create an instance of a Manager object, you can use the methods declared in
Employee.
You can also call methods that are specific to the Manager class as well.
Java SE 7 Programming 3 - 16
What Is Polymorphism?
The word polymorphism, strictly defined, means many forms.
Employee emp = new Manager();
Java SE 7 Programming 3 - 17
Overloading Methods
Your design may call for several methods in the same class
with the same name but with different arguments.
You might want to design methods with the same intent (method name), like print, to print
out several different types. You could design a method for each type:
printInt(int i)
printFloat(float f)
printString(String s)
But this would be tedious and not very object-oriented. Instead, you can create a reusable
method name and just change the argument list. This process is called overloading.
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 argument list that
differ only in return type are not allowed.
Java SE 7 Programming 3 - 18
Statistics
float avg1
float avg2
float avg3
Java provides a convenient syntax for collapsing these three methods into just one and
providing for any number of arguments.
Java SE 7 Programming 3 - 19
sum += x;
result = (float) sum / nums.length;
}
return (result);
}
}
Java SE 7 Programming 3 - 20
Single Inheritance
Although Java does not permit more than one class to a subclass, the language does provide
features that enable multiple classes to implement the features of other classes. You will see
this in the lesson on inheritance.
Single inheritance does not prevent continued refinement and specialization of classes as
shown above.
In the diagram shown in the slide, a manager can have employees, and a director has a
budget and can approve expenses.
Java SE 7 Programming 3 - 21
Java SE 7 Programming 3 - 22
Summary
Quiz
Given the diagram in the slide titled Single Inheritance and
the following Java statements, which statement does not
compile?
a. e.addEmployee (a);
b. m.addEmployee(a);
c. m.approveExpense(100000.00);
d. All of them fail to compile.
Java SE 7 Programming 3 - 23
Quiz
Java SE 7 Programming 3 - 24
Quiz
Which of the following declarations demonstrates the
application of good Java naming conventions?
Java SE 7 Programming 3 - 25
Quiz
a.
b.
c.
d.
Java SE 7 Programming 3 - 26
Java SE 7 Programming 3 - 27
Java SE 7 Programming 3 - 28
Java SE 7 Programming 4 - 2
Objectives
Same
Package
private
Yes
default
Yes
Yes
protected
Yes
Yes
public
Yes
Yes
Subclass in
Another
Package
Yes
Universe
Yes
Yes
The access modifier keywords shown in this table are private, protected, and public.
When a keyword is absent, the default access modifier is applied.
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 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 protected feature. As a result, protected fields or methods are actually
more accessible than those marked with default access control. You should use protected
access when it is appropriate for a classs subclass, but not unrelated classes.
Java SE 7 Programming 4 - 3
Modifier
(keyword)
1
2
3
4
5
6
7
8
9
package test;
import demo.Foo;
public class Bar extends Foo {
private int sum = 10;
public void reportSum () {
sum += result;
sum += other;
}
}
subclass-friendly declaration
compiler error
In this example, there are two classes in two packages. Class Foo is in the package demo,
and declares a data field called result with a protected access modifier.
In the class Bar, which extends Foo, there is a method, 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
subclasseseven 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 project.
Java SE 7 Programming 4 - 4
1 package demo;
2 public class Foo {
3
protected int result = 20;
4
int other = 25;
5 }
1
2
3
4
5
6
7
8
9
package test;
import demo.Foo2;
public class Bar2 extends Foo2 {
private int sum = 10;
private int result = 30;
public void reportSum() {
sum += result;
}
}
In this example, the class Foo2 declares the field result. However, the class Bar2 declares
its own field result. The consequence is that the field result from class Foo2 is
shadowed by the field result in class Bar2. What is sum in this example? sum is now 40
(10 + 30). Modern IDEs (such as NetBeans) detect shadowing and produce a warning.
Methods with the same name are not shadowed but are overridden. You learn about
overriding later in this lesson.
Java SE 7 Programming 4 - 5
1 package demo;
2 public class Foo2 {
3
protected int result = 20;
4 }
1 package demo;
2 public class Foo3 {
3
private int result = 20;
4
protected int getResult() { result = value; }
5 }
1
2
3
4
5
6
7
8
package test;
import demo.Foo3;
public class Bar3 extends Foo3 {
private int sum = 10;
public void reportSum() {
sum += getResult();
}
}
Copyright 2011, Oracle and/or its affiliates. All rights reserved.
A slightly modified version of the example using the protected keyword is shown in the
slide. If the idea is to limit access of the field result to classes within the package and the
subclasses (package-protected), you should make the access explicit by defining a method
purposefully written for package and subclass-level access.
Java SE 7 Programming 4 - 6
Overriding Methods
Although the Employee class has getters to return values for a print statement, it might be
nice to have a utility method to get specific details about the employee. Consider a method
added to the Employee class to print details about the Employee object.
In addition to adding fields or methods to a subclass, you can also modify or change the
existing behavior of a method of the parent (superclass).
You may want to specialize this method to describe a Manager object.
Java SE 7 Programming 4 - 7
Overriding Methods
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 getDetails method of the parent
class.
Note: If, for example, a class declares two public methods with the same name, and a
subclass overrides one of them, the subclass still inherits the other method.
Java SE 7 Programming 4 - 8
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?
Answer: Recall that methods are inherited from the parent class. So, at run time, the
getDetails method of the parent class (Employee) is executed.
Java SE 7 Programming 4 - 9
Java SE 7 Programming 4 - 10
To override a method, the name and the order of arguments must be identical.
By changing the access of the Manager getDetails method to private, only that class
can execute the method. However, language semantics for the execution of e.getDetails
dictate that the Manager getDetails method is executed. The result is a runtime error.
What happens if you make the Employee method getDetails private and the Manager
method public?
Answer: Because the compiler does type checking, the compiler complains that you are
attempting to access a private method in Employee.
Java SE 7 Programming 4 - 11
Applying Polymorphism
Design Problem
What is the problem in the example in the slide? Each method performs the calculation
based on the type of employee passed in, and returns the number of shares.
Consider what happens if you add two or three more employee types. You would need to add
three additional methods, and possibly replicate code depending upon the business logic
required to compute shares.
Clearly, this is not a good way to treat this problem. Although the code will work, this is not
easy to read and is likely to create much duplicate code.
Java SE 7 Programming 4 - 12
Applying Polymorphism
A good practice is to pass parameters and write methods that
use the most generic form of your object as possible.
Java SE 7 Programming 4 - 13
Java SE 7 Programming 4 - 14
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 these in the next slide.
Java SE 7 Programming 4 - 15
Casting Rules
Upward casts are always permitted and do not require a cast
operator.
Employee e = m; // OK
Employee e = d; // OK
Manager m = d; // OK
Java SE 7 Programming 4 - 16
Casting Rules
For downward casts, the compiler must be satisfied that the
cast is at least possible.
Manager m = (Manager)e;
// Would also work if
// e was a Director obj
Director d = (Director)m;
// fails at run time
Downward Casts
With a downward cast, the compiler simply determines if the cast is possible; if the cast down
is to a subclass, then it 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 subclass.
The cast of the variable e to a Manager reference m satisfies the compiler, because Manager
and Employee are in the same class hierarchy, so the cast will possibly 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.
The cast of the variable m to a Director instance satisfies the compiler, but because m is
actually a Manager instance, this cast fails at run time with a ClassCastException.
Finally, any cast will fail that is outside the class hierarchy, such as the cast from a Manager
instance to an Engineer. A Manager and an Engineer are both employees, but a
Manager is not an Engineer.
Java SE 7 Programming 4 - 17
Java SE 7 Programming 4 - 18
Note: Sometimes you may want to be able to print out the name of the class that is executing
a method. The getClass() method is an Object method used to return the Class object
instance, and the getName() method provides the fully qualified name of the runtime class.
getClass().getName(); // returns the name of this class instance
These methods are in the Object class.
Java SE 7 Programming 4 - 19
Employee
Employee
x.equals
Employee
x.equals
x = new
y = x;
(y); //
z = new
(z); //
Employee (1,"Sue","111-11-1111",10.0);
true
Employee (1,"Sue","111-11-1111",10.0);
false!
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:
If x == y, return true.
For an object (like the Employee object) that contains values, this comparison is not
sufficient, particularly if we want to make sure there is one and only one employee with a
particular ID.
Java SE 7 Programming 4 - 20
This simple equals test first tests to make sure that the object passed in is not null, and then
tests to make sure that it is an instance of an Employee class (all subclasses are also
employees, so this works). Then the Object is cast to Employee, and each field in
Employee is checked for equality.
Note: For String types, you should use the equals method to test the strings character by
character for equality.
Java SE 7 Programming 4 - 21
1 // Generated by NetBeans
2 public int hashCode() {
3
int hash = 7;
4
hash = 83 * hash + this.empId;
5
hash = 83 * hash + Objects.hashCode(this.name);
6
hash = 83 * hash + Objects.hashCode(this.ssn);
7
hash = 83 * hash + (int)
(Double.doubleToLongBits(this.salary) ^
(Double.doubleToLongBits(this.salary) >>> 32));
8
return hash;
9 }
Overriding hashCode
The Java documentation for the Object class states:
"... It is generally necessary to override the hashCode method whenever this method
[equals] is overridden, so as to maintain the general contract for the hashCode method,
which states that equal objects must have equal hash codes."
The hashCode method is used in conjunction with the equals method in hash-based
collections, such as HashMap, HashSet, and Hashtable.
This method is easy to get wrong, so you need to be careful. The good news is that IDEs
such as NetBeans can 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.
Java SE 7 Programming 4 - 22
The general contract for Object states that if two objects are
considered equal (using the equals method), then integer
hashcode returned for the two objects should also be equal.
Java SE 7 Programming 4 - 23
Summary
Quiz
Suppose that you have an Account class with a withdraw()
method, and a Checking class that extends Account that
declares its own withdraw() method. What is the result of the
following code fragment?
Account acct = new Checking();
acct.withdraw(100);
Java SE 7 Programming 4 - 24
1
2
Quiz
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.
Account acct = new Checking();
if (acct instanceof Checking) { // will this block run? }
a. True
b. False
Java SE 7 Programming 4 - 25
1
2
Quiz
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?
Account acct1 = new Checking();
Account acct2 = new Savings();
Savings acct3 = (Savings)acct1;
a.
b.
c.
d.
Java SE 7 Programming 4 - 26
1
2
3
Quiz
10
11
12
13
14
15
16
package com.bank.type;
import com.bank.Account;
public class Savings extends Account {
private double interest;
Account acct = new Account();
public double getBalance (){ return (interest + balance); }
}
a.
b.
c.
d.
Java SE 7 Programming 4 - 27
1 package com.bank;
2 public class Account {
3
double balance;
4 }
Java SE 7 Programming 4 - 28
Java SE 7 Programming 5 - 2
Objectives
Class Inheritance
When designing an object-oriented solution, you should attempt to avoid code duplication.
One technique to avoid duplication is to create library methods and classes. Libraries function
as a central point to contain often reused code. Another technique to avoid code duplication is
to use class inheritance. When there is 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 base type possible. In Java,
generalization and specialization enable reuse through method inheritance 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.
Java SE 7 Programming 5 - 3
Enabling Generalization
Coding to a common base type allows for the introduction of
new subclasses with little or no modification of any code that
depends on the more generic base type.
Java SE 7 Programming 5 - 4
Method Implementations
When sibling classes have a common method, it is typically placed in a parent class. Under
some circumstances, however, the parent class's implementation will always need to be
overridden with a specialized implementation.
In these cases, inclusion of the method in a parent class has both advantages and
disadvantages. It allows the use of generic reference types, but developers can easily forget
to supply the specialized implementation in the subclasses.
Java SE 7 Programming 5 - 5
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 typically be extended
by a child class and may be used as a reference type.
Java SE 7 Programming 5 - 6
An abstract method:
Cannot have a method body
Must be declared in an abstract class
Is overridden in subclasses
Java SE 7 Programming 5 - 7
Java SE 7 Programming 5 - 8
Quiz
Java SE 7 Programming 5 - 9
Java SE 7 Programming 5 - 10
static Keyword
Static Methods
Static methods are methods that can be called even if the class
they are declared in has not been instantiated. Static methods:
Are called class methods
Are useful for APIs that are not object oriented.
Factory Methods
In place of directly invoking constructors, you will often use static methods to retrieve object
references. Unless something unexpected happens, a new object is created whenever a
constructor is called. A static factory method could maintain a cache of objects for reuse or
create new instances if the cache was depleted. A factory method may also produce an object
that subclasses the methods return type.
Example:
NumberFormat nf = NumberFormat.getInstance();
Java SE 7 Programming 5 - 11
Java SE 7 Programming 5 - 12
Java SE 7 Programming 5 - 13
double d = Math.random();
StaticUtilityClass.printMessage();
StaticUtilityClass uc = new StaticUtilityClass();
uc.printMessage(); // works but misleading
sameClassMethod();
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.
Java SE 7 Programming 5 - 14
Static Variables
Java SE 7 Programming 5 - 15
public StaticCounter() {
counter++;
}
Java SE 7 Programming 5 - 16
new StaticCounter();
new StaticCounter();
System.out.println("count: " + StaticCounter.getCount());
Static Imports
A static import statement makes the static members of a class
available under their simple name.
Given either of the following lines:
Overusing static import can negatively affect the readability of your code. Avoid adding
multiple static imports to a class.
Java SE 7 Programming 5 - 17
Quiz
Java SE 7 Programming 5 - 18
Final Methods
Performance Myths
There is little to no performance benefit when you declare a method as final. Methods should
be declared as final only to disable method overriding.
Java SE 7 Programming 5 - 19
Final Classes
A class can be declared final. Final classes may not be
extended.
public final class FinalParentClass { }
Java SE 7 Programming 5 - 20
// compile-time error
public class ChildClass extends FinalParentClass { }
Final Variables
Method parameters
Local variables
Note: Final references must always reference the same object,
but the contents of that object may be modified.
Java SE 7 Programming 5 - 21
Final Fields
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
A field that is both static and final is considered a constant. By convention, constant fields use
identifiers consisting of only uppercase letters and underscores.
Java SE 7 Programming 5 - 22
public VariableExampleClass() {
field = 100;
}
Quiz
Java SE 7 Programming 5 - 23
that equals 2.
Java SE 7 Programming 5 - 24
Typesafe Enumerations
Java SE 7 Programming 5 - 25
Enum Usage
Enum references can be statically imported.
Java SE 7 Programming 5 - 26
Complex Enums
Enums can have fields, methods, and private constructors.
Enum Constructors
You may not instantiate an enum instance with new.
Java SE 7 Programming 5 - 27
Java SE 7 Programming 5 - 28
Quiz
Design Patterns
Design patterns are:
Reusable solutions to common software development
problems
Documented in pattern catalogs
Java SE 7 Programming 5 - 29
Singleton Pattern
The singleton design pattern details a class implementation
that can be instantiated only once.
2 private SingletonClass() {}
public static SingletonClass getInstance() {
3
return instance;
}
}
Java SE 7 Programming 5 - 30
Nested Classes
Inner classes
Member classes
Local classes
Anonymous classes
Static nested classes
Java SE 7 Programming 5 - 31
Java SE 7 Programming 5 - 32
Java SE 7 Programming 5 - 33
Quiz
Java SE 7 Programming 5 - 34
Java SE 7 Programming 5 - 35
Summary
Java SE 7 Programming 5 - 36
Java SE 7 Programming 5 - 37
This practice covers using the static and final keywords and
refactoring an existing application to implement the singleton
design pattern.
Java SE 7 Programming 5 - 38
Java SE 7 Programming 5 - 39
Java SE 7 Programming 6 - 2
Objectives
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
implementation is vendor-specific.
Division of labor
Outlining the business API needed by an applications UI
allows the UI and the business logic to be developed in
tandem.
Abstraction
You just learned how to define abstract types by using classes. There are two ways to define type
abstraction in Java: abstract classes and interfaces. By writing code to reference abstract types,
you no longer depend on specific implementing classes. Defining these abstract types may seem
like extra work in the beginning but can reduce refactoring at a later time if used appropriately.
Java SE 7 Programming 6 - 3
Java Interfaces
Java interfaces are used to define abstract types. Interfaces:
Are similar to abstract classes containing only public
abstract methods
Outline methods that must be implemented by a class
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 the contract
must fulfill the entire contract or be declared abstract.
Java SE 7 Programming 6 - 4
Java SE 7 Programming 6 - 5
Constant Fields
Only constant fields are permitted in an interface. When you declare a field in an interface, it is
implicitly public, static, and final. You may redundantly specify these modifiers. Avoid
grouping all the constant values for an application in a single interface; good design distributes the
constant values of an application across many classes and interfaces. Creating monolithic classes
or interfaces that contain large groupings of unrelated code does not follow best practices for
object-oriented design.
Java SE 7 Programming 6 - 6
Interface References
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.
Java SE 7 Programming 6 - 7
instanceof Operator
You can use instanceof with interfaces.
Implements
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 Television implements
ElectronicDevice . Therefore, a Television is an instance of a Television, an
ElectronicDevice, and a java.lang.Object.
Java SE 7 Programming 6 - 8
Marker Interfaces
Java SE 7 Programming 6 - 9
Casting Guidelines
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) {
e.turnOn();
}
Java SE 7 Programming 6 - 10
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 affecting your code. An EmployeeDAOMemoryImpl typed reference could
be used to invoke a method that appears only in the EmployeeDAOMemoryImpl class.
References typed to a specific class cause your code to be more tightly coupled to that class and
potentially cause greater refactoring of your code when changing implementations.
Java SE 7 Programming 6 - 11
EmployeeDAOMemoryImpl implements
EmployeeDAO
Extends First
If you use both extends and implements, extends must come first.
Java SE 7 Programming 6 - 12
Extending Interfaces
Java SE 7 Programming 6 - 13
Extends
Implements
Interface Inheritances
Interfaces are used for a form of inheritance that is referred to as interface inheritance. Java allows
multiple interface inheritance but only single class inheritance.
Extending an Implementing Class
If you write a class that extends a class that implements an interface, the class you authored also
implements the interface. For example, AmphibiousCar extends BasicCar. BasicCar
implements Car; therefore, AmphibiousCar also implements Car.
Interfaces Extending Interfaces
An interface can extend another interface. For example, the interface MotorizedBoat can
extend the Boat interface. If the AmphibiousCar class implements 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. If the signatures are the same, there is
no conflict and only one implementation is required.
Java SE 7 Programming 6 - 14
Quiz
Java SE 7 Programming 6 - 15
Java SE 7 Programming 6 - 16
Java SE 7 Programming 6 - 17
DAO Pattern
Java SE 7 Programming 6 - 18
DAO Implementations
If you think that you might need to change your DAO implementation at a later time to use a
different persistence mechanism, it is best to use an interface to define the contract that all DAO
implementations must 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 database-enabled DAOs.
Java SE 7 Programming 6 - 19
Java SE 7 Programming 6 - 20
The EmployeeDAO
implementation is hidden.
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 do not want the majority of the code you write to be tightly coupled with the
type of persistence.
Java SE 7 Programming 6 - 21
The Factory
The implementation of the factory is the only point in the
application that should depend on concrete DAO classes.
Returns an interface typed
reference
For simplicity, this factory hardcodes the name of a concrete class to instantiate. You could
enhance this factory by putting the class name in an external source such as a text file and use
the java.lang.Class class to instantiate the concrete subclass. A basic example of using the
java.lang.Class is the following:
String name = "com.example.dao.EmployeeDAOMemoryImpl";
Class clazz = Class.forName(name);
EmployeDAO dao = (EmployeeDAO)clazz.newInstance();
Java SE 7 Programming 6 - 22
Java SE 7 Programming 6 - 23
Quiz
Java SE 7 Programming 6 - 24
Code Reuse
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 occurring
in a project. Besides performing manual code audits, there are tools you can use to detect
duplicated code. For one such example, refer to http://pmd.sourceforge.net/cpd.html.
Java SE 7 Programming 6 - 25
Design Difficulties
Java SE 7 Programming 6 - 26
Class inheritance allows for code reuse but is not very modular
How do you create a SpyCarWithSunRoof?
Composition
composition
Delegation
Method delegation and method forwarding are two terms that are often used interchangeably.
Method forwarding is when you write a method that does nothing except pass execution over to
another method. In some cases, delegation may imply more than simple forwarding. For more on
the difference between the two, refer to page 20 of the book Design Patterns: Elements of
Reusable Object-Oriented Software.
Java SE 7 Programming 6 - 27
Composition Implementation
Method
forwarding
Right-click within the braces of the complex class and choose "Insert Code.
2.
3.
Java SE 7 Programming 6 - 28
Code Reuse
The ability to use the addCar method for any type of Car, no matter how complex, is another form
of code reuse. We cannot currently say the following:
addCar(new SpyCarWithSunRoof());
Java SE 7 Programming 6 - 29
Each delegate class that you use in a composition should have an interface defined. When
creating the composing class, you declare that it implements all of the delegate interface types.
By doing this, you create an object that is a composition of other objects and has many types.
Now we can say:
addCar(new SpyCarWithSunRoof());
Java SE 7 Programming 6 - 30
Quiz
Java SE 7 Programming 6 - 31
Java SE 7 Programming 6 - 32
Summary
Java SE 7 Programming 6 - 33
Java SE 7 Programming 6 - 34
Java SE 7 Programming 6 - 35
Java SE 7 Programming 7 - 2
Objectives
Generics
Provide flexible type safety to your code
Move many common errors from runtime to compile time
Provide cleaner, easier-to-write code
Reduce the need for casting with collections
Are used heavily in the Java Collections API
Java SE 7 Programming 7 - 3
}
public void add(Shirt shirt){
this.shirt = shirt;
}
public Shirt get(){
return this.shirt;
}
}
The two examples in the slide show very simple caching classes. Even though each class is very
simple, a separate class is required for any object type.
Java SE 7 Programming 7 - 4
To create a generic version of the CacheAny class, a variable named T is added to the class
definition surrounded by angle brackets. In this case, T stands for type and can represent any
type. As the example shows, the code has changed to use t instead of a specific type information.
This change allows the CacheAny class to store any type of object.
T was chosen not by accident but by convention. A number of letters are commonly used with
generics.
Note: You can use any identifier you want. The following values are merely strongly suggested.
Here are the conventions:
T: Type
E: Element
K: Key
V: Value
S, U: Used if there are second types, third types, or more
Java SE 7 Programming 7 - 5
Generics in Action
Note how the one generic version of the class can replace any number of type-specific caching
classes. The add() and get() functions work exactly the same way. In fact, 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 the TestCacheAny.java file.
Java SE 7 Programming 7 - 6
Syntax
//Generics
CacheAny<String> myMessage = new CacheAny<>();
}
The type inference diamond is a new feature in JDK 7. In 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.
Java SE 7 Programming 7 - 7
Java SE 7 Programming 7 - 8
Quiz
Collections
A collection is a single object that manages a group of objects. Objects in the collection are called
elements. Various collection types implement standard data structures including stacks, queues,
dynamic arrays, and hashes. All the collection objects have been optimized for use in Java
applications.
Note: The Collections classes are all stored in the java.util package. The import statements
are not shown in the following examples, but the import statements are required for each
collection type:
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
Java SE 7 Programming 7 - 9
The diagram in the slide shows all the collection types that descend from Collection. Some
sample methods are provided for both Collection and List. Note the use of generics.
Characteristics of Implementation Classes
HashSet: A collection of elements that contains no duplicate elements
TreeSet: A sorted collection of elements that contains no duplicate elements
ArrayList: A dynamic array implementation
Deque: A collection that can be used to implement a stack or a queue
Note: The Map interface is a separate inheritance tree and is discussed later in the lesson.
Java SE 7 Programming 7 - 10
Collection Types
List Interface
The List interface is the basis for all Collections classes that exhibit list behavior.
Java SE 7 Programming 7 - 11
Java SE 7 Programming 7 - 12
In the example in the slide, a part number list is created using an ArrayList. Using syntax prior
to Java version 1.5, there is no type definition. So any type can be added to the list as shown on
line 8. So it is up to the programmer to know what objects are in the list and in what order. If an
assumption were made that the list was only for Integer objects, a runtime error would occur on
line 12.
On lines 1016, with a non-generic collection, an Iterator is used to iterate through the list of
items. Notice that a lot of casting is required to get the objects back out of the list so you can print
the data.
In the end, there is a lot of needless syntactic sugar (extra code) working with collections in this
way.
If the line that adds the String to the ArrayList is commented out, the program produces the
following output:
Part number: 1111
Part number: 2222
Part number: 3333
Java SE 7 Programming 7 - 13
1 import java.util.ArrayList;
2 import java.util.List;
3
4 public class GenericArrayList {
5 public static void main(String args[]){
6
7
List<Integer> partList = new ArrayList<>(3);
8
9
partList.add(new Integer(1111));
10
partList.add(new Integer(2222));
11
partList.add(new Integer(3333));
12
partList.add(new Integer(4444)); // ArrayList auto grows
13
14
System.out.println("First Part: " + partList.get(0)); // First item
15
partList.add(0, new Integer(5555)); // Insert an item by index
16
17
// partList.add("Bad Data"); // compile error now
With generics, things are much simpler. When the ArrayList is initialized on line 6, any attempt
to add an invalid value (line 15) results in a compile-time error.
The example in the slide shows a number of ArrayList features.
Line 12 demonstrates how an ArrayList grows automatically when an item is added
beyond its original size.
Line 14 shows how elements can be accessed by their index.
Line 15 shows how elements can be inserted into the list based on their index.
Note: On line 7, the ArrayList is assigned to a List type. Using this style enables you to swap
out the List implementation without changing other code.
Java SE 7 Programming 7 - 14
Generic ArrayList
Using the for-each loop is much easier and provides much cleaner code. No casts are done
because of the autounboxing feature of Java.
Java SE 7 Programming 7 - 15
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 enable you to make sensible
assignments without formal casting syntax. Java provides the casts for you at compile time.
Note: Be careful when using autoboxing in a loop. There is a performance cost to using this
feature.
Java SE 7 Programming 7 - 16
Quiz
Which of the following declares an Integer ArrayList with
three elements?
List<Integer>
List<Integer>
List<Integer>
List<Integer>
partList
partList
partList
partList
=
=
=
=
new
new
new
new
ArrayList<>(three);
ArrayList<>[3];
ArrayList<>(three);
ArrayList<>(3);
Java SE 7 Programming 7 - 17
a.
b.
c.
d.
Set Interface
A set is a list that contains only unique elements.
A set has no index.
Duplicate elements are not allowed in a set.
You can iterate through elements to access them.
TreeSet provides sorted implementation.
Java SE 7 Programming 7 - 18
A set is a collection of unique elements. This example uses a TreeSet, which sorts the items in
the set. If the program is run, the output is as follows:
Item: one
Item: three
Item: two
Java SE 7 Programming 7 - 19
Map Interface
Key
Value
101
Blue Shirt
102
Black Shirt
103
Gray Shirt
A Map is good for tracking things like part lists and their descriptions (as shown in the slide).
Java SE 7 Programming 7 - 20
The Map interface does not extend the Collection interface because it represents mappings
and not a collection of objects. Some of the key implementation classes include:
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.
Java SE 7 Programming 7 - 21
Map Types
The example shows how to create a Map and perform standard operations on it. The output from
the program is:
=== Part List ===
Part#: 111111 Blue Polo Shirt
Part#: 222222 Black T-Shirt
Part#: 333333 Duke Hat
Java SE 7 Programming 7 - 22
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
Java SE 7 Programming 7 - 23
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).
Java SE 7 Programming 7 - 24
Ordering Collections
The Collections API provides two interfaces for ordering elements: Comparable and
Comparator.
The Comparable interface is implemented in a class and provides a single sorting option for the
class.
The Comparator interface enables you to create multiple sorting options. You plug in the
designed option whenever you want.
Both interfaces can be used with sorted collections, such as TreeSet and TreeMap.
Java SE 7 Programming 7 - 25
Comparable Interface
Using the Comparable interface:
Overrides the compareTo method
Provides only one sort option
The slide shows how the ComparableStudent class relates to the Comparable interface and
TreeSet.
Java SE 7 Programming 7 - 26
This example in the slide implements the Comparable interface and its compareTo method.
Notice that because the interface is designed using generics, the angle brackets define the class
type that is passed into the compareTo method. The if statements are included to demonstrate
the comparisons that take place. You can also merely return a result.
The returned numbers have the following meaning.
Negative number: s comes before the current element.
Positive number: s comes after the current element.
Zero: s is equal to the current element.
In cases where the collection contains equivalent values, replace the code that returns zero with
additional code that returns a negative or positive number.
Java SE 7 Programming 7 - 27
Comparable: Example
ID: 3333
ID: 2222
GPA:3.4
GPA:3.9
ID: 1111
GPA:3.8
Java SE 7 Programming 7 - 28
Comparator Interface
The slide shows two Comparator classes that can be used with the Student class. The
example in the next slide shows how to use Comparator with an unsorted interface like
ArrayList by using the Collections utility class.
Java SE 7 Programming 7 - 29
The example in the slide shows the Comparator classes that are created to sort based on Name
and GPA. For the name comparison, the if statements have been simplified.
Java SE 7 Programming 7 - 30
Comparator: Example
The example in the slide shows how the two Comparator objects are used with a collection.
Note: Some code has been commented out to save space.
Notice how the Comparator objects are initialized on 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 following output.
Name: George Washington ID: 3333 GPA:3.4
Name: John Adams ID: 2222 GPA:3.9
Name: Thomas Jefferson ID: 1111 GPA:3.8
Name: John Adams ID: 2222 GPA:3.9
Name: Thomas Jefferson ID: 1111 GPA:3.8
Name: George Washington ID: 3333 GPA:3.4
Notes
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.
Java SE 7 Programming 7 - 31
Java SE 7 Programming 7 - 32
Quiz
Java SE 7 Programming 7 - 33
Summary
Java SE 7 Programming 7 - 34
Java SE 7 Programming 7 - 35
Java SE 7 Programming 7 - 36
String Processing
Objectives
Java SE 7 Programming 8 - 2
Command-Line Arguments
When a Java program is launched from a terminal 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").
Java SE 7 Programming 8 - 3
Example execution:
java TestArgs "Ted Baxter" 45 100.25
args[0] is 'Ted Baxter'
args[1] is '45'
args[2] is '100.25'
Command-line arguments are always passed to the main method as strings, regardless of their
intended type. If an application requires command-line arguments other than type String (for
example, numeric values), the application should convert the string arguments to their respective
types using the wrapper classes, such as the Integer.parseInt method, which can be used to
convert the string argument that represents the numeric integer to type int.
Java SE 7 Programming 8 - 4
Command-Line Arguments
Properties
The benefit of a properties file is the ability to set values for your application externally. The
properties file is typically read at the start of the application and is used for default values. But the
properties file can also be an integral part of a localization scheme, where you store the values of
menu labels and text for various languages that your application may support.
The convention for a properties file is <filename>.properties, but the file can have any
extension you want. The file can be located anywhere that the application can find it.
Java SE 7 Programming 8 - 5
hostName = www.example.com
userName = user
password = pass
In the code fragment, you create a Properties object. Then, using a try statement, you open a
file relative to 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.
Java SE 7 Programming 8 - 6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Property information can also be passed on the command line. The advantage to passing
properties from the command line is simplicity. You do not have to open a file and read from it.
However, if you have more than a few parameters, a properties file is preferable.
Java SE 7 Programming 8 - 7
If you do not want to type System.out.whatever over and over again, you can use
PrintWriter to save you some typing. The example in the slide shows how to create the object.
The true option is required to force PrintWriter to flush each line printed to the console.
Java SE 7 Programming 8 - 8
import java.io.PrintWriter;
printf format
You can perform the printf format using both the String class and any output stream. The slide
shows several different string formatting examples. See the Java API documentation for details
about all the options.
%s: String
%d: Decimal
%f: Float
The program output is the following:
We have 002 Blue Polo shirts
We have 002 Blue Polo shirts
We have 002 Blue Polo shirts
We have 002 Blue Polo shirts
that
that
that
that
cost
cost
cost
cost
$24.99.
$24.99.
$24.99.
$24.99.
Java SE 7 Programming 8 - 9
Quiz
Java SE 7 Programming 8 - 10
String Processing
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.
Java SE 7 Programming 8 - 11
Searching
Parsing
Extracting substring
Concurrency
The StringBuilder and StringBuffer classes are the preferred way to concatenate strings.
Java SE 7 Programming 8 - 12
StringBuilder: Example
public class StringBuilding {
public static void main(String[] args){
StringBuilder sb = new StringBuilder(500);
");
System.out.println(sb.toString());
}
}
Copyright 2011, Oracle and/or its affiliates. All rights reserved.
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...
[
10 ] times
Java SE 7 Programming 8 - 13
The code in the slide demonstrates some of the more useful string methods of the String class.
equals(): Tests the equality of the contents of two strings. This is preferable to ==, which
tests whether two objects point to the same reference.
contains(): Searches a string to see if it 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
Java SE 7 Programming 8 - 14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
4
5
6
7
8
9
10
The simplest way to parse a string is using the split() method. Call the method with the
character (or characters) 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
Maroon Shirt
Java SE 7 Programming 8 - 15
1
2
3
4
5
6
7
8
9
10
11
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 delimiter ", " in this case
means use both commas and spaces as delimiters. Thus, the result from parsing is the following:
Blue
Shirt
Red
Shirt
Black
Shirt
Maroon
Shirt
Java SE 7 Programming 8 - 16
1
2
3
Scanner
A Scanner can tokenize a string or a stream.
public static void main(String[] args) {
Scanner s = null;
StringBuilder sb = new StringBuilder(64);
String line01 = "1.1, 2.2, 3.3";
float fsum = 0.0f;
s = new Scanner(line01).useDelimiter(", ");
try {
while (s.hasNextFloat()) {
float f = s.nextFloat();
fsum += f;
sb.append(f).append(" ");
}
System.out.println("Values found: " + sb.toString());
System.out.println("FSum: " + fsum);
} catch (Exception e) {
System.out.println(e.getMessage());
}
A Scanner can be used to tokenize an input stream or a string. In addition, a Scanner can be
used to tokenize numbers and convert them into any primitive number type. Note how the
Scanner is defined on line 7. The resulting object can be iterated over based on a specific type.
In this case, a float is used.
The output from this code segment is as follows:
Values found: 1.1 2.2 3.3
FSum: 6.6000004
Java SE 7 Programming 8 - 17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Regular Expressions
Pattern
Matcher
PatternSyntaxException
java.util.regex
Java SE 7 Programming 8 - 18
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternExample {
public static void main(String[] args){
String t = "It was the best of times";
Pattern pattern = Pattern.compile("the");
Matcher matcher = pattern.matcher(t);
if (matcher.find()) { System.out.println("Found match!"); }
}
}
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!
Java SE 7 Programming 8 - 19
Character Classes
[abc]
[^abc]
[a-c]
Java SE 7 Programming 8 - 20
Character Description
Pattern
Text Matched
w.s
w[abc]s
t[^aeo]mes
The code for this example can be found in the StringExamples project in the
CustomCharClassExamples.java file.
Java SE 7 Programming 8 - 21
Target String
The example in the slide shows two ways to find was and a way to find times.
To make this happen in Java:
1. Create a Pattern object to store the regular expression that you want to search with.
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.
4. Call Matcher.group() to display the characters that match your pattern.
Java SE 7 Programming 8 - 22
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Predefined
Character
Character Class
Negated
Negated Class
Character
\d (digit)
[0-9]
\D
[^0-9]
\w (word char)
[a-zA-Z0-9_]
\W
[^a-zA-Z0-9_]
\S
[^ \r\t\n\f\0XB]
A number of character classes are used repeatedly. These classes are turned into predefined
character classes. Classes exist to identify digits, word characters, and white space.
White-Space Characters
\t: Tab character
\n: New-line character
\r: Carriage return
\f: Form feed
\x0B: Vertical tab
Java SE 7 Programming 8 - 23
Pattern
Description
Text Matched
\\d\\d
Jo told me 20 ways
to San Jose in 15
minutes.
\\sin\\s
Jo told me 20 ways
to San Jose in 15
minutes.
\\Sin\\S
Jo told me 20 ways
to San Jose in 15
minutes.
** If there are additional matches in the current line, additional calls to find() will return the next
match on that line.
Example:
Pattern p1 = Pattern.compile("\\d\\d");
Matcher m1 = p1.matcher(t);
while (m1.find()){
System.out.println("Found: " + m1.group());
}
Produces:
Found: 20
Found: 15
The code for this example can be found in the StringExamples project in the
PredefinedCharClassExample.java file.
Java SE 7 Programming 8 - 24
Target String
Quantifiers
{n}
{m,n}
{m,}
(xx){n}
Java SE 7 Programming 8 - 25
Quantifier Description
Quantifier: Examples
Pattern
Text Matched
ago.*
Longlonglong ago, in
a galaxy far far away
gal.{3}
Longlonglong ago, in
a galaxy far far away
(long){2}
Longlonglong ago, in
a galaxy far far away
The code for this example can be found in the StringExamples project in the
QuantifierExample.java file.
Java SE 7 Programming 8 - 26
Target String
Greediness
Target String
Pattern
Text Matched
ago.*far
Longlonglong ago, in
a galaxy far far away.
ago.*?far
Longlonglong ago, in
a galaxy far far away.
A regular expression always tries to match the characters that return the most characters. This is
known as the greediness principle. Use the ? operator to limit the result to the fewest characters
needed to match the pattern.
The code for this example can be found in the StringExamples project in the
GreedinessExample.java file.
Java SE 7 Programming 8 - 27
Java SE 7 Programming 8 - 28
Quiz
Anchor
Description
\b
\B
Java SE 7 Programming 8 - 29
Boundary Matchers
Boundary: Examples
Pattern
^it.*?times
Text Matched
It was the best of
times or it was the
worst of times
It was the best of
times or it was the
worst of times
It was the best of
times or it was the
worst of times
The code for this example can be found in the StringExamples project in the
BoundaryCharExample.java file.
Java SE 7 Programming 8 - 30
Target String
Quiz
Java SE 7 Programming 8 - 31
Target String
george.washington@example.com
Match 3 Parts
(george).(washington)@(example.com)
Group Numbers
( 1 ).( 2 )@( 3 )
Pattern
(\\S+?)\\.(\\S+?)\\@(\\S+)
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 pair of parentheses
is numbered. In a regular expression, group(0) matches all the text matched when groups are
used. Here is the source code for the example:
public class MatchingExample {
public static void main(String[] args){
String email = "george.washington@example.com";
Pattern p1 = Pattern.compile("(\\S+?)\\.(\\S+?)\\@(\\S+)");
Matcher m1 = p1.matcher(email);
if (m1.find()){
System.out.println("First: " + m1.group(1));
System.out.println("Last: " + m1.group(2));
System.out.println("Domain: " + m1.group(3));
System.out.println("Everything Matched: " + m1.group(0));
}
}
}
Java SE 7 Programming 8 - 32
Pattern p1 = Pattern.compile("h1");
Matcher m1 = p1.matcher(header);
if (m1.find()){
header = m1.replaceAll("p");
System.out.println(header);
}
}
}
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>
Java SE 7 Programming 8 - 33
Summary
Java SE 7 Programming 8 - 34
Java SE 7 Programming 8 - 35
Java SE 7 Programming 8 - 36
Java SE 7 Programming 8 - 37