
- •Contents at a Glance
- •Contents
- •About the Authors
- •About the Technical Reviewer
- •Acknowledgments
- •Introduction
- •Oracle Java Certifications: Overview
- •FAQ 1. What are the different levels of Oracle Java certification exams?
- •FAQ 4. Is OCPJP 7 prerequisite for other Oracle certification exams?
- •FAQ 5. Should I take the OCPJP 7 or OCPJP 6 exam?
- •The OCPJP 7 Exam
- •FAQ 7. How many questions are there in the OCPJP 7 exam?
- •FAQ 8. What is the duration of the OCPJP 7 exam?
- •FAQ 9. What is the cost of the OCPJP 7 exam?
- •FAQ 10. What are the passing scores for the OCPJP 7 exam?
- •FAQ 11. What kinds of questions are asked in the OCPJP 7 exam?
- •FAQ 12. What does the OCPJP 7 exam test for?
- •FAQ 13. I’ve been a Java programmer for last five years. Do I have to prepare for the OCPJP 7 exam?
- •FAQ 14. How do I prepare for the OCPJP 7 exam?
- •FAQ 15. How do I know when I’m ready to take the OCPJP 7 exam?
- •Taking the OCPJP 7 Exam
- •FAQ 16. What are my options to register for the exam?
- •FAQ 17. How do I register for the exam, schedule a day and time for taking the exam, and appear for the exam?
- •The OCPJP 7 Exam: Pretest
- •Answers with Explanations
- •Post-Pretest Evaluation
- •Essentials of OOP
- •FunPaint Application: An Example
- •Foundations of OOP
- •Abstraction
- •Encapsulation
- •Inheritance
- •Polymorphism
- •Class Fundamentals
- •Object Creation
- •Constructors
- •Access Modifiers
- •Public Access Modifier
- •Private Access Modifier
- •Protected and Default Access Modifier
- •Overloading
- •Method Overloading
- •Constructor Overloading
- •Overload resolution
- •Points to Remember
- •Inheritance
- •Runtime Polymorphism
- •An Example
- •Overriding Issues
- •Overriding: Deeper Dive
- •Invoking Superclass Methods
- •Type Conversions
- •Upcasts and Downcasts
- •Casting Between Inconvertible Types
- •Using “instanceof” for Safe Downcasts
- •Java Packages
- •Working with Packages
- •Static Import
- •Summary
- •Abstract Classes
- •Points to Remember
- •Using the “final” Keyword
- •Final Classes
- •Final Methods and Variables
- •Points to Remember
- •Using the “static” Keyword
- •Static Block
- •Points to Remember
- •Flavors of Nested Classes
- •Static Nested Classes (or Interfaces)
- •Points to Remember
- •Inner Classes
- •Points to Remember
- •Local Inner Classes
- •Points to Remember
- •Anonymous Inner Classes
- •Points to Remember
- •Enum Data Types
- •Points to Remember
- •Summary
- •Interfaces
- •Declaring and Using Interfaces
- •Points to Remember
- •Abstract Classes vs. Interfaces
- •Choosing Between an Abstract Class and an Interface
- •Object Composition
- •Composition vs. Inheritance
- •Points to Remember
- •Design Patterns
- •The Singleton Design Pattern
- •Ensuring That Your Singleton Is Indeed a Singleton
- •The Factory Design Pattern
- •Differences Between Factory and Abstract Factory Design Patterns
- •The Data Access Object (DAO) Design Pattern
- •Points to Remember
- •Summary
- •Generics
- •Using Object Type and Type Safety
- •Using the Object Class vs. Generics
- •Container Implementation Using the Object Class
- •Container Implementation Using Generics
- •Creating Generic Classes
- •Diamond Syntax
- •Interoperability of Raw Types and Generic Types
- •Generic Methods
- •Generics and Subtyping
- •Wildcard Parameters
- •Limitations of Wildcards
- •Bounded Wildcards
- •Wildcards in the Collections Class
- •Points to Remember
- •The Collections Framework
- •Why Reusable Classes?
- •Basic Components of the Collections Framework
- •Abstract Classes and Interfaces
- •Concrete Classes
- •List Classes
- •ArrayList Class
- •The ListIterator Interface
- •The LinkedList Class
- •The Set Interface
- •The HashSet Class
- •The TreeSet Class
- •The Map Interface
- •The HashMap Class
- •Overriding the hashCode() Method
- •The NavigableMap Interface
- •The Queue Interface
- •The Deque Interface
- •Comparable and Comparator Interfaces
- •Algorithms (Collections Class)
- •The Arrays Class
- •Methods in the Arrays Class
- •Array as a List
- •Points to Remember
- •Summary
- •Generics
- •Collections Framework
- •Processing Strings
- •String Searching
- •The IndexOf() Method
- •The regionMatches() Method
- •String Parsing
- •String Conversions
- •The Split() Method
- •Regular Expressions
- •Understanding regex Symbols
- •Regex Support in Java
- •Searching and Parsing with regex
- •Replacing Strings with regex
- •String Formatting
- •Format Specifiers
- •Points to Remember
- •Summary
- •Reading and Writing from Console
- •Understanding the Console Class
- •Formatted I/O with the Console Class
- •Special Character Handling in the Console Class
- •Using Streams to Read and Write Files
- •Character Streams and Byte Streams
- •Character Streams
- •Reading Text Files
- •Reading and Writing Text Files
- •“Tokenizing” Text
- •Byte Streams
- •Reading a Byte Stream
- •Data Streams
- •Writing to and Reading from Object Streams: Serialization
- •Serialization: Some More Details
- •Points to Remember
- •Summary
- •A Quick History of I/O APIs
- •Using the Path Interface
- •Getting Path Information
- •Comparing Two Paths
- •Using the Files Class
- •Checking File Properties and Metadata
- •Copying a File
- •Moving a File
- •Deleting a File
- •Walking a File Tree
- •Revisiting File Copy
- •Finding a File
- •Watching a Directory for Changes
- •Points to Remember
- •Summary
- •Introduction to JDBC
- •The Architecture of JDBC
- •Two-Tier and Three-Tier JDBC Architecture
- •Types of JDBC Drivers
- •Setting Up the Database
- •Connecting to a Database Using a JDBC Driver
- •The Connection Interface
- •Connecting to the Database
- •Statement
- •ResultSet
- •Querying the Database
- •Updating the Database
- •Getting the Database Metadata
- •Points to Remember
- •Querying and Updating the Database
- •Performing Transactions
- •Rolling Back Database Operations
- •The RowSet Interface
- •Points to Remember
- •Summary
- •Define the Layout of the JDBC API
- •Connect to a Database by Using a JDBC driver
- •Update and Query a Database
- •Customize the Transaction Behavior of JDBC and Commit Transactions
- •Use the JDBC 4.1 RowSetProvider, RowSetFactory, and RowSet Interfaces
- •Introduction to Exception Handling
- •Throwing Exceptions
- •Unhandled Exceptions
- •Try and Catch Statements
- •Programmatically Accessing the Stack Trace
- •Multiple Catch Blocks
- •Multi-Catch Blocks
- •General Catch Handlers
- •Finally Blocks
- •Points to Remember
- •Try-with-Resources
- •Closing Multiple Resources
- •Points to Remember
- •Exception Types
- •The Exception Class
- •The RuntimeException Class
- •The Error Class
- •The Throws Clause
- •Method Overriding and the Throws Clause
- •Points to Remember
- •Custom Exceptions
- •Assertions
- •Assert Statement
- •How Not to Use Asserts
- •Summary
- •Introduction
- •Locales
- •The Locale Class
- •Getting Locale Details
- •Resource Bundles
- •Using PropertyResourceBundle
- •Using ListResourceBundle
- •Loading a Resource Bundle
- •Naming Convention for Resource Bundles
- •Formatting for Local Culture
- •The NumberFormat Class
- •The Currency Class
- •The DateFormat Class
- •The SimpleDateFormat Class
- •Points to Remember
- •Summary
- •Introduction to Concurrent Programming
- •Important Threading-Related Methods
- •Creating Threads
- •Extending the Thread Class
- •Implementing the Runnable Interface
- •The Start( ) and Run( ) Methods
- •Thread Name, Priority, and Group
- •Using the Thread.sleep() Method
- •Using Thread’s Join Method
- •Asynchronous Execution
- •The States of a Thread
- •Two States in “Runnable” State
- •Concurrent Access Problems
- •Data Races
- •Thread Synchronization
- •Synchronized Blocks
- •Synchronized Methods
- •Synchronized Blocks vs. Synchronized Methods
- •Deadlocks
- •Other Threading Problems
- •Livelocks
- •Lock Starvation
- •The Wait/Notify Mechanism
- •Let’s Solve a Problem
- •More Thread States
- •timed_waiting and blocked States
- •waiting State
- •Using Thread.State enum
- •Understanding IllegalThreadStateException
- •Summary
- •Using java.util.concurrent Collections
- •Semaphore
- •CountDownLatch
- •Exchanger
- •CyclicBarrier
- •Phaser
- •Concurrent Collections
- •Apply Atomic Variables and Locks
- •Atomic Variables
- •Locks
- •Conditions
- •Multiple Conditions on a Lock
- •Use Executors and ThreadPools
- •Executor
- •Callable, Executors, ExecutorService, ThreadPool, and Future
- •ThreadFactory
- •The ThreadLocalRandom Class
- •TimeUnit Enumeration
- •Use the Parallel Fork/Join Framework
- •Useful Classes of the Fork/Join Framework
- •Using the Fork/Join Framework
- •Points to Remember
- •Summary
- •Using java.util.concurrent Collections
- •Applying Atomic Variables and Locks
- •Using Executors and ThreadPools
- •Using the Parallel Fork/Join Framework
- •Chapter 3: Java Class Design
- •Chapter 4: Advanced Class Design
- •Chapter 5: Object-Oriented Design Principles
- •Chapter 6: Generics and Collections
- •Chapter 7: String Processing
- •Chapter 8: Java I/O Fundamentals
- •Chapter 9: Java File I/O (NIO.2)
- •Chapter 10: Building Database Applications with JDBC
- •Chapter 11: Exceptions and Assertions
- •Chapter 12: Localization
- •Chapter 13: Threads
- •Chapter 14: Concurrency
- •OCPJP7 Exam (1Z0-804 a.k.a. Java SE 7 Programmer II) Topics
- •OCPJP 7 Exam (1Z0-805, a.k.a. Upgrade to Java SE 7 Programmer) Topics
- •Answers and Explanations
- •Answer Sheet
- •Answers and Explanations
- •Index

ChaPTer 15 ■ OCPJP 7 QuICk reFreSher
|
Iterable |
Map |
Iterator |
|
Collection |
SortedMap |
ListIterator |
|
|
NavigableMap |
|
List |
Set |
Queue |
|
|
SortedSet |
Deque |
|
|
NavigableSet |
|
|
Figure 15-1. Important high-level java.util interfaces and their inheritance relationships
•Implement the Comparable interface for your classes when a natural order is possible. If you want to compare the objects other than the natural order or if there is no natural ordering present for your class type, then create separate classes implementing the Comparator interface. Also, if you have multiple alternative ways to decide the order, then go for the
Comparator interface.
Chapter 7: String Processing
•A regular expression defines a search pattern that can be used to execute operations such as string search and string manipulation. Table 15-1 summarizes commonly used symbols to specify regex, Table 15-2 lists commonly used metasymbols to specify regex, and Table 15-3 presents commonly used quantifiers with regex.
Table 15-1. Commonly Used Symbols to Specify Regular Expressions
Symbol Description
^expr |
Matches the expr at the beginning of line. |
expr$ |
Matches the expr at the end of line. |
. |
Matches any single character (except newline character). |
[xyz] |
Matches either x, y, or z. |
[p-z] |
Specifies a range. Matches any character from p to z. |
[p-z1-9] |
Matches either any character from p to z or any digit from 1 to 9 |
|
(remember, it won’t match p1). |
[^p-z] |
‘^’ as first character inside a bracket negates the pattern; |
|
it matches any character except characters p to z. |
Xy |
Matches x followed by y. |
x | y |
Matches either x or y. |
|
|
491

Chapter 15 ■ OCPJP 7 Quick Refresher
Table 15-2. Commonly Used Metasymbols to Specify Regular Expressions
Symbol Description
\d |
Matches digits (equivalent to [0–9]). |
|
\D |
Matches non-digits. |
|
\w |
Matches word characters. |
|
\W |
Matches non-word characters. |
|
\s |
Matches whitespaces (equivalent to [\t\r\f\n]). |
|
\S |
Matches non-whitespaces. |
|
\b |
Matches word boundary when outside bracket. Matches backslash |
|
|
when inside bracket. |
|
\B |
Matches non-word boundary. |
|
\A |
Matches beginning of string. |
|
\Z |
Matches end of string. |
|
|
|
|
Table 15-3. Commonly Used Quantifier Symbols |
||
|
|
|
Symbol |
Description |
|
expr? |
Matches 0 or 1 occurrence of expr (equivalent to expr{0,1}). |
|
expr* |
Matches 0 or more occurrences of expr (equivalent to expr{0,}). |
|
expr+ |
Matches 1 or more occurrences of expr (equivalent to expr{1,}). |
|
expr{x} |
Matches x occurrences of expr. |
|
expr{x, y} |
Matches between x and y occurrences of expr. |
|
expr{x,} |
Matches x or more occurrences of expr. |
|
|
|
|
•The argument of the split() method is a delimiter string, which is a regular expression. If the regular expression you pass has invalid syntax, you’ll get a PatternSyntaxException exception.
•Use the Pattern and Matcher classes whenever you are performing a search or replace on strings heavily; they are more efficient and faster than any other way to perform search/ replace in Java.
•You can form groups within a regex. These groups can be used to specify quantifiers on a desired subset of the whole regex. These groups can also be used to specify back reference.
•The method printf() (and the method format() in the String class) uses string formatting flags to format strings.
•Each format specifier starts with the % sign; followed by flags, width, and precision information; and ending with a data type specifier. In this string, the flags, width, and precision information are optional while the % sign and data type specifier are mandatory. Table 15-4 shows the commonly used data type specifier symbols.
492

Chapter 15 ■ OCPJP 7 Quick Refresher
Table 15-4. Commonly Used Data Type Specifiers
Symbol Description
%b |
Boolean |
%c |
Character |
%d |
Decimal integer (signed) |
%e |
Floating point number in scientific format |
%f |
Floating point number in decimal format |
%g |
Floating point number in decimal or scientific format |
|
(depending on the value passed as argument) |
%h |
Hashcode of the passed argument |
%n |
Line separator (new line character) |
%o |
Integer formatted as an octal value |
%s |
String |
%t |
Date/time |
%x |
Integer formatted as an hexadecimal value |
|
|
•If you do not specify any string formatting specifier, the printf() method will not print anything from the given arguments!
•Flags such as '-', '^', or '0' make sense only when you specify width with the format specifier string.
•You can also print the % character in a format string; however, you need to use an escape sequence for it. In format specifier strings, % is an escape character, which means you need to use %% to print a single %.
•If you do not provide the intended input data type as expected by the format string, you can get an IllegalFormatConversionException.
•If you want to form a string and use it later rather than just printing it using the printf() method, you can use a static method in the String class, format().
Chapter 8: Java I/O Fundamentals
•You can obtain reference to the console using the System.console() method; if the JVM is not associated with any console, this method will fail and return null.
•Many methods are provided in Console-support formatted I/O. You can use the printf() and format() methods available in the Console class to print formatted text; the overloaded readLine() and readPassword() methods take format strings as arguments.
•You can use character streams for text-based I/O and byte streams for data-based I/O.
493
Chapter 15 ■ OCPJP 7 Quick Refresher
•Character streams for reading and writing are called readers and writers, respectively (represented by the abstract classes Reader and Writer). Byte streams for reading and writing are called input streams and output streams, respectively (represented by the abstract classes
InputStream and OutputStream).
•You can combine stream objects. You can create an object of BufferedInputStream that takes a FileInputStream object. In this way, the output of one stream is chained to the filtered stream. This is an important, useful, and elegant way to customize the stream based on your needs.
•For processing data with primitive data types and Strings, you can use data streams.
•Serialization is the process of converting the objects in memory into a series of bytes. You need to implement the Serializable interface in a class if you want to make the objects of the class serializable.
•The Serializable interface is a marker interface. That means the Serializable interface does not declare any method inside it.
•If you want to customize the process of serialization, you can implement the readObject() and writeObject() methods. Note that both of these methods are private methods, which means you are not overriding or overloading these methods. JVM checks the implementation of these methods and calls them instead of the usual methods. It sounds weird but it is the way the customization of the serialization process is implemented in the JVM.
•A serialized object can be communicated over the network and deserialized on another machine. However, the class file of the object must be in the path of the destination machine, otherwise only the state of the object will be restored, not the whole object (i.e., you cannot invoke a method on the restored object).
•You can create your own protocol for serialization. For that, you need to implement the Externalizable interface instead of the Serializable interface.
•When you are not specifying serialVersionUID in a serialized class, JVM computes it for you. However, each JVM implementation has different mechanism to compute it; hence, it is not guaranteed that your serialized class will work on two different JVMs when you have not specified the serialVersionUID explicitly. Therefore, it is strongly recommended that you provide serialVersionUID in a class implementing the Serializable interface.
Chapter 9: Java File I/O (NIO.2)
•A Path object is a programming abstraction to represent a path of a file/directory.
•Do not confuse File with Files, Path with Paths, and FileSystem with FileSystems; they are different. File is an old class (Java 4) that represents file/directory path names, while Files was introduced in Java 7 as a utility class with comprehensive support for I/O APIs. The Path interface represents a file/directory path and defines a useful set of methods. However, the Paths class is a utility class that offers only two methods (both to get the Path object). FileSystems offer a list of factory methods for the class FileSystem, whereas FileSystem provides a useful set of methods to get information about a file system.
494

Chapter 15 ■ OCPJP 7 Quick Refresher
•The file or directory represented by a Path object might not exist.
•Path provides two methods to use to compare Path objects: equals() and compareTo(). Even if two Path objects point to the same file/directory, it is not guaranteed that you will get true from the equals() method. You need to make sure that both are absolute and normalized paths for an equality comparison to succeed for paths.
•You can check the existence of a file using the exists() method of the Files class.
•You can retrieve attributes of a file using the getAttributes() method. You can use the readAttributes() method of the Files class to read attributes of a file in bulk.
•While copying, all the directories (except the last one if you are copying a directory) in the specified path must exist to avoid NoSuchFileException.
•If you copy a directory using the copy() method, it will not copy the files/directories contained in the source directory; you need to explicitly copy them to the destination folder.
•It is not necessary that you perform copy on two files/directories only. You can take input from an InputStream and write to a file; similarly, you can take input from a file and copy to an
OutputStream. You can use the methods copy(InputStream, Path, CopyOptions...) and copy(Path, OutputStream, CopyOptions...).
•Use the delete() method to delete a file; use the deleteIfExists() method to delete a file only if it exists.
•If you do not want to implement all four methods in the FileVisitor interface, you can simply extend your implementation from the SimpleFileVisitor class.
•The PathMatcher interface is useful when you want to find a file satisfying a certain pattern. You can specify the pattern using glob or regex. Table 15-5 summarizes the patterns supported by the Glob syntax.
Table 15-5. Patterns Supported by Glob Syntax
Pattern Description
* |
Matches any string of any length, even zero length. |
** |
Similar to “*” but it crosses directory boundaries. |
? |
Matches to any single character. |
[xyz] |
Matches to either x, y, or z. |
[0-5] |
Matches to any character from the range 0 to 5. |
[a-z] |
Matches to any lowercase letter. |
{xyz, abc} |
Matches to either xyz or abc. |
|
|
•Java 7 offers a directory watch service that can notify you when the file you are working on is changed by some other program. You can register a Path object using a watch service along with certain event types. Whenever any file in the specified directory changes, an event is sent to the registered program.
•You must be careful performing an operation while walking a file tree. For instance, if you are performing a recursive delete, then you should first delete all the containing files before deleting the directory that is holding these containing files.
495