Académique Documents
Professionnel Documents
Culture Documents
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
Java SE 7 Programming m
co e
i l
g ma Guid
g h @ ent
v ar Guide d I
t-uVolume
y
Student S
( finn e this
E SE to us
R GH nse
V A lice
I L IP ble
P H fera
N Y rans
N
FI non-t
D67238GC20
Edition 2.0
June 2012
D74996
Aptech Ltd
Authors Copyright 2012, Oracle and/or its affiliates. All rights reserved.
Tom McGinn This document contains proprietary information and is protected by copyright and
Matt Heimer other intellectual property laws. You may copy and print this document solely for your
own use in an Oracle training course. The document may not be modified or altered
in any way. Except where your use constitutes "fair use" under copyright law, you
Technical Contributors may not use, share, download, upload, copy, print, display, perform, reproduce,
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
publish, license, post, transmit, or distribute this document in whole or in part without
and Reviewers the express authorization of Oracle.
Peter Hall
The information contained in this document is subject to change without notice. If you
Marnie Knue find any problems in the document, please report them in writing to: Oracle University,
500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
Lee Klement warranted to be error-free.
Steve Watts
Restricted Rights Notice
Brian Earl
Vasily Strelnikov If this documentation is delivered to the United States Government or anyone using
the documentation on behalf of the United States Government, the following notice is
Andy Smith applicable:
Nancy K.A.N
U.S. GOVERNMENT RIGHTS
Chris Lamb
s a
The U.S. Governments rights to use, modify, reproduce, release, perform, display, or
Todd Lowry
)h a
disclose these training materials are restricted by the terms of the applicable Oracle
license agreement and/or the applicable U.S. Government contract.
Ionut Radu
co e m
Trademark Notice
i l
Joe Darcy
mitsaaffiliates. id names
uOther
Brian Goetz g
Oracle and Java are registered trademarks of Oracle and/or
may be trademarks of their respective owners. @ t G
g h e n
ar Stud
Alan Bateman
David Holmes y v
( finn e this
Editors
E SE to us
Richard Wallis
G H se
Daniel Milne R
A licen
V
I L IP ble
Vijayalakshmi Narasimhan
P H fera
GraphicYDesignerns
INNHans
FJames n - tra
no
Publishers
Syed Imtiaz Ali
Sumesh Koshy
Aptech Ltd
Contents
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
1 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 s a
Java SE Platform Versions 1-11 )h a
Downloading and Installing the JDK 1-12 m
co e
i l
Java in Server Environments 1-13
g ma Guid
The Java Community 1-14
g h @ ent
The Java Community Process (JCP) 1-15
y v ar Stud
finn e this
OpenJDK 1-16
Oracle Java SE Support 1-17 (
Additional Resources 1-18 E SE to us
Summary 1-19 R GH nse
V A lice
2 Java Syntax I L IP blReview
and Class
e
PH 2-2sfer a
Objectives
Y
I N N - t r an Review 2-3
Java Language
F Class
nonStructure 2-4
A Simple Class 2-5
Code Blocks 2-6
Primitive Data Types 2-7
Java SE 7 Numeric Literals 2-9
Java SE 7 Binary Literals 2-10
Operators 2-11
Strings 2-12
String Operations 2-13
if else 2-14
Logical Operators 2-15
Arrays and for-each Loop 2-16
for Loop 2-17
iii
Aptech Ltd
iv
Aptech Ltd
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
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
v
Aptech Ltd
vi
Aptech Ltd
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
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
vii
Aptech Ltd
viii
Aptech Ltd
Quiz 8-31
Matching and Groups 8-32
Using the replaceAll Method 8-33
Summary 8-34
Practice 8-1 Overview: Parsing Text with split() 8-35
Practice 8-2 Overview: Creating a Regular Expression Search Program 8-36
Practice 8-3 Overview: Transforming HTML by Using Regular Expressions 8-37
ix
Aptech Ltd
Summary 9-30
Practice 9-1 Overview: Catching Exceptions 9-31
Practice 9-2 Overview: Extending Exception 9-32
Objectives 10-2
Java I/O Basics 10-3
I/O Streams 10-4
I/O Application 10-5
Data Within Streams 10-6
Byte Stream InputStream Methods 10-7
Byte Stream OutputStream Methods 10-9
Byte Stream Example 10-10
Character Stream Reader Methods 10-11
s a
Character Stream Writer Methods 10-12
)h a
Character Stream Example 10-13 m
co e
i l
ma Guid
I/O Stream Chaining 10-14
Chained Streams Example 10-15 g
@ ent
g h
Processing Streams 10-16
Console I/O 10-17 y v ar Stud
java.io.Console 10-18 ( finn e this
SE to us
Writing to Standard Output 10-19
E
GH nse
Reading from Standard Input 10-20
R
A lice
Channel I/O 10-21
V
L IP ble
Practice 10-1 Overview: Writing a Simple Console I/O Application 10-22
I
P H fera
Persistence 10-23
N Y rans
Serialization and Object Graphs 10-24
N
FI non-t
Transient Fields and Objects 10-25
Transient: Example 10-26
Serial Version UID 10-27
Serialization Example 10-28
Writing and Reading an Object Stream 10-29
Serialization Methods 10-30
readObject Example 10-31
Summary 10-32
Quiz 10-33
Practice 10-2 Overview: Serializing and Deserializing a ShoppingCart 10-37
x
Aptech Ltd
xi
Aptech Ltd
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
s a
Executing Runnable Instances 12-9
)h a
A Runnable with Shared Data 12-10 m
co e
i l
ma Guid
One Runnable: Multiple Threads 12-11
Quiz 12-12 g
@ ent
g h
Problems with Shared Data 12-13
Nonshared Data 12-14 y v ar Stud
Quiz 12-15 ( finn e this
SE to us
Atomic Operations 12-16
E
GH nse
Out-of-Order Execution 12-17
R
Quiz 12-18 V A lice
L IP ble
The volatile Keyword 12-19
I
P H fera
Stopping a Thread 12-20
N Y rans
The synchronized Keyword 12-22
N
FI non-t
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
Aptech Ltd
13 Concurrency
Objectives 13-2
The java.util.concurrent Package 13-3
The java.util.concurrent.atomic Package 13-4
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
xiii
Aptech Ltd
15 Localization
Objectives 15-2
Why Localize? 15-3
A Sample Application 15-4
Locale 15-5
Resource Bundle 15-6
xiv
Aptech Ltd
n o 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
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SE to us
R GH nse
V A lice
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Introduction
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Course Goals
This course covers the core APIs that you use to design
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 1 - 2
Aptech Ltd
Course Objectives
following:
Create Java technology applications that leverage the
object-oriented features of the Java language, such as
encapsulation, inheritance, and polymorphism
Execute a Java application from the command line
Create applications that use the Collections framework
Implement error-handling techniques using exception
a
handling
) has
Implement input/output (I/O) functionality to read from
l c omand e
write to data and text files a i i d
and understand advanced @ gm t Gu
I/O streams a r gh tuden
v n y is S
( f i n th
E us e
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 1 - 3
Aptech Ltd
Course Objectives
(continued)
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 1 - 4
Aptech Ltd
Audience
Java SE 7 Programming 1 - 5
Aptech Ltd
Prerequisites
Java SE 7 Programming 1 - 6
Aptech Ltd
Class Introductions
Name
Title or position
Company
Experience with Java programming and Java applications
Reasons for attending
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 1 - 7
Aptech Ltd
Course Environment
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Classroom PC
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP products
In this course, the Ifollowing b le are preinstalled for the lesson practices:
PHJavasfSE a
erDevelopment Kit includes the command-line Java compiler
JDK 7: The
Y
N -and
(javac) r n Java Runtime Environment (JRE), which supplies the java command
athe
I N
F needed t
nonto 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
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I
Platform-IndependentL IPPrograms
b le
PHapplications
f a
er are written in the Java programming language and compiled to
Java technology
Y s
an is executed on the Java platform. The software that provides you
N -tBytecode
JavaIN
bytecode.
F a runnable r
with non 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
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP bleGroups
Identifying Java Technology
P Ha complete
f e raline of Java technology products ranging from kits that create
ans to emulation (testing) environments for consumer devices, such as
Oracle provides
JavaIN NY -trprograms
technology
F phones.
cellular non As indicated in the graphic, all Java technology products share the
foundation of the Java language. Java technologies, such 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 illustrates the three Java technology product
groups and 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.
Note: Applets and applications differ in several ways. Primarily, applets are launched inside a
web browser, whereas applications are launched within an operating system.
Java SE 7 Programming 1 - 10
Aptech Ltd
Developer
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Year 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 s a
)h a
2011 1.7 7 m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
How to Detect Your I L P ble
IVersion
If Java SEY PH sonfeyour
is installed
ra system, you can detect the version number by running
N N -traNote n that the java command is included with the Java Runtime
java I -version.
F non(JRE). As a developer, you also need a Java compiler, typically javac. The
Environment
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.
Java SE 7 Programming 1 - 11
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP ble
1. Go to http://www.oracle.com/technetwork/java/javase/downloads/index.html.
I
2. ChoosePthe Java e ra Standard Edition (Java SE) link.
H fPlatform,
NY -tthe s
anversion
3. IN
F Download
n r that is appropriate for your operation system.
o
n the installation instructions.
4. Follow
5. Set your PATH.
Java SE 7 Programming 1 - 12
Aptech Ltd
environments:
Oracle Fusion Middleware
Java application servers
GlassFish
WebLogic
Database servers
MySQL
s a
Oracle Database
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Enterprise EnvironmentsI L IP ble
P H developf e raJava SE applications. There are standard patterns you need to
In this course,
followN N
when
you
Yimplementing
t r a ns Java SE applications, such as always creating a main method that
FIbe different
may
-
non 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
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
ar Stud
Apache Software Foundation
y v
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
What Is the Java Community?
P H Java f e ra
N Y rans
At a very high level, Community is the term used to refer to the many individuals and
FIN noasnthat
organizations
developers
t develop, innovate, and use Java technology. This community includes
-individuals, organizations, businesses, and open-source projects.
It is very common for you to download and use Java libraries from non-Oracle sources within
the Java community. For instance, in this course, you use an Apache-developed JDBC library
to access a relational database.
Java SE 7 Programming 1 - 14
Aptech Ltd
http://jcp.org
Free download of all Java Specification Requests (JSRs)
Early access to specifications
Public review and feedback opportunities
Open membership
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
JCP.next I L IP ble
P e ra that outline the standards of the Java platform. The behavior of
H the fJSRs
Y rans
The JCP produces
N
N
I onis-talso defined and improved through the JSR process. The JCP is evolving and
the JCP itself
itsF
improvements
n 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
Aptech Ltd
OpenJDK
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
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L
Why OpenJDK Is IImportantIP ble
is P
H feraOpenJDK enables users to port Java to operating systems and
Because itY
N
hardwareN t
platformsr nofstheir choosing. Ports are underway for many platforms (besides those
open source,
a
FI supported)
already
-
non including FreeBSD, OpenBSD, NetBSD, and MacOS X.
Java SE 7 Programming 1 - 16
Aptech Ltd
Java SE 7 Programming 1 - 17
Aptech Ltd
Additional Resources
Topic Website
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 1 - 18
Aptech Ltd
Summary
Java SE 7 Programming 1 - 19
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SE to us
R GH nse
V A lice
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Objectives
following:
Create simple Java classes
Create primitive variables
Manipulate Strings
Use if-else and switch branching statements
Iterate with loops
Create arrays
Use Java fields, constructors, and methods s a
)h a
Use package and import m
statements i l co e
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 2 - 2
Aptech Ltd
Java SE 7 Programming 2 - 3
Aptech Ltd
Class Structure
package <package_name>;
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
import <other_packages>;
<constructor method(s)>;
s a
<other methods>;
)h a
} m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP in abtext
A Java class is described
I le file with a .java extension. In the example shown, the
Java keywords H highlighted
Pare f a
er in bold.
Y
Npackage s
ankeyword defines where this class lives relative to other classes, and
N
I The
F provides - t r
n on 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
Aptech Ltd
A Simple Class
}
}
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
To run a Java program,
I L IPyou must
b le define a main method as shown in the slide. The main
PH sfecalled
method is automatically
a
r when the class is called from the command line.
Y
N -arguments
Command-line r an are passed to the program through the args[] array.
I N
F A nmethod t
Note: on 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
Aptech Ltd
Code Blocks
Java SE 7 Programming 2 - 6
Aptech Ltd
Point False
byte float char boolean
short double
int
long
1, 2, 3, 42 3.0F 'a' true
07 .3337F '\u0061' false
0xff 4.022E23 '\n'
s a
0 0.0 '\u0000' false ) h
a
l c om e
Append uppercase or lowercase "L" or "F" to the number m aito specify
uid a
long or a float number.
g
@ ent G
g h
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Integer I L IP ble
P H different
f e rainteger types to accommodate different size numbers. All the
Java provides
N
numeric N
types
four
t ns which means that they can hold positive or negative numbers.
Y arerasigned,
FI notypes
The integer
n- 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. The most common integer type is int.
Number of bits = 32.
long range is 9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. Number of
bits = 64.
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 precision of float. A float uses 32 bits
to store data, whereas a double uses 64 bits.
Java SE 7 Programming 2 - 7
Aptech Ltd
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.
Boolean
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 2 - 8
Aptech Ltd
Java SE 7 Programming 2 - 9
Aptech Ltd
s a
// Some 32-bit 'int' values:
)h a
int anInt1 = 0b1010_0001_0100_0101_1010_0001_0100_0101; m
co e
i l
int anInt2 = 0b101;
g ma Guid
int anInt3 = 0B101; // The B can be upper h @or e n t case.
lower
g
ar Stud
y v
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L
Binary literals are Java
I IPint values.
b le A cast is required when the integer value of the literal
PH snon-negative
exceeds the greatest f er a value that the type can hold. For example:
Y n
I N on-=tra0b0111_1111; // aByte is 127
byteNaByte
F
byte aByten = 0b1000_0000; // compiler error a cast is required
// (value is -128)
Java SE 7 Programming 2 - 10
Aptech Ltd
Operators
Java SE 7 Programming 2 - 11
Aptech Ltd
Strings
1 public class Strings {
2
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
E us(
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
The code in the slide
I L P ble how text characters are represented in Java. Single
Idemonstrates
characters canP H represented
be f e ra with the char type. However, Java also includes a String
type for N Y ransmultiple characters. Strings can be defined as shown in the slide and
representing
N
FI nousing
combined n-t 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
Aptech Ltd
String Operations
Java SE 7 Programming 2 - 13
Aptech Ltd
if else
2
3 public static void main(String args[]){
4 long a = 1;
5 long b = 2;
6
7 if (a == b){
8 System.out.println("True");
9 } else {
a
10 System.out.println("False");
) has
11 }
l c om e
12
m ai uid
@ g t G
13 }
h
g tude n
14 } var n y is S
( f i n th
E us e
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
The example in theIL IP demonstrates
slide b le the syntax for an if-else statement in Java.
H
P the code r a
fein the slide is as follows:
The outputYfrom
N -tra n s
FINFalse
non
Java SE 7 Programming 2 - 14
Aptech Ltd
Logical Operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Conditional operators
&& Conditional-AND
s a
|| Conditional-OR )h a
?: Ternary (shorthand for if-then-else statement)
m
co e
i l
Type comparison operator g ma Guid
g h @typeent
instanceof Compares an object to a specified
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP ofblthe
The slide shows aIsummary e logic and conditional operators in Java.
PH sfer a
Y
N -tran
I N
F non
Java SE 7 Programming 2 - 15
Aptech Ltd
3
4 String[] names = new String[3];
5
6 names[0] = "Blue Shirt";
7 names[1] = "Red Shirt"; Arrays are objects.
8 names[2] = "Black Shirt"; Array objects have a
9 final field length.
10 int[] numbers = {100, 200, 300};
11
12 for (String name:names){
13 System.out.println("Name: " + name);
s a
14 }
)h a
15 m
co e
i l
ma Guid
16 for (int number:numbers){
17 System.out.println("Number: " + number);
g
@ ent
18 }
g h
19 }
y v ar Stud
finn e this
20 }
E us(
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L
This class demonstrates
I IP howbtoledefine arrays in Java. The first example creates a String
P H each
array and initializes f e ra separately. The second int array is defined in a single
element
N
statement.Y rans
N
FI array -t
Each oisniterated through using the Java for-each construct. The loop defines an
n
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
Aptech Ltd
for Loop
2
3 public static void main(String args[]){
4
5 for (int i = 0; i < 9; i++ ){
6 System.out.println("i: " + i);
7 }
8
9 }
s a
10 }
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
The classic for loop
I L IisPshownblinethe slide. A counter is initialized and incremented for each
P
step of the loop.HWhen fthee a
rcondition statement evaluates to false (when i is no longer less
than 9),N Ylooprexits.
the a n s Here is the sample output for this program.
I N - t
i:F0
non
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
Java SE 7 Programming 2 - 17
Aptech Ltd
while Loop
2
3 public static void main(String args[]){
4
5 int i = 0;
6 int[] numbers = {100, 200, 300};
7
8 while (i < numbers.length ){
9 System.out.println("Number: " + numbers[i]);
a
10 i++;
) has
11 }
l c om e
12 }
m ai uid
13 } @g nt G gh tude
a
v sS r
n y
( fin e thi
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
The while loop performs
I L IP a test b leand continues if the expression evaluates to true. The
PH here,
while loop, shown f a
eriterates through an array using a counter. Here is the output from
Y an
the codeNin the slide:
s
I N
F no100 n - t r
Number:
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
Aptech Ltd
3
4 String color = "Blue";
5 String shirt = " Shirt";
6
7 switch (color){
8 case "Blue":
9 shirt = "Blue" + shirt;
10 break;
11 case "Red":
12 shirt = "Red" + shirt;
13 break;
s a
14 default:
)h a
15 shirt = "White" + shirt; m
co e
i l
ma Guid
16 }
17 g
@ ent
g h
ar Stud
18 System.out.println("Shirt type: " + shirt);
19 }
y v
20 }
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
This example shows I L IaPswitch b lestatement in Java using a String. Prior to version 7 of Java,
PHbyte,sfshort,
only enums and
a
er char, and int primitive data types could be used in a
switchN Y
statement.
r anYou will see enums in the lesson titled Advanced Class Design.
I N
F non - t
Java SE 7 Programming 2 - 19
Aptech Ltd
Java SE 7 Programming 2 - 20
Aptech Ltd
Java SE 7 Programming 2 - 21
Aptech Ltd
Methods
E us(
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Adding Instance Methods I L IP to b lethe Employee Class
PH isstofecreate a
r a set of methods that manipulate field data: methods that set
A commonYpractice
N
the valueNof eacht r n and methods that get the value of each field. These methods are
afield,
I
F accessors -
called non (getters) and mutators (setters).
The convention is to use set and get plus the name of the field with the first letter of the field
name capitalized (lower camel case). Most modern integrated development environments
(IDEs) provide an easy way to automatically generate the accessor (getter) and mutator
(setter) methods for you.
Notice that the set methods use the keyword this. The this keyword allows the compiler to
distinguish between the field name of the class (this) and the parameter name being passed
in as an argument. Without the keyword this, the net effect is you are assigning a value to
itself. (In fact, NetBeans provides a warning: "Assignment to self.")
In this simple example, you could use the setName method to change the employee name
and the 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.)
Java SE 7 Programming 2 - 22
Aptech Ltd
FIN memory
allocate
n trfor the Employee object and call a constructor method in the class. An
-object
instance nofoan is created when you use the new keyword with a constructor. All of the
fields declared in the class are provided memory space and initialized to their default values.
If the memory allocation and constructor are successful, a reference to the object is returned
as a result. In the example in the slide, the reference is assigned to a variable called emp.
To store values (data) into the Employee object instance, you could just assign values to
each field by accessing the fields directly. However, this is not a good practice and negates
the principle of encapsulation. Instead, you should invoke instance methods and pass a value
to the method to set the value of each data field. Later in this lesson you will look at
restricting access to the fields to promote encapsulation.
Once all the data fields are set with values, you have an instance of an Employee with an
empId with a value of 101, name with the string John Smith, Social Security number string
(ssn) set to 011-22-3467, and salary with the value of 120,345.27.
Java SE 7 Programming 2 - 23
Aptech Ltd
Constructors
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 2 - 24
Aptech Ltd
package Statement
Java SE 7 Programming 2 - 25
Aptech Ltd
import Statements
Java SE 7 Programming 2 - 26
Aptech Ltd
More on import
Java SE 7 Programming 2 - 27
Aptech Ltd
Java Is Pass-By-Value
assignment operations.
To visualize this with primitives, consider the following:
int x = 3;
int y = x;
3 3
s a
)h a
x y m
co e
i l
copy the value of x g ma Guid
@ the
h5;), e n t
If x is later modified (for example, x r= g u d value of y
v a
y is S t
remains unchanged. n n
( f i e th
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
The Java language I L IP pass-by-value
uses b le for all assignment operations. This means that the
H
P rightsside
argument on the r a
fe of the equal sign is evaluated, and the value of the argument is
assigned Y
to the left n
N -tra of the equal sign.
side
I N
FJavanprimitives,
For on 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
Aptech Ltd
42 memory address = 42
x Employee
y = x;
object s a
) h a
42 m
co e
i l
y g ma Guid
g h @ ent
After the assignment, the value ofvyaris the tsame
y S ud as the
value of x: a reference to thefinsame n tEmployee h is object.
(
E use
E S oaffiliates. All rights reserved.
Oracle and/or tits
Copyright 2012,H
G s e
V AR licen
For Java objects, the
I L P ofbanleobject reference is the memory pointer to the instance of the
Ivalue
P
Employee object Hcreated.f e ra
WhenN N
you
Yassignrathensvalue of x to y, you are not creating a new Employee object, but rather
FI ofnthe
a copy
-t of the reference.
onvalue
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
Aptech Ltd
Java SE 7 Programming 2 - 30
Aptech Ltd
Java SE 7 Programming 2 - 31
Aptech Ltd
directory D:\test\com\example:
javac d D:\test D:\test\com\example\HelloWorld.java
To run the application, you use the interpreter and the fully
qualified class name:
java cp D:\test com.example.HelloWorld
Hello World!
s a
java cp D:\test com.example.HelloWorld Tom
)h a
Hello Tom! m
co e
i l
The advantage of an IDE like NetBeans @ is g ma Guid
that
h e n t
management of the class path, compilation, g
ar Studand running
y v
the Java application are handled
( finn through t h is the tool.
S E use
E oaffiliates. All rights reserved.
Oracle and/or tits
Copyright 2012,H
G s e
V AR licen
Example I L IP ble
P H simple
f e ra class in a file named HelloWorld.java in the
N Y rans directory:
Consider the following
N
I on-t
D:\test\com\example
F
packagen 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
Aptech Ltd
loads the compiled Java class files using a Java class of its
own called the class loader (java.lang.ClassLoader).
The class loader is called when a class member is used for
the first time:
public class Test {
public void someOperation() {
Employee e = new Employee();
//... The class loader is called to "load"
this class into memory. s a
}
)h a
} m
co e
i l
m a u id
Test.class.getClassLoader().loadClass("Employee"); g
@ ent G
g h
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Typically, the use of
I L IPclassbloader
the le is completely invisible to you. You can see the results of
PHby using
the class loader f a
r -verbose flag when you run your application. For example:
ethe
Y n s
N -traclasspath
javaNverbose
F I n
D:\test com.example.HelloWorld
[Loaded nojava.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
Aptech Ltd
Garbage Collection
Java SE 7 Programming 2 - 34
Aptech Ltd
Summary
Java SE 7 Programming 2 - 35
Aptech Ltd
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. An import statement is missing.
a
b. The boolean valid is assigned a String.
) has
c. String s is created using new.
l c om e
d. ai uid
BrokenClass method is missing a returnmstatement.
@ g t G
e. Need to create a new BrokenClass h n
v a rgobject.
t u de
f. The integer value i is assigned is S
nnya double.
( fi e th
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L
Answer: b and f willIPcausebcompilation
le errors. c will compile but is not a good
practice. P H fer a
N Y rans
a. AnN
I on-tstatement is not required, unless the class uses classes outside of
import
Fjava.lang.
n
d. BrokenClass() is a constructor.
e. Construction of a BrokenClass instance would typically happen in another class.
Java SE 7 Programming 2 - 36
Aptech Ltd
Quiz
Java SE 7 Programming 2 - 37
Aptech Ltd
Quiz
N
I on-t the result is the average of 200+300/3 = 166.66667. Change the for loop
values. Therefore,
to F
int = 0;nto properly calculate the average.
Java SE 7 Programming 2 - 38
Aptech Ltd
Java SE 7 Programming 2 - 39
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SE to us
R GH nse
V A lice
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Objectives
following:
Use encapsulation in Java class design
Model business problems using Java classes
Make classes immutable
Create and use Java subclasses
Overload methods
Use variable argument methods
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 3 - 2
Aptech Ltd
Encapsulation
Java SE 7 Programming 3 - 3
Aptech Ltd
Encapsulation: Example
s a
Employee ID
Set Name )h a
Name
Raise Salary
m
co e
i l
Social Security Number
g ma Guid
Salary
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
A Simple Model ILI
P ble
P Hare asked
f e rato create a model of a typical employee. What data might you
Y rans
Suppose that you
to N
wantIN -t in an object that describes an employee?
represent
F n o
Employee
n 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
Aptech Ltd
fields private.
1 public class CheckingAccount {
2 private int custID; Declaring fields private prevents
3 private String name; direct access to this data from a class
4 private double amount; instance.
5 public CheckingAccount {
6 }
7 public void setAmount (double amount) {
8 this.amount = amount;
s a
9 }
)h a
10 public double getAmount () { m
co e
i l
11 return amount;
g ma Guid
12 }
g h @ ent
13 //... other public accessor and mutator methods
y v ar Stud
finn e this
14 }
E us(
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
In this example, the
I L IP custID,
fields b le name, and amount are now marked private, making
them invisibleP H offethe
outside
a
r methods in the class itself.
Y
N -tran s
I
F nonN
For example:
CheckingAccount ca = new CheckingAccount():
ca.amount = 1_000_000_000.00; // illegal!
Java SE 7 Programming 3 - 5
Aptech Ltd
E us(
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 3 - 6
Aptech Ltd
Revisiting Employee
Java SE 7 Programming 3 - 7
Aptech Ltd
Java SE 7 Programming 3 - 8
Aptech Ltd
1 package com.example.domain;
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 3 - 9
Aptech Ltd
Java SE 7 Programming 3 - 10
Aptech Ltd
Creating Subclasses
Java SE 7 Programming 3 - 11
Aptech Ltd
Subclassing
superclass: Employee
("parent" class)
Java SE 7 Programming 3 - 12
Aptech Ltd
Manager Subclass
1 package com.example.domain;
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 3 - 13
Aptech Ltd
Java SE 7 Programming 3 - 14
Aptech Ltd
Java SE 7 Programming 3 - 15
Aptech Ltd
Employee object:
Manager mgr = new Manager (102, "Barbara Jones",
"107-99-9078", 109345.67, "Marketing");
Java SE 7 Programming 3 - 16
Aptech Ltd
What Is Polymorphism?
Java SE 7 Programming 3 - 17
Aptech Ltd
Overloading Methods
Your design may call for several methods in the same class
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 3 - 18
Aptech Ltd
Single Inheritance
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Although Java does I L IPpermitblmore
not e than one class to a subclass, the language does provide
PH multiple
features that enable f a
er classes to implement the features of other classes. You will see
Y
N lesson
this in the a s
onninheritance.
I N
F inheritance- t r
Single n on 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
Aptech Ltd
Summary
Java SE 7 Programming 3 - 22
Aptech Ltd
Quiz
a. e.addEmployee (a);
b. m.addEmployee(a); s a
)h a
c. m.approveExpense(100000.00); m
co e
i l
d. All of them fail to compile. g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Answer: a, c I L IP ble
P H because f e ra the Employee class does not have an addEmployee method.
N Ya partrofanthes Manager class.
a. A compiler error
F N
I on-t
This is
n properly because, although the constructor is creating a Director, it is the
b. Compiles
Manager class that the compiler is looking at to determine if there is an addEmployee
method
c. A compiler error because the Manager class does not contain an approveExpense
method
Java SE 7 Programming 3 - 23
Aptech Ltd
Quiz
Java SE 7 Programming 3 - 24
Aptech Ltd
Quiz
Java SE 7 Programming 3 - 25
Aptech Ltd
Quiz
What changes would you perform to make this class
immutable? (Choose all that apply.)
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 3 - 26
Aptech Ltd
Java SE 7 Programming 3 - 27
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 3 - 28
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Objectives
following:
Use access levels: private, protected, default, and
public.
Override methods
Overload constructors and other methods appropriately
Use the instanceof operator to compare object types
Use virtual method invocation a
Use upward and downward casts ) has
l c om e
Override methods from the
m ai uid
Object class to improve @ g t G
h e n
the functionality of your class arg tud y v sS
n
fin e thi
(
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 4 - 2
Aptech Ltd
You have seen the keywords public and private. There are
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Yes Yes s a
default
)h a
Yes Yes Yes *
m
co e
protected
i l
public Yes Yes Yes gm t GYes
a uid
r g h@ den
Classes can be default (no modifier)nyorva public. S tu
( fin e this
E SEand/ort o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
The access modifier
I L IP blshown
keywords e in this table are private, protected, and public.
PHis absent,
When a keyword f a
er the default access modifier is applied.
Y s
an provides the greatest control over access to fields and methods.
N -keyword
The private
I N
F private, t r
With
non 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
Aptech Ltd
1 package demo;
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
1 package test;
2 import demo.Foo;
3 public class Bar extends Foo {
a
4 private int sum = 10;
) has
5 public void reportSum () {
l c om e
6 sum += result;
m ai uid
@ g t G
7 sum += other; compiler
h n
error
8 } v a rg tude
y S
9 } if nn this
S E ( use
H EOracle and/or
Copyright 2012, toits affiliates. All rights reserved.
G s e
V AR licen
In this example, there
I L IP le in two packages. Class Foo is in the package demo,
are twobclasses
and declares Pa data
a
H fieldfecalled
r result with a protected access modifier.
Y
N Bar, s
an extends Foo, there is a method, reportSum, that adds the value of
In theN
I class
F ntoosum. - t rwhich
n The method then attempts to add the value of other to sum. The field
result
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
Aptech Ltd
1 package demo;
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
1 package test;
2 import demo.Foo2;
3 public class Bar2 extends Foo2 {
4 private int sum = 10;
result field shadows as
a
)h
5 private int result = 30;
the parent's field.
m
6 public void reportSum() {
i l co e
7 sum += result;
g ma Guid
8 }
g h @ ent
9 } var tud y is S
f i n n th
( e
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
In this example, the I L IP Foo2
class b ledeclares the field result. However, the class Bar2 declares
PH sThe
its own field result. f a
erconsequence is that the field result from class Foo2 is
shadowed Y
N by the r n result in class Bar2. What is sum in this example? sum is now 40
afield
(10 I N - t
F+ 30).noModern
n 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
Aptech Ltd
1 package test;
s a
2 import demo.Foo3;
)h a
3 public class Bar3 extends Foo3 {
m
co e
4 private int sum = 10; i l
5 public void reportSum() {
g ma Guid
6 sum += getResult();
g h @ ent
7 }
y v ar Stud
8 }
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
L IP of btheleexample using the protected keyword is shown in the
A slightly modifiedIversion
P
slide. If the idea His to limit
f e ra of the field result to classes within the package and the
access
subclasses
N N t r a ns
Y(package-protected), you should make the access explicit by defining a method
I -
F nonwritten for package and subclass-level access.
purposefully
Java SE 7 Programming 4 - 6
Aptech Ltd
Overriding Methods
V AR licen
Although the Employee I L IP classbhasle getters to return values for a print statement, it might be
H method
nice to have aPutility f a
er to get specific details about the employee. Consider a method
Y
added toNthe Employee
s
an class to print details about the Employee object.
I N - t r
In F
addition
n otonadding 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
Aptech Ltd
Overriding Methods
V AR licen
L IP bitlereplaces the method in the superclass (parent) class.
When a method isIoverridden,
P ra Manager instance.
H forfeany
This method
N Y rans
is called
N
I onform
A call
F of the -t super.getDetails() invokes the getDetails method of the parent
class. n
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
Aptech Ltd
V AR licen
During run time, theI L IP Virtual
Java b leMachine invokes the getDetails method of the
PH If you
appropriate class. f r a
ecomment out the getDetails method in the Manager class shown
Y
N -tra
in the previous slide,n s
what happens when m.getDetails()is invoked?
I N
F nRecall
Answer: on 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
Aptech Ltd
V AR licen
L
Compiler Versus IRuntimeIP Behavior
b le
H to remember
Pthing f er a
The important
N Y a n s is the difference between the compiler (which checks that
eachIN
F method
behavior o n -tr fieldwith
and
associated
is accessible based on the strict definition of the class) and the
an object determined at run time.
n
This distinction is an important and powerful aspect of polymorphism: The behavior of an
object is determined by its runtime reference.
Because the object you created was a Manager object, at run time, when the getDetails
method was invoked, the run time reference is to the getDetails method of a Manager
class, even though the variable e is of the type Employee.
This behavior is referred to as virtual method invocation.
Note: If you are a C++ programmer, you get this behavior in C++ only if you mark the method
using the C++ keyword virtual.
Java SE 7 Programming 4 - 10
Aptech Ltd
V AR licen
To override a method,
I L IPthe nameb leand the order of arguments must be identical.
PHis a subclass
f a
er overrides a method in the parent class, it must provide the
When a method
Y s
an than the parent class. For example, if the parent method getDetails()
sameI orN
N greater
- t r
access
onFthe slide
n n protected, then the overriding method getDetails() in the subclass must be
owas
protected or public.
Java SE 7 Programming 4 - 11
Aptech Ltd
Applying Polymorphism
V AR licen
Design Problem ILI
P ble
P H in fthe
e a
rexample
N Y rans
What is the problem in the slide? Each method performs the calculation
F INon the
based
o n -t of employee passed in, and returns the number of shares.
type
Considernwhat 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
Aptech Ltd
Applying Polymorphism
V AR licen
Use the Most GenericI L IPFormble
P His to design
f e raand write methods that take the most generic form of your object
Y rans
A good practice
N
N
I on-t
as possible.
F n Employee is a good base class to start from.
In this case,
Java SE 7 Programming 4 - 13
Aptech Ltd
Applying Polymorphism
V AR licen
L IP ble
In this modified EmployeeStockPlan,
I the grantStock method calls a method defined by
the base class, H
PEmployee, r a
fe that returns a base stock count. The EmployeeStockPlan class
Y
N -tra
uses a multiplier to n s
determine how many stocks to grant. A class may override the
I N
F non method (as the Manager class does here) based on business policy.
calculateStock
In this approach, regardless of the number of different Employee types (all extending the
Employee object) the EmployeeStockPlan class will always function.
Java SE 7 Programming 4 - 14
Aptech Ltd
V AR licen
L IP EmployeeRequisition
In this example, a Iclass, b le has a method that uses the instanceof
H
P siffthe
keyword to determine r a
e object can open an requisition for an employee. Per the business
Y
N -tra
policy, only Managersn and above can open a requisition for a new employee.
I
F nonN
Java SE 7 Programming 4 - 15
Aptech Ltd
V AR licen
Although a genericIL IP blreference
superclass e is useful for passing objects around, you may need
to use a method H
P fromsthe r a
fesubclass.
In theN
Y
slide, ra n
N for-texample, you need the setDeptName method of the Manager class. To
F I
satisfy the n
ocompiler, you can cast a reference from the generic superclass to the specific
class.
n
However, there are rules for casting references. You see these in the next slide.
Note: The instanceof operator shown on the slide is not required by the compiler before
the cast, however, without checking the object's type, if a non-Manager object type is passed
to the modifyDeptForManager method, an exception (ClassCastException) will be
thrown at runtime.
Java SE 7 Programming 4 - 16
Aptech Ltd
Casting Rules
operator.
Director d = new Director();
Manager m = new Manager();
Employee e = m; // OK
s a
Employee e = d; // OK
)h a
m
co e
Manager m = d; // OK i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 4 - 17
Aptech Ltd
Casting Rules
Manager m = (Manager)e;
// Would also work if
// e was a Director obj
s a
)h a
Engineer eng = c(Engineer)m; m
o e
Director d = (Director)m;
// compileraerroruid i l
gm t G
// fails at run time
@
gh tuden
a
v sS r
n y
( fin e thi
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Downward Casts ILI
P ble
P Hcast, fthe
e racompiler simply determines if the cast is possible; if the cast down
ansit is possible that the cast will succeed.
With a downward
NY -trthen
is to IaNsubclass,
F
Note thatnat
n time the cast results in a java.lang.ClassCastException if the object
orun
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 - 18
Aptech Ltd
is equivalent to:
public class Employee extends Object { //... }
s a
)h a
The root class contains several non-final methods, obut m
there are three that are important to consider overriding: a ilc ide
m u
toString, equals, and hashCode h@g nt G
v a rg tude
n n y is S
( f i e th
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I
Best Practice: OverloadL IP Object
b le Methods
a
PH sferclass is the root class of all classes in the Java programming
The java.lang.Object
Y
N
language.
I - t r an will subclass Object by default.
N All classes
F defines
Object n on 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.
Java SE 7 Programming 4 - 19
Aptech Ltd
V AR licen
The println method I L IPis overloaded
b le with a number of parameter types. When you invoke
a
PH sfer the method that takes an Object parameter is matched and
System.out.println(e);
Y
invoked.NThis method
r an in turn invokes the toString() method on the object instance.
I N
F Sometimes - t
Note: n on 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 - 20
Aptech Ltd
V AR licen
The equals method I L IofPObjectb ledetermines (by default) only if the values of two object
PHto thesfsame
references point
a
er object. Basically, the test in the Object class is simply as
follows:N Y r an
I N - t
F Ifnxo==ny, 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 - 21
Aptech Ltd
V AR licen
This simple equals I L IP firstbtests
test le to make sure that the object passed in is not null, and then
tests to makePsure
a
H that fiteisr an instance of an Employee class (all subclasses are also
N N
employees, Yso this
t r a ns Then the Object is cast to Employee, and each field in
works).
FI noisnchecked
Employee - 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 - 22
Aptech Ltd
The general contract for Object states that if two objects are
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
V AR licen
Overriding hashCode I L IP ble
P H fefor rathe Object class states:
Y rans
The Java documentation
N
"...
F N n -t necessary to override the hashCode method whenever this method
ItI is generally
o
[equals]nis 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 - 23
Aptech Ltd
Summary
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 4 - 24
Aptech Ltd
Quiz
V AR licen
Answer: e I L IP ble
P H feclass ra extends Account, the withdraw method declared in
Because the
N N Yoverrides
Checking
t r a nsthe withdraw method in Account. At run time, the method for the
FI (Checking)
Checking
object
-
non is executed.
Java SE 7 Programming 4 - 25
Aptech Ltd
Quiz
a. True
b. False
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Answer: a I L IP ble
P ra
Halso anfeinstanceof
N Y rans
Actually, acct is the Account class.
FIN non-t
Java SE 7 Programming 4 - 26
Aptech Ltd
Quiz
V AR licen
Answer: b I L IP ble
P Hassume f e a
rthat
The compiler
N Y will
a n s it is possible to cast an Account type object to another
Account.
However, nrun-trtime,Savings
FIN natoBecause extends from Account, this looks like a typical downward cast.
the true type of the object is determined, and you cannot cast between
children.
Java SE 7 Programming 4 - 27
Aptech Ltd
Quiz
1 package com.bank;
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
10 package com.bank.type;
11 import com.bank.Account;
12 public class Savings extends Account {
13 private double interest;
14 Account acct = new Account();
15 public double getBalance (){ return (interest + balance); }
16 }
V AR licen
Answer: b I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 4 - 28
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 4 - 29
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SE to us
R GH nse
V A lice
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Objectives
following:
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 a
s
Distinguish between top-level and nested classes ) ha
l c om e
m ai uid
@ g t G
h n
v a rg tude
n n y is S
( f i e th
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 2
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v a r
S t ud
Class InheritancenDiagram
( fin e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Class InheritanceILI
P ble
P f e ra
Han object-oriented
N Y rans
When designing solution, you should attempt to avoid code duplication.
N n-tot avoid duplication is to create library methods and classes. Libraries function
OneItechnique
asF nopoint to contain often reused code. Another technique to avoid code duplication is
a central
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
Aptech Ltd
Enabling Generalization
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L
Coding for Generalization IP ble
P H f e ra reference type possible. Java IDEs may contain refactoring tools
Always use
N
the most
NYin changing
that Iassist t r a nsexisting references to a more generic base type.
generic
F non-
Java SE 7 Programming 5 - 4
Aptech Ltd
@ g t
g h e n
}
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L
Method ImplementationsIP ble
P H have f e raa common method, it is typically placed in a parent class. Under
N Y rans
When sibling classes
some N n-ta specialized
circumstances,
FI nowith however, the parent class's implementation will always need to be
overridden 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
Aptech Ltd
class-level modifier.
V AR licen
Declaring a class as
I L IP bprevents
abstract le any instances of that class from being created. It is a
compile-time P
error f a
H to instantiate
er an abstract class. An abstract class will typically be extended
Y s
anmay be used as a reference type.
Nclass-tand
by a child
I N
F non r
Java SE 7 Programming 5 - 6
Aptech Ltd
method-level modifier.
An abstract method: s a
)h a
Cannot have a method body m
Must be declared in an abstract class i l co e
g ma Guid
Is overridden in subclasses
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Inheriting AbstractI L IP ble
Methods
P H inherits
f e raan abstract method, it is inheriting a method signature but no
N Y rans
When a child class
N
I on-t For this reason, no braces are allowed when defining an abstract method.
implementation.
AnFabstract
n method is a way to guarantee that any child class will contain a method with a
matching signature.
Java SE 7 Programming 5 - 7
Aptech Ltd
V AR licen
Making Use of Abstract I L IP Classes
b le
PH tosavoid f a
er implementing an abstract method by declaring child classes as
While it is Y
possible
N Nthis only
abstract, t r n to delay the inevitable. Applications require non-abstract methods to
aserves
I
F objects. -
create non Use abstract methods to outline functionality required in child classes.
Java SE 7 Programming 5 - 8
Aptech Ltd
Quiz
a. A return value
b. A method implementation
c. Method parameters
d. private access
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Answer: b, d I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 9
Aptech Ltd
static Keyword
V AR licen
I
Java: Object-orientedL IPby Design
b le
PH sflanguage
er a
The Java programming
Y was designed as an object-oriented language, unlike
N tr a n
FIN nolike
languages
developing
-Objective-C and C++, which inherited the procedural design of C. When
innJava, you should always attempt to design an object-oriented solution.
Java SE 7 Programming 5 - 10
Aptech Ltd
Static Methods
Static methods are methods that can be called even if the class
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
V AR licen
Factory Methods ILI
P ble
PH invoking f e raconstructors, you will often use static methods to retrieve object
In place ofY
N directly
a s
nsomething
N
references. t
Unless
FI noisncalled.
- r unexpected happens, a new object is created whenever a
constructor 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
Aptech Ltd
private int x;
V AR licen
I L IP ble
Static Method Limitations
P H be used
f e rabefore any instances of their enclosing class have been created.
N Y rans
Static methods can
N -tspeaking,
Chronologically
FIoccurrences
n this means that in a running Java Virtual Machine, there may not be
any n o of the containing classes instance variables. Static methods can never
access their enclosing classes instance variables or call their non-static methods.
Java SE 7 Programming 5 - 12
Aptech Ltd
double d = Math.random();
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
StaticUtilityClass.printMessage();
StaticUtilityClass uc = new StaticUtilityClass();
uc.printMessage(); // works but misleading
sameClassMethod();
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 13
Aptech Ltd
Static Variables
V AR licen
Class Loading ILI
P ble
PH sfera classes are typically loaded on demand (first use). Static
ApplicationYdeveloper-supplied
N
variables
I - t r an when their enclosing class is loaded. An attempt to access a static
Nare initialized
F member
class non can trigger the loading of a class.
Java SE 7 Programming 5 - 14
Aptech Ltd
public StaticCounter() {
Only one copy in
counter++; memory
}
V AR licen
I L IP ble
Persisting Static Variables
P H thatfare
e raused to persist application state in Java only save instance
Y rans
Many technologies
N
N
variables. -t variables.
FI nMaintaining a single object that keeps track of shared state may be used as an
alternativeotonstatic
Java SE 7 Programming 5 - 15
Aptech Ltd
double p = Math.PI;
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
new StaticCounter();
new StaticCounter();
System.out.println("count: " + StaticCounter.getCount());
V AR licen
Object References I L IPStaticblMembers
to e
H references
Pobject f a
er to static methods should be avoided, you should also avoid
Just as using
Y
N references s
an to access static variables. If all the members of a class are static,
using
I N
object
F nusing - t r
consider on a private constructor to prevent object instantiation.
Java SE 7 Programming 5 - 16
Aptech Ltd
Static Imports
V AR licen
L
Overusing static import
I IPcan negatively
b le affect the readability of your code. Avoid adding
multiple staticP
imports
a
H tofearclass.
N N Y
t r a ns
FI non-
Java SE 7 Programming 5 - 17
Aptech Ltd
Quiz
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Answer: b I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 18
Aptech Ltd
Final Methods
overridden.
public class MethodParentClass {
public final void printMessage() {
System.out.println("This is a final method");
}
}
V AR licen
Performance Myths I L IP ble
P H f e ra benefit when you declare a method as final. Methods should
N Y rans
There is little to no performance
N
FI nonas-tfinal only to disable method overriding.
be declared
Java SE 7 Programming 5 - 19
Aptech Ltd
Final Classes
extended.
public final class FinalParentClass { }
// compile-time error
public class ChildClass extends FinalParentClass { }
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 20
Aptech Ltd
Final Variables
may not change their values after they are initialized. Final
variables can be:
Class fields
Final fields with compile-time constant expressions are
constant variables.
Static can be combined with final to create an always-
available, never-changing variable.
Method parameters a
) has
Local variables
l c om e
Note: Final references must always reference the m ai uobject,
same id
g G
h@ ent
but the contents of that object may be modified.
rg tud
v
y is S a
f i n n th
( e
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I
Benefits and Drawbacks L IP ofbFinal
le Variables
PH sfer a
Bug Prevention
Y
I
Final N N -can
variables t r annever have their values modified after they are initialized. This behavior
F ona bug-prevention mechanism.
functionsnas
Thread Safety
The immutable nature of final variables eliminates any of the concerns that come with
concurrent access by multiple threads.
Final Reference to Objects
A final object reference only serves to prevent a reference from pointing to another object.
If you are 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 reference.
Maintaining an object's references prevents that object from being available for garbage
collection.
Java SE 7 Programming 5 - 21
Aptech Ltd
public VariableExampleClass() {
field = 100;
// compile-time error forgottenField
// not initialized
}
V AR licen
Final Fields I L IP ble
InitializingY P
H fera
N N t r a ns
FI fields
Final
n o n-
(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
Aptech Ltd
Quiz
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Answer: a I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 23
Aptech Ltd
@ entg
g h
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I
Runtime Range Checking L IP ble
P Hthe slide,
f e rayou must perform a runtime range check when using an int to
In the example
N N
represent state.
in
Y Within
t r a ns the setState method, an if statement can be used to validate that
FIthe nvalues
only on- 0, 1, or 2 are accepted. This type of check is performed every time the
setState method is called, resulting in additional overhead.
Java SE 7 Programming 5 - 24
Aptech Ltd
Typesafe Enumerations
}
s a
)h a
An enum can be used in the following way: m
i l co e
Computer comp = new Computer();
m a u id
comp.setState(PowerState.SUSPEND); @ g
This method G
t reference
takes a
g h d e n .
a
v s Str PowerState
u
n y
( fin e thi
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Compile-Time Range I L IPChecking
b le
PinHthe sslide,
f a
er the compiler performs a compile-time check to ensure that only
In the example
Y
validIN N -traninstances are passed to the setState method. No range checking
PowerState
F nisoincurred
overhead n at run time.
Java SE 7 Programming 5 - 25
Aptech Ltd
Enum Usage
V AR licen
Note: When an enum I L IP
is usedbinle a switch statement, only the enum constants can be used
H fe r a
P casesstatements.
as labels for the
N Y a n
FIN non-tr
Java SE 7 Programming 5 - 26
Aptech Ltd
Complex Enums
V AR licen
Enum Constructors I L IP ble
P H feanraenum instance with new.
N Y rans
You may not instantiate
N
FI non-t
Java SE 7 Programming 5 - 27
Aptech Ltd
Quiz
levels:
a. public
b. protected
c. Default (no declared access level)
d. private
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Answer: c, d I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 28
Aptech Ltd
Design Patterns
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L
Design Pattern Catalogs IP ble
P f e ra for many programming languages. Most of the traditional
Hare available
Y rans
Pattern catalogs
N
N
design patterns
FI Design n tapply to any object-oriented programming language. One of the most popular
-Patterns:
books, n o Elements of Reusable Object-Oriented Software, uses a combination
of C++, Smalltalk, and diagrams to show possible pattern implementations. Many Java
developers still reference this book because the concepts translate to any object-oriented
language.
You learn more about design patterns and other Java best practices in the Java Design
Patterns course.
Java SE 7 Programming 5 - 29
Aptech Ltd
Singleton Pattern
2 private SingletonClass() {}
V AR licen
Implementing theIL IP blPattern
Singleton e
H pattern
Pdesign f a
er is one of the creational design patterns that are categorized in
The singleton
N Y an s
Design
F I N Patterns:
n - t rElements of Reusable Object-Oriented Software.
o
n the singleton design pattern:
To implement
1. Use a static reference to point to the single instance. Making the reference final ensures
that it will never reference a different instance.
2. Add a single private constructor to the singleton class. The private modifier allows only
"same class" access, which prohibits any attempts to instantiate the singleton class
except for the attempt in step 1.
3. A public factory method returns a copy of the singleton reference. This method is
declared static to access the static field declared in step 1. Step 1 could use a public
variable, eliminating the need for the factory method. Factory methods provide greater
flexibility (for example, implementing a per-thread singleton solution) and are typically
used in most singleton implementations.
To obtain a singleton reference, call the getInstance method:
SingletonClass ref = SingletonClass.getInstance();
Java SE 7 Programming 5 - 30
Aptech Ltd
Nested Classes
V AR licen
Reasons to Use NestedI L IP Classes
b le
a
H feisr taken from
Pinformation
The following
N N Y
t r a ns
http://download.oracle.com/javase/tutorial/java/javaOO/nested.html.
F I on-
Logical nGrouping 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 private. By hiding class B within class A, A's members can be declared
private and B can access them. In addition, B itself can be hidden from the outside world.
More Readable, Maintainable Code
Nesting small classes within top-level classes places the code closer to where it is used.
Java SE 7 Programming 5 - 31
Aptech Ltd
@ entg
g h
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Inner Classes Versus I L IPStaticblNested
e Classes
P H e r a
An inner class
N a n sf part of the outer class and inherits access to all the private
Y isrconsidered
FIN nclass.
members
member
of thetouter class. The example in the slide shows an inner class, which is a
on-Inner classes can also be declared inside a method block (local classes).
A static nested class is not an inner class, but its declaration appears similar with an
additional static modifier on the nested class. Static nested classes can be instantiated
before the enclosing outer class and, therefore, are denied access to all non-static members
of the enclosing class.
Java SE 7 Programming 5 - 32
Aptech Ltd
V AR licen
A Class with No Name I L IP ble
P Hthe slide,
f e rathe java.lang.Object class is being subclassed, and it is that
N Y rans
In the example in
N
subclass
nis-tbeingclass
that
FI na oseparate instantiated. When you compile an application with anonymous
classes, file following a naming convention of Outer$1.class will be
generated, where 1 is the index number of anonymous classes in an enclosing class and
Outer is the name of the enclosing class.
Anonymous inner classes can also be local classes.
Java SE 7 Programming 5 - 33
Aptech Ltd
Quiz
a. anonymous
b. local
c. static
d. member
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
Answer: a, b, d ILI
P ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 34
Aptech Ltd
Summary
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 35
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 36
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 37
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 38
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SEand/or
t o
s
uaffiliates.
G H se
Copyright 2012, Oracle its All rights reserved.
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 5 - 39
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SE to us
R GH nse
V A lice
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Objectives
following:
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 a
as
m )h
i l co e
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 6 - 2
Aptech Ltd
Implementation Substitution
Java SE 7 Programming 6 - 3
Aptech Ltd
Java Interfaces
Java SE 7 Programming 6 - 4
Aptech Ltd
Java SE 7 Programming 6 - 5
Aptech Ltd
Constant Fields
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Only constant fieldsIare L IPpermitted
b lein an interface. When you declare a field in an interface, it is
PHstatic,
implicitly public, f a
erand final. You may redundantly specify these modifiers. Avoid
groupingN Y s
an values for an application in a single interface; good design distributes the
all the constant
I
constantN values - t r
F non an application across many classes and interfaces. Creating monolithic classes
of
or interfaces that contain large groupings of unrelated code does not follow best practices for
object-oriented design.
Java SE 7 Programming 6 - 6
Aptech Ltd
Interface References
Java SE 7 Programming 6 - 7
Aptech Ltd
instanceof Operator
Implements
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
Television is an instance of an ElectronicDevice.
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Previously, you used
I L IP ble on class types. Any type that can be used as a reference can
instanceof
be used as an P H forfethe
operand ra instanceof operator. In the slide, a Television implements
N Y ran.sTherefore, a Television is an instance of a Television, an
ElectronicDevice
N
FI non-t and a java.lang.Object.
ElectronicDevice,
Java SE 7 Programming 6 - 8
Aptech Ltd
Marker Interfaces
Java SE 7 Programming 6 - 9
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Casting GuidelinesILIP b le
a
H fer to class types, if you cast to a type that is invalid for that object, your
Just as youYdoP s
when casting
N N
application t r
generatesa nan exception and is even likely to crash. To verify that a cast will succeed,
F I
you should o n -
n 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
Aptech Ltd
Java SE 7 Programming 6 - 11
Aptech Ltd
interface:
public class AmphibiousCar extends BasicCar implements
MotorizedBoat { }
Java SE 7 Programming 6 - 12
Aptech Ltd
Extending Interfaces
Java SE 7 Programming 6 - 13
Aptech Ltd
s a
)h a
m
co e
i l
ma Guid
Extends Implements
g
@ ent
g h
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Interface Inheritances I L IP ble
P e raof inheritance that is referred to as interface inheritance. Java allows
H for afform
Interfaces are
N
multiple N
used
interface t a ns but only single class inheritance.
Y rinheritance
FI noannImplementing
Extending
-
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
Aptech Ltd
Quiz
a. True
b. False
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Answer: a I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 6 - 15
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I
Object-Oriented Design L IP Principles
b le
a
H fenotr an implementation is a practice that was popularized in the book
Program toYanP
DesignN N
Patterns:t r a ns of Reusable Object-Oriented Software.
interface,
Elements
FI nonmore
You can learn
-
about object-oriented design principles and design patterns in the Java
Design Patterns course.
Java SE 7 Programming 6 - 16
Aptech Ltd
DAO Pattern
Java SE 7 Programming 6 - 17
Aptech Ltd
methods.
s a
)h a
m
co e
i l
g ma Guid
Before the DAO pattern gh@ den
t
y v ar Stu
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
The Single-ResponsibilityI L IP Principle
b le
H shown
Pclass f a
er in the slide has methods that focus on two different principles or
The Employee
Y
NOne set s
aofnmethods focuses on manipulating the representation of a person, and the
I N
concerns.
F dealsnowith - t r
n persisting Employee objects. Because these two sets of responsibilities may be
other
modified at different points in the lifetime of your applications, it makes sense to split them up into
different classes.
Java SE 7 Programming 6 - 18
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
After refactoring to the DAO y v ar Stud
pattern
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
DAO Implementations I L IP ble
H feneed
thatPyou might
ra to change your DAO implementation at a later time to use a
If you think Y
N a s
nmechanism,
F I N
different
n - t
persistence r it is best to use an interface to define the contract that all DAO
no must meet.
implementations
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
Aptech Ltd
Java SE 7 Programming 6 - 20
Aptech Ltd
The EmployeeDAO
implementation is hidden.
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L
This pattern eliminates
I P constructor
Idirect b le calls in favor of invoking a method. A factory is often
H r a
P sfethe DAO pattern.
used when implementing
In the N
Y
N -intrthe
example anslide, you have no idea what type of persistence mechanism is used by
I
F non because it is just an interface. The factory could return a DAO implementation that
EmployeeDAO
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
Aptech Ltd
The Factory
Java SE 7 Programming 6 - 22
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
Clients depending only on abstract
y v ar DAOs S tud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 6 - 23
Aptech Ltd
Quiz
a. True
b. False
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Answer: a I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 6 - 24
Aptech Ltd
Code Reuse
problems. You do not want to fix the same bug multiple times.
Dont repeat yourself! (DRY principle)
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
a
types of objects together (composition). as )h
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Copying and pasting I L IP is notblsomething
code e that must always be avoided. If duplicated code
H pointfe r a
Y Plines
serves as a starting and is heavily modified, that may be an acceptable situation for you to
copy andN paste a n
of
scode. You should be aware of how much copying and pasting is occurring
IN oBesides
in aFproject. - t r
n n
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
Aptech Ltd
Design Difficulties
Class inheritance allows for code reuse but is not very modular
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g m a
G uid
Method implementations located across different
h @ e n t
classes
g
ar Stud
y v
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
Limitations with Inheritance
P ra inheritance, which eliminates the possibility of inheriting different
Hsinglefeclass
Java supports
N
only s
Y ofraanmethod
F I N
implementations
n - t with the same signature. Multiple interface inheritance does not pose
no as class inheritance because there can be no conflicting method
the same problem
implementations in interfaces.
Java SE 7 Programming 6 - 26
Aptech Ltd
Composition
s a
)h a
m
co e
i l
Combining multiple classes' methods g ma Guid
through composition and forwardingrgh
@ ent
y v a Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Delegation I L IP ble
P Hand method
f e ra forwarding are two terms that are often used interchangeably.
Method delegation
N Y raisnwhen s
Method
F I N n - t
forwarding you write a method that does nothing except pass execution over to
no In some cases, delegation may imply more than simple forwarding. For more on
another method.
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
Aptech Ltd
Composition Implementation
s a
// other forwarded methods
)h a
} m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP ble Composition Easy
IDE Wizards Make IImplementing
P H fewith ra the NetBeans IDE, use the Insert Code tool as follows:
ansthe braces of the complex class and choose "Insert Code.
To implement composition
N NY -twithin
1. IRight-click r
F non
2. Select "Delegate Method.
The Generate Delegate Methods dialog box appears.
3. Select the method calls that you want to forward.
The methods are inserted for you.
Repeat these steps for each delegate class.
Java SE 7 Programming 6 - 28
Aptech Ltd
s a
)h a
m
co e
A complex car object that cannot be passed i l
to a method expecting a simple car g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Code Reuse I L IP ble
P Hthe addCar
f e ramethod for any type of Car, no matter how complex, is another form
The ability to
N
of code N
reuse.
use
t ns currently say the following:
Y Weracannot
FI non-SpyCarWithSunRoof());
addCar(new
Java SE 7 Programming 6 - 29
Aptech Ltd
s a
)h a
m
co e
i l
g m a
G uid
Composition with interfaces to
g h @ ent
support polymorphism
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Each delegate classIL IPyou use
that b lein a composition should have an interface defined. When
PH sclass,
creating the composing f a
er you declare that it implements all of the delegate interface types.
By doingN Y an an object that is a composition of other objects and has many types.
this, you create
r
I N
F we can n - t
Now
n osay:
addCar(new SpyCarWithSunRoof());
Java SE 7 Programming 6 - 30
Aptech Ltd
Quiz
a. Polymorphism
b. Composition
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Answer: b I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 6 - 31
Aptech Ltd
Summary
Java SE 7 Programming 6 - 32
Aptech Ltd
Writing an interface
Implementing an interface
Creating references of an interface type
Casting to interface types
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 6 - 33
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 6 - 34
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 6 - 35
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SE to us
R GH nse
V A lice
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Objectives
Java SE 7 Programming 7 - 2
Aptech Ltd
Generics
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 7 - 3
Aptech Ltd
Java SE 7 Programming 7 - 4
Aptech Ltd
2
3 private T t;
4
5 public void add(T t){
6 this.t = t;
7 }
8
9 public T get(){
s a
10 return this.t;
)h a
11 } m
co e
i l
12 }
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L
To create a genericIversionIP of theb leCacheAny class, a variable named T is added to the class
PH bysfangle
definition surrounded a
er brackets. In this case, T stands for type and can represent any
type. As N Y
the example
r nshows, the code has changed to use t instead of a specific type information.
athe
I N
F non
This change - t
allows 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
Aptech Ltd
Generics in Action
alternatives.
Java SE 7 Programming 7 - 6
Aptech Ltd
Syntax
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
//Generics
)h a
CacheAny<String> myMessage = new CacheAny<>();
m
co e
} i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP is ba lnew
The type inference diamond
I e feature in JDK 7. In the generic code, notice how the
right-side type P H fisealways
definition
a
r equivalent to the left-side type definition. In JDK 7, you can use
Y s
an that the right type definition is equivalent to the left. This helps to avoid
N to -indicate
the diamond
I
F non
typing N
redundantt r
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
Aptech Ltd
Quiz
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Answer: a I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 7 - 8
Aptech Ltd
Collections
of objects.
Objects in a collection are called elements.
Primitives are not allowed in a collection.
Various collection types implement many common data
structures:
Stack, queue, dynamic array, hash
The Collections API relies heavily
s a
on generics for its implementation. a
m )h
i l co e
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
A collection is a single
I L P that
Iobject b lemanages a group of objects. Objects in the collection are called
PHcollection
elements. Various f a
er types implement standard data structures including stacks, queues,
dynamic N Y
arrays, and
s
anhashes. All the collection objects have been optimized for use in Java
I N
F non
applications. - t r
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
Aptech Ltd
Collection Types
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IPshowsballlethe collection types that descend from Collection. Some
The diagram in the Islide
sample methodsP H e
are provided
f rafor both Collection and List. Note the use of generics.
N
Characteristics
N t ns
Y ofraImplementation Classes
F I n -
no A collection of elements that contains no duplicate elements
HashSet:
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
Aptech Ltd
List Interface
Java SE 7 Programming 7 - 11
Aptech Ltd
s a
List<Integer> partList = new ArrayList<>(3);
partList.add(new Integer(1111)); )h a
m
co e
partList.add(new Integer(2222));
i l
partList.add(new Integer(3333));
g ma Guid
partList.add(new Integer(4444)); // ArrayList auto grows
g h @ ent
y v ar Stud
System.out.println("First Part: " + partList.get(0)); // First item
finn e this
partList.add(0, new Integer(5555)); // Insert an item by index
E us(
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
An ArrayList implements
I L IP a Listb le collection. The implementation exhibits characteristics of a
PH array.
dynamically growing f a
erA to-do list application is a good example of an application that can
Y an s
N an -ArrayList.
benefit from
I N
F non t r
Java SE 7 Programming 7 - 12
Aptech Ltd
Java SE 7 Programming 7 - 13
Aptech Ltd
Generic ArrayList
Java SE 7 Programming 7 - 14
Aptech Ltd
Java SE 7 Programming 7 - 15
Aptech Ltd
Simplifies syntax
Produces cleaner, easier-to-read code
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 7 - 16
Aptech Ltd
Quiz
Java SE 7 Programming 7 - 17
Aptech Ltd
Set Interface
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
As an example, a set
I L IP be used
can b leto track a list of unique part numbers.
PH sfer a
Y
N -tran
I N
F non
Java SE 7 Programming 7 - 18
Aptech Ltd
E us(
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L
A set is a collection Iof P elements.
Iunique b le This example uses a TreeSet, which sorts the items in
PH issfrun,
the set. If the program
a
er the output is as follows:
Item:None
Y
N -tran
I
F three
Item: non
Item: two
Java SE 7 Programming 7 - 19
Aptech Ltd
Map Interface
Key Value
101 Blue Shirt
s a
102 Black Shirt )h a
m
co e
103 Gray Shirt i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP things
A Map is good for tracking
I b e part lists and their descriptions (as shown in the slide).
llike
PH sfer a
Y
N -tran
I N
F non
Java SE 7 Programming 7 - 20
Aptech Ltd
Map Types
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
The Map interface does
I L IPnot extend
b lethe Collection interface because it represents mappings
PH of objects.
and not a collection f a
er Some of the key implementation classes include:
Y
N -Atrmap
TreeMap:
s
an where the keys are automatically sorted
I N
F HashTable:
on A classic associative array implementation with keys and values. HashTable
n
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
Aptech Ltd
Java SE 7 Programming 7 - 22
Aptech Ltd
Deque Interface
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP of Collection
Deque is a child interface
I b le (just like Set and List).
H r a
e asynchronous message requests so they can be processed in
Pused tosftrack
A queue is often
AN
Y
stack can a n
FI non-tr
order.N be very useful for traversing a directory tree or similar structures.
Java SE 7 Programming 7 - 23
Aptech Ltd
Java SE 7 Programming 7 - 24
Aptech Ltd
Ordering Collections
sort collections.
Both are implemented using generics.
Using the Comparable interface:
Overrides the compareTo method
Provides only one sort option
Using the Comparator interface:
Is implemented by using the compare method
s a
Enables you to create multiple Comparator classes
)h a
Enables you to create and use numerous sorting loptions m
co e
i
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
The Collections APIIL IP two
provides b leinterfaces for ordering elements: Comparable and
Comparator. PH f er a
Y s
n is implemented in a class and provides a single sorting option for the
N -trainterface
The Comparable
I N
F non
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
Aptech Ltd
Comparable Interface
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
The slide shows how
I L IPComparableStudent
the b le class relates to the Comparable interface and
TreeSet. H
P sfe r a
Y
N -tran
I N
F non
Java SE 7 Programming 7 - 26
Aptech Ltd
Comparable: Example
Java SE 7 Programming 7 - 27
Aptech Ltd
for(ComparableStudent student:studentList){
System.out.println(student);
}
}
s a
}
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
In the example in the I L IP an bArrayList
slide, le of ComparableStudent elements is created. After
H
P sfe
the list is initialized, it is r
sorteda using the Comparable interface. The output of the program is as
follows: N Y r an
I N
F George - t
Name:
n on Washington ID: 3333 GPA:3.4
Name: John Adams ID: 2222 GPA:3.9
Name: Thomas Jefferson ID: 1111 GPA:3.8
Note: The ComparableStudent class has overridden the toString() method.
Java SE 7 Programming 7 - 28
Aptech Ltd
Comparator Interface
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
The slide shows twoIL IP bleclasses that can be used with the Student class. The
Comparator
example in theP
next ra how to use Comparator with an unsorted interface like
H slidefeshows
N Yby using
a s Collections utility class.
nthe
ArrayList
N
FI non- t r
Java SE 7 Programming 7 - 29
Aptech Ltd
Comparator: Example
Java SE 7 Programming 7 - 30
Aptech Ltd
Java SE 7 Programming 7 - 31
Aptech Ltd
Quiz
for a collection?
a. Comparable
b. Comparison
c. Comparator
d. Comparinator
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Answer: c I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 7 - 32
Aptech Ltd
Summary
Java SE 7 Programming 7 - 33
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 7 - 34
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 7 - 35
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 7 - 36
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
String Processing
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Sand/or
E
H se titsoaffiliates. All rights reserved.
Copyright 2012, Oracle
G
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Aptech Ltd
Objectives
Java SE 7 Programming 8 - 2
Aptech Ltd
Command-Line Arguments
arguments.
These string arguments are placed on the command line to
launch the Java interpreter after the class name:
java TestArgs arg1 arg2 "another arg"
Java SE 7 Programming 8 - 3
Aptech Ltd
Command-Line Arguments
Java SE 7 Programming 8 - 4
Aptech Ltd
Properties
Java SE 7 Programming 8 - 5
Aptech Ltd
Java SE 7 Programming 8 - 6
Aptech Ltd
line.
Use the D option to pass key-value pairs:
java Dpropertyname=value Dpropertyname=value myApp
s a
Get the Properties data from the System object: h a
String userName = System.getProperty("username"); o m )
a ilc ide
@ gm t Gu
a r gh tuden
n y v sS
( fin e thi
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Property informationIL IPalso beblpassed
can e on the command line. The advantage to passing
Hcommand
properties fromPthe f a
er line is simplicity. You do not have to open a file and read from it.
Y
However,Nif you have
s
anmore than a few parameters, a properties file is preferable.
I N
F non - t r
Java SE 7 Programming 8 - 7
Aptech Ltd
import java.io.PrintWriter;
Java SE 7 Programming 8 - 8
Aptech Ltd
printf format
E us(
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
You can perform theIL IP format
printf b le using both the String class and any output stream. The slide
shows several P H string
different f a
er formatting examples. See the Java API documentation for details
about allN Y
the options. an s
I N
F %s: String- t r
n on
%d: Decimal
%f: Float
The program output is the following:
We have 002 Blue Polo shirts that cost $24.99.
We have 002 Blue Polo shirts that cost $24.99.
We have 002 Blue Polo shirts that cost $24.99.
We have 002 Blue Polo shirts that cost $24.99.
Java SE 7 Programming 8 - 9
Aptech Ltd
Quiz
Java SE 7 Programming 8 - 10
Aptech Ltd
String Processing
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP covers
The first part of this Isection b lestring functions that are not regular expressions. When you
perform simpleP string f a
H manipulations,
er there are a number of very useful built-in methods.
N Y a n s
FIN non-tr
Java SE 7 Programming 8 - 11
Aptech Ltd
Java SE 7 Programming 8 - 12
Aptech Ltd
StringBuilder: Example
Java SE 7 Programming 8 - 13
Aptech Ltd
Java SE 7 Programming 8 - 14
Aptech Ltd
Java SE 7 Programming 8 - 15
Aptech Ltd
Java SE 7 Programming 8 - 16
Aptech Ltd
Scanner
A Scanner can tokenize a string or a stream.
1 public static void main(String[] args) {
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
2 Scanner s = null;
3 StringBuilder sb = new StringBuilder(64);
4 String line01 = "1.1, 2.2, 3.3";
5 float fsum = 0.0f;
6
7 s = new Scanner(line01).useDelimiter(", ");
8 try {
9 while (s.hasNextFloat()) {
10 float f = s.nextFloat();
11 fsum += f;
s a
12
13 }
sb.append(f).append(" ");
)h a
m
co e
14 System.out.println("Values found: " + sb.toString());
i l
15 System.out.println("FSum: " + fsum);
g ma Guid
16 } catch (Exception e) {
g h @ ent
17 System.out.println(e.getMessage());
y v ar Stud
finn e this
18 }
E us(
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
A Scanner can be Iused L IPto tokenize
b le an input stream or a string. In addition, a Scanner can be
used to tokenizePH numbers f a
r convert them into any primitive number type. Note how the
eand
Y
ScannerNis defined s
n line 7. The resulting object can be iterated over based on a specific type.
aon
I N
F non
In this case, a - t
float
r 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
Aptech Ltd
Regular Expressions
Java SE 7 Programming 8 - 18
Aptech Ltd
y v
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L
The Pattern and Matcher
I IP objects
b le work together to provide a complete solution.
The Pattern P object defines
a
H fer the regular expression that will be used for the search. As shown in
N Y
the example,
N r a
a regular
t nsexpression can be as simple as a word or phrase.
I on-
TheFMatcher
n 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
Aptech Ltd
Character Classes
Character Description
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 8 - 20
Aptech Ltd
Java SE 7 Programming 8 - 21
Aptech Ltd
Java SE 7 Programming 8 - 22
Aptech Ltd
Character Character
\d (digit) [0-9] \D [^0-9]
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
A number of character
I L P bareleused repeatedly. These classes are turned into predefined
Iclasses
P HClasses
character classes. f e a to identify digits, word characters, and white space.
rexist
N
White-Space
N t r a ns
Y Characters
I on-
\t:FTab character
n
\n: New-line character
\r: Carriage return
\f: Form feed
\x0B: Vertical tab
Java SE 7 Programming 8 - 23
Aptech Ltd
Java SE 7 Programming 8 - 24
Aptech Ltd
Quantifiers
Quantifier Description
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 8 - 25
Aptech Ltd
Quantifier: Examples
Java SE 7 Programming 8 - 26
Aptech Ltd
Greediness
characters as possible.
Use the ? operator to limit the search to the shortest
possible match.
Target String Longlonglong ago, in a galaxy far far away.
Java SE 7 Programming 8 - 27
Aptech Ltd
Quiz
more times?
a. *
b. +
c. .
d. ?
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Answer: b I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 8 - 28
Aptech Ltd
Boundary Matchers
Anchor Description
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Boundary characters
I L IPbe used
can b leto match different parts of a line.
PH sfer a
Y
N -tran
I N
F non
Java SE 7 Programming 8 - 29
Aptech Ltd
Boundary: Examples
Target String it was the best of times or it was the worst of times
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
Java SE 7 Programming 8 - 30
Aptech Ltd
Quiz
a. *
b. +
c. $
d. ^
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
Answer: c I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 8 - 31
Aptech Ltd
Pattern (\\S+?)\\.(\\S+?)@(\\S+)
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP you can
With regular expressions,
I b leuse parentheses to identify parts of a string to match. This
example matchesPHthe component
f a
er parts of an email address. Notice how each pair of parentheses
Y s
an expression, group(0) or group() matches all the text matched when
N In-atrregular
is numbered.
I N
F non
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
Aptech Ltd
Pattern p1 = Pattern.compile("h1");
Matcher m1 = p1.matcher(header);
if (m1.find()){
header = m1.replaceAll("p");
s a
System.out.println(header);
)h a
} m
co e
i l
ma Guid
}
} g
@ ent
g h
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
L IP bleby using the replaceAll method after performing a find.
You can do a search-and-replace
I
P H ferais as follows:
N Y rans
The output from the program
N
FI nonan
<p>This is -t H1</p>
Java SE 7 Programming 8 - 33
Aptech Ltd
Summary
Java SE 7 Programming 8 - 34
Aptech Ltd
parse text.
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 8 - 35
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 8 - 36
Aptech Ltd
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E us
Copyright 2012,H ESand/ortitsoaffiliates.
Oracle All rights reserved.
G s e
V AR licen
I L IP ble
P H fera
N Y rans
N
FI non-t
Java SE 7 Programming 8 - 37
Aptech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates
s a
)h a
m
co e
i l
g ma Guid
g h @ ent
y v ar Stud
( finn e this
E SE to us
R GH nse
V A lice
I L IP ble
P H fera
N Y rans
N
FI non-t