
- •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 6 ■ Generics and Collections
Listing 6-20. NavigableMapTest.java
// This program demonstrates the usage of navigable tree interface and TreeMap class
import java.util.*;
public class NavigableMapTest {
public static void main(String []args) {
NavigableMap<Integer, String> examScores = new TreeMap<Integer, String>();
examScores.put(90, "Sophia"); examScores.put(20, "Isabella"); examScores.put(10, "Emma"); examScores.put(50, "Olivea");
System.out.println("The data in the map is: " + examScores); System.out.println("The data descending order is: " + examScores.descendingMap()); System.out.println("Details of those who passed the exam: " +
examScores.tailMap(40));
System.out.println("The lowest mark is: " + examScores.firstEntry());
}
}
It prints the following:
The data in the map is: {10=Emma, 20=Isabella, 50=Olivea, 90=Sophia}
The data descending order is: {90=Sophia, 50=Olivea, 20=Isabella, 10=Emma} Details of those who passed the exam: {50=Olivea, 90=Sophia}
The lowest mark is: 10=Emma
In this program, you have a NavigableMap<Integer, String> that maps the exam score and the name of the person. You create a TreeMap<String, String> to actually store the exam scores. By default, a TreeMap stores data in ascending order. If you want the data in descending order, it’s easy: you just have to use the descendingMap() method (or descendingKeySet() if you are only interested in the keys).
Given the passing score is 40, you might want to get the map with data of those who failed in the exam. For that, you can use the headMap() method with the key value 40 (since the data is in ascending order, you want to get the “head” part of the map from the given position). Similarly, to get the data of those who passed the exam, you can use the tailMap() method.
If you want the immediate ones above and below the passing score, you can use the higherEntry() and lowerEntry() methods, respectively. The firstEntry() and lastEntry() methods give the entries with lowest and highest key values. So, when you use the firstEntry() method on examScores, you get Emma with 10 marks. If you use lastEntry(), you get Sophia, who has score 90.
The Queue Interface
A Queue follows FIFO mechanism: the first inserted element will be removed first. For getting a queue behavior, you can create a LinkedList object and refer it through a Queue reference. When you call the methods from Queue reference, the object behaves like a Queue. Listing 6-21 shows an example and it will become clear. Lennon,
McCartney, Harrison, and Starr are taking an online exam. Let’s see how you can remember the sequence in which they logged in to take the exam (see Listing 6-21).
185
Chapter 6 ■ Generics and Collections
Listing 6-21. QueueTest.java
// This program shows the key characteristics of Queue interface
import java.util.*;
class QueueTest {
public static void main(String []args) {
Queue<String> loginSequence = new LinkedList<String>();
loginSequence.add("Harrison");
loginSequence.add("McCartney");
loginSequence.add("Starr");
loginSequence.add("Lennon");
System.out.println("The login sequence is: " + loginSequence); while(!loginSequence.isEmpty())
System.out.println("Removing " + loginSequence.remove());
}
}
This prints the following:
The login sequence is: [Harrison, McCartney, Starr, Lennon] Removing Harrison
Removing McCartney Removing Starr Removing Lennon
In this example, you create a Queue<String> to point it to a LinkedList<String> object. Then you add four elements (names in the sequence in which they logged in) to the queue. After the elements are inserted, you print the queue by (implicitly) calling the toString() method on loginSequence. You call the remove() method to remove one element of the queue. The remove() method removes an element from the head of the queue and returns the extracted element. You got the same sequence as output as you inserted in the queue.
The Deque Interface
Deque (Doubly ended queue) is a data structure that allows you to insert and remove elements from both the ends. The Deque interface was introduced in Java 6 in java.util.collection package. The Deque interface extends the Queue interface just discussed. Hence, all methods provided by Queue are also available in the Deque interface. Let’s examine the commonly used methods of the Deque interface, summarized in Table 6-7.
186

Chapter 6 ■ Generics and Collections
Table 6-7. Commonly Used Methods in the Deque Interface
|
|
Method |
Short Description |
void addFirst(Element) |
Adds the Element to the front of the Deque. |
void addLast(Element) |
Adds the Element to the last of the Deque. |
Element removeFirst() |
Removes an element from the front of the Deque and returns it. |
Element removeLast() |
Removes an element from the last of the Deque and returns it. |
Element getFirst() |
Returns the first element from the Deque, does not remove. |
Element getLast() |
Returns the last element from the Deque, does not remove. |
|
|
All methods listed in Table 6-7 raise appropriate exceptions if they fail. There is another set of methods, listed in Table 6-8, that achieves the same functionality. However, they do not raise exception on failure; instead they return a special value. For instance, the method getFirst() returns the first element from the Deque but does not remove it. If the Deque is empty, it raises the exception, NoSuchElementException. At the same time, the peekFirst() method also carry out the same functionality. However, it returns null if the Deque is empty. When the Deque is created with predefined capacity, the methods listed in Table 6-8 are preferred over the methods listed in Table 6-7.
Table 6-8. Commonly Used Methods in the Deque Interface (Returns Special Value)
|
|
Method |
Short Description |
boolean offerFirst(Element) |
Adds the Element to the front of the Deque if it is not violating capacity constraint. |
boolean offerLast(Element) |
Adds the Element to the end of the Deque if it is not violating capacity constraint. |
Element pollFirst() |
Removes an element from the front of the Deque and returns it; if the Deque is |
|
empty, it returns null. |
Element pollLast() |
Removes an element from the end of the Deque and returns it; if the Deque is |
|
empty, it returns null. |
Element peekFirst() |
Returns the first element from the Deque but does not remove it; returns null |
|
if Deque is empty. |
Element peekLast() |
Returns the last element from the Deque but does not remove it; returns null |
|
if Deque is empty. |
|
|
You just observed that the methods in Table 6-8 return null if they fail. What if you are storing null as an element? Well, it is not recommended that you store null as an argument, since there are methods in the Deque interface that return null, and it would be difficult for you to distinguish between the success or failure of the method call.
There are three concrete implementations of the Deque interface: LinkedList, ArrayDeque, and LinkedBlockingDeque. Let’s use ArrayDeque to understand the features of the Deque interface.
187
Chapter 6 ■ GeneriCs and ColleCtions
It is evident from the list of methods supported by Deque that it is possible to realize the standard behavior of a queue, stack, and deque. Let’s implement a special queue (say, to pay utility bill) where a customer can be added only at the end of the queue and can be removed either at the front of the queue (when the customer paid the bill) or from the end of the queue (when the customer gets frustrated from the long line and leaves the queue himself). Listing 6-22 shows how to do this.
Listing 6-22. SplQueueTest.java
// This program shows the usage of Deque interface
import java.util.*;
class SplQueue {
private Deque<String> splQ = new ArrayDeque<>(); void addInQueue(String customer){
splQ.addLast(customer);
}
void removeFront(){ splQ.removeFirst();
}
void removeBack(){ splQ.removeLast();
}
void printQueue(){
System.out.println("Special queue contains: " + splQ);
}
}
class SplQueueTest {
public static void main(String []args) { SplQueue splQ = new SplQueue(); splQ.addInQueue("Harrison"); splQ.addInQueue("McCartney"); splQ.addInQueue("Starr"); splQ.addInQueue("Lennon");
splQ.printQueue();
splQ.removeFront();
splQ.removeBack();
splQ.printQueue();
}
}
It prints the following:
Special queue contains: [Harrison, McCartney, Starr, Lennon]
Special queue contains: [McCartney, Starr]
You first define a class—SplQueue—that defines a container splQ of type ArrayDeque with basic four operations. The method addInQueue() adds a customer at the end of the queue, the method removeBack() removes a customer from the end of the queue, the method removeFront() removes a customer from the front of the queue, and the method printQueue() simply prints all elements of the queue. You simply use the addLast(), removeFront(),
188