
- •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 4 ■Advanced Class Design
public String toString() {
return "You selected a color with RGB values " + color;
}
};
}
public static void main(String []args) { Shape.Color descriptiveColor =
StatusReporter.getDesciptiveColor(new Shape.Color(0, 0, 0)); System.out.println(descriptiveColor);
}
}
It prints
You selected a color with RGB values red = 0 green = 0 blue = 0
That’s nice. The rest of the program, including the main() method, remains the same and the getDescriptiveColor() method became simpler! You did not explicitly create a class with a name (which was DescriptiveColor); instead you just created a derived class of Shape.Color “on the fly” in the return statement. Note that the keyword class is also not needed.
Points to Remember
These points about anonymous classes concern questions that might be asked on the OPCJP 7 exam:
•Anonymous classes are defined in the new expression itself, so you cannot create multiple objects of an anonymous class.
•You cannot explicitly extend a class or explicitly implement interfaces when defining an anonymous class.
Enum Data Types
There are many situations where you want to restrict the user to providing input from a predefined list. For instance, you might want the user to choose from a set of constants defining several printer types:
public static final int DOTMATRIX = 1; public static final int INKJET = 2; public static final int LASER = 3;
The solution works. In this case, however, you could pass any other integer (say 10), and compiler would happily take it. Therefore, this solution is not a typesafe solution.
To avoid this condition, you may define you own class (say PrinterType) and allow only legitimate values. However, you need to define the class and its attributes manually. That’s where formerly you could have employed Joshua Bloch’s typesafe enumeration patterns. But don’t worry—you don’t need to learn those patterns anymore. Java 5 introduced the data type enum to help you in such situations.
Listing 4-9 defines an enum class (yes, enums are special classes) for the above example.
103
Chapter 4 ■Advanced Class Design
Listing 4-9. EnumTest.java
//define an enum for classifying printer types enum PrinterType {
DOTMATRIX, INKJET, LASER
}
//test the enum now
public class EnumTest { PrinterType printerType;
public EnumTest(PrinterType pType) { printerType = pType;
}
public void feature() {
// switch based on the printer type passed in the constructor switch(printerType){
case DOTMATRIX:
System.out.println("Dot-matrix printers are economical and almost obsolete"); break;
case INKJET:
System.out.println("Inkjet printers provide decent quality prints"); break;
case LASER:
System.out.println("Laser printers provide best quality prints"); break;
}
}
public static void main(String[] args) {
EnumTest enumTest = new EnumTest(PrinterType.LASER); enumTest.feature();
}
}
It prints
Laser printers provide best quality prints
Let’s probe the Listing 4-9 example in more detail.
•In a switch-case statement, you do not need to provide the fully qualified name for enum elements. This is because switch takes an instance of the enum type, and hence switch-case understands the context (type) in which you are specifying enum elements.
•You cannot provide any input while creating an instance of enumTest other than that specified in the enum definition. That makes enum typesafe.
Note that you can declare an enum (PrinterType in this case) in a separate file, just like you can declare any other normal Java class.
104
Chapter 4 ■Advanced Class Design
Now that you understand the basic concept of enum data type, let’s look at a more detailed example in which you define member attributes and methods in an enum data type. Yes, you can define methods or fields in an enum definition, as shown in Listing 4-10.
Listing 4-10. PrinterType.java
public enum PrinterType {
DOTMATRIX(5), INKJET(10), LASER(50);
private int pagePrintCapacity;
private PrinterType(int pagePrintCapacity) { this.pagePrintCapacity = pagePrintCapacity;
}
public int getPrintPageCapacity() { return pagePrintCapacity;
}
}
// EnumTest.java public class EnumTest {
PrinterType printerType;
public EnumTest(PrinterType pType) { printerType = pType;
}
public void feature() { switch (printerType) { case DOTMATRIX:
System.out.println("Dot-matrix printers are economical"); break;
case INKJET:
System.out.println("Inkjet printers provide decent quality prints"); break;
case LASER:
System.out.println("Laser printers provide the best quality prints"); break;
}
System.out.println("Print page capacity per minute: " + printerType.getPrintPageCapacity());
}
public static void main(String[] args) {
EnumTest enumTest1 = new EnumTest(PrinterType.LASER); enumTest1.feature();
EnumTest enumTest2 = new EnumTest(PrinterType.INKJET); enumTest2.feature();
}
}
105

Chapter 4 ■Advanced Class Design
The output of the above program is given below:
Laser printers provide the best quality prints Print page capacity per minute: 50
Inkjet printers provide decent quality prints Print page capacity per minute: 10
Well, what do you observe in this new version of enum example program? You defined a new attribute, a new constructor, and a new method for the enum class. The attribute pagePrintCapacity is set by the initial values specified with enum elements (such as LASER(50)), which calls the constructor of the enum class. However, the enum class cannot have a public constructor, or the compiler will complain with following message: "Illegal modifier for the enum constructor; only private is permitted."
A constructor in an enum class can only be specified as private.
Points to Remember
•Enums are implicitly declared public, static, and final, which means you cannot extend them.
•When you define an enumeration, it implicitly inherits from java.lang.Enum. Internally, enumerations are converted to classes. Further, enumeration constants are instances of the enumeration class for which the constant is declared as a member.
•You can apply the valueOf() and name() methods to the enum element to return the name of the enum element.
•If you declare an enum within a class, then it is by default static.
•You cannot use the new operator on enum data types, even inside the enum class.
•You can compare two enumerations for equality using == operator.
•When an enumeration constant’s toString() method is invoked, it prints the name of the enumeration constant.
•The static values() method in the Enum class returns an array of the enumeration constants when called on an enumeration type.
•Enumeration constants cannot be cloned. An attempt to do so will result in a
CloneNotSupportedException.
•If enumeration constants are from two different enumerations, the equals() method does not return true.
Enum avoids magic numbers, which improves readability and understandability of the source code. Also, enums are typesafe constructs. Therefore, you should use enums wherever applicable.
106

Chapter 4 ■Advanced Class Design
Question time!
1.Which of the following statements is true?
A.You cannot extend a concrete class and declare that derived class abstract.
B.You cannot extend an abstract class from another abstract class.
C.An abstract class must declare at least one abstract method in it.
D.You can create instantiate of a concrete subclass of an abstract class but cannot create instance of an abstract class itself.
Answer: D. You can create instantiate of a concrete subclass of an abstract class but cannot create instance of an abstract class itself.
2.Choose the best answer based on the following class definition: public abstract final class Shape { }
A.Compiler error: a class must not be empty.
B.Compiler error: illegal combination of modifiers abstract and final.
C.Compiler error: an abstract class must declare at least one abstract method.
D.No compiler error: this class definition is fine and will compile successfully. Answer: B. Compiler error: illegal combination of modifiers abstract and final.
(You cannot declare an abstract class final since an abstract class must to be extended. Class can be empty in Java, including abstract classes. An abstract class can declare zero or more abstract methods.)
3.Look at the following code and choose the right option for the word <access-modifier>:
//Shape.java public class Shape {
protected void display() { System.out.println("Display-base");
}
}
//Circle.java
public class Circle extends Shape { <access-modifier> void display(){
System.out.println("Display-derived");
}
}
107
Chapter 4 ■advanCed Class design
a.Only protected can be used.
B.public and protected both can be used.
C.public, protected, and private can be used.
d.Only public can be used.
Answer: B. public and protected both can be used.
(You can provide only a less restrictive or same-access modifier when overriding a method.)
4.Consider this program to answer the following question:
class Shape {
public Shape() {
System.out.println("Shape constructor");
}
public class Color {
public Color() {
System.out.println("Color constructor");
}
}
}
class TestColor {
public static void main(String []args) {
Shape.Color black = new Shape().Color(); // #1
}
}
What will be the output of the program?
a.Compile error: the method Color() is undefined for the type shape.
B.Compile error: invalid inner class.
C.Works fine: shape constructor, Color constructor.
d.Works fine: Color constructor, shape constructor.
Answer: a. Compile error: the method Color() is undefined for the type shape.
(You need to create an instance of outer class shape in order to create an inner class instance).
5.if you replace the Color class instantiation statement (tagged as #1 inside a comment in the program given in the previous questions) with the following statement, what would be the output of the program?
Shape.Color black = new Shape().new Color();
a.Works fine and will print this output:
shape constructor Color constructor
108
Chapter 4 ■Advanced Class Design
B.Works fine and will print this output:
Color constructor Shape constructor
C.Compiler error: The method Color() is undefined for the type Shape.
D.Compile without error but results in a runtime exception.
Answer: A. Works fine and will print this output:
Shape constructor
Color constructor
6.What will be the output of the given program?
class Shape {
private boolean isDisplayed; protected int canvasID; public Shape() {
isDisplayed = false; canvasID = 0;
}
public class Color {
public void display() {
System.out.println("isDisplayed: "+isDisplayed); System.out.println("canvasID: "+canvasID);
}
}
}
class TestColor {
public static void main(String []args) { Shape.Color black = new Shape().new Color(); black.display();
}
}
A.Compiler error: an inner class can only access public members of the outer class.
B.Compiler error: an inner class cannot access private members of the outer class.
C.Runs and prints this output:
isDisplayed: false canvasID: 0
D.Compiles fine but crashes with a runtime exception.
Answer: C. Runs and prints this output:
isDisplayed: false canvasID: 0
(An inner class can access all members of an outer class, including the private members of the outer class).
109
Chapter 4 ■Advanced Class Design
7.Look at this program and predict the output:
public class EnumTest { PrinterType printerType;
enum PrinterType {INKJET, DOTMATRIX, LASER}; public EnumTest(PrinterType pType) {
printerType = pType;
}
public static void main(String[] args) { PrinterType pType = new PrinterType();
EnumTest enumTest = new EnumTest(PrinterType.LASER);
}
}
A.Prints the output printerType:LASER.
B.Compiler Error: enums must be declared static.
C.Compiler Error: cannot instantiate the type EnumTest.PrinterType.
D.This program will compile fine, and when run, will crash and throw a runtime exception. Answer: C. Compiler Error: cannot instantiate the type EnumTest.PrinterType.
(You cannot instantiate an enum type using new.)
8.Is the enum definition given below correct?
public enum PrinterType { |
|
|
private int pagePrintCapacity; |
// |
#1 |
DOTMATRIX(5), INKJET(10), LASER(50); |
// |
#2 |
|
|
|
private PrinterType(int pagePrintCapacity) { this.pagePrintCapacity = pagePrintCapacity;
}
public int getPrintPageCapacity() { return pagePrintCapacity;
}
}
A.Yes, this enum definition is correct and will compile cleanly without any warnings or errors.
B.No, this enum definition is incorrect and will result in compile error(s).
C.No, this enum definition will result in runtime exception(s).
D.Yes, this enum definition is correct but will compile with warnings.
110