
- •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 11 ■ Exceptions and Assertions
Try-with-Resources
It is a fairly common mistake by Java programmers to forget releasing resources, even in the finally block. Also, if you’re dealing with multiple resources, it is tedious to remember to call the close() method in the finally block. Java 7 introduced a feature named try-with-resources to help make your life easier. Listing 11-9 makes use of this feature; it is an improved version of Listing 11-8.
Listing 11-9. TryWithResources1.java
import java.util.*;
class TryWithResources1 {
public static void main(String [] args) {
System.out.println("Type an integer in the console: ");
try(Scanner consoleScanner = new Scanner(System.in)) {
System.out.println("You typed the integer value: " + consoleScanner.nextInt());
} catch(Exception e) {
// catch all other exceptions here ...
System.out.println("Error: Encountered an exception and could not read an integer from the console... ");
System.out.println("Exiting the program - restart and try the program again!");
}
}
}
The behavior will be similar to that of the program in Listing 11-7, so we’re not running the program and showing the sample output again.
Make sure you take a closer look at the syntax for try-with-resources block.
try(Scanner consoleScanner = new Scanner(System.in)) {
In this statement, you have acquired the resources inside the parenthesis after the try keyword, but before the try block. Also, in the example, you don’t provide the finally block. The Java compiler will internally translate this try-with-resources block into a try-finally block (of course, the compiler will retain the catch blocks you provide). You can acquire multiple resources in the try-with-resources block; such resource acquisition statements should be separated by semicolons.
Can you provide try-with-resources statements without any explicit catch or finally blocks? Yes! Remember that a try block can be associated with a catch block, finally block, or both. A try-with-resources statement block gets expanded internally into a try-finally block. So, you can provide a try-with-resources statement without explicit catch or finally blocks. Listing 11-10 uses a try-with-resources statement without any explicit catch or finally blocks.
Listing 11-10. TryWithResources2.java
import java.util.*;
class TryWithResources2 {
public static void main(String [] args) {
System.out.println("Type an integer in the console: ");
try(Scanner consoleScanner = new Scanner(System.in)) {
System.out.println("You typed the integer value: " + consoleScanner.nextInt());
}
}
}
332
Chapter 11 ■ Exceptions and Assertions
Although it is possible to create a try-with-resources statement without any explicit catch or finally, it doesn’t mean you should do so! For example, since this code does not have a catch block, if you type some invalid input, the program will crash.
D:\> java TryWithResources1 Type an integer in the console: ten
Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119)
at TryWithResources1.main(TryWithResources1.java:7)
So, the benefit of a try-with-resources statement is that it simplifies your life by not having to provide finally blocks explicitly. However, you still need to provide necessary catch blocks.
Note that for a resource to be usable with a try-with-resources statement, the class of that resource must implement the java.lang.AutoCloseable interface. This interface declares one single method named close(). You already know that the try-with-resources feature was added in Java 7. This AutoCloseable interface was also introduced in Java 7, and the interface is made of the base interface of the Closeable interface. This is to make sure
that the existing resource classes work seamlessly with a try-with-resources statement. In other words, you can use all old stream classes with try-with-resources because they implement the AutoCloseable interface.
Closing Multiple Resources
You can use more than one resource in a try-with-resources statement. Here is a code snippet for creating a zip file from a given text file that makes use of a try-with-resources statement:
//buffer is the temporary byte buffer used for copying data from one stream to another stream byte [] buffer = new byte[1024];
//these stream constructors can throw FileNotFoundException
try (ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(zipFileName)); FileInputStream fileIn = new FileInputStream(fileName)) { zipFile.putNextEntry(new ZipEntry(fileName)); // putNextEntry can throw
// IOException
int lenRead = 0; // the variable to keep track of number of bytes sucessfully read
// copy the contents of the input file into the zip file
while((lenRead = fileIn.read(buffer)) > 0) { // read can throw IOException
zipFile.write(buffer, 0, lenRead); // write can throw IOException
}
//the streams will be closed automatically because they are within try-with-
//resources statement
}
In this code, the buffer is a byte array. This array is temporary storage useful for copying raw data from one stream to another stream. In the try-with-resources statement, you open two streams: ZipOutputStream for writing to the zip file and FileInputStream for reading in the text file. (Note: API support for zip (and jar) files is available in java.util.zip library.) You want to read the input text file, zip it, and put that entry in the zip file. For putting a
333
Chapter 11 ■ Exceptions and Assertions
file/directory entry into the zip file, the ZipOutputStream class provides a method named putNextEntry(), which takes a ZipEntry object as an argument. The statement zipFile.putNextEntry(new ZipEntry(fileName)); puts a file entry named fileName into the zipFile.
For reading the contents of the text file, you use the read() method in the FileInputStream class. The read() method takes the buffer array as the argument. The amount of data to read per iteration (i.e., “data chunk size” to read) is given by the size of the passed array; it is 1024 bytes in this code. The read() method returns the number of bytes it read, and if there is no more data to read, it returns –1. The while loop checks if read succeeded (using the > 0 condition) before writing it to the zip file.
For writing data to the zip file, you use the write() method in the ZipOutputStream class. The write() method takes three arguments: the first argument is the data buffer; the second argument is start offset in the data buffer (which is 0 because you always read from the start of the buffer); and the third is the number of bytes to be written.
Now we come to the main discussion. Note how you open two resources in the try block and these two resource acquisition statements are separated by semicolons. You do not have an explicit finally block to release the resources because the compiler will automatically insert calls to the close methods for these two streams in the finally block(s).
Listing 11-11 is the complete program that makes use of this code segment to illustrate the use of try-with- resources statement for auto-closing multiple streams.
Listing 11-11. ZipTextFile.java
import java.util.*; import java.util.zip.*; import java.io.*;
//class ZipTextFile takes the name of a text file as input and creates a zip file
//after compressing that text file.
class ZipTextFile {
public static final int CHUNK = 1024; // to help copy chunks of 1KB
public static void main(String []args) {
if(args.length == 0) {
System.out.println("Pass the name of the file in the current directory to be zipped as an argument");
System.exit(-1);
}
String fileName = args[0];
// name of the zip file is the input file name with the suffix ".zip"
String zipFileName = fileName + ".zip";
byte [] buffer = new byte[CHUNK];
// these constructors can throw FileNotFoundException
try (ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(zipFileName)); FileInputStream fileIn = new FileInputStream(fileName)) {
// putNextEntry can throw IOException zipFile.putNextEntry(new ZipEntry(fileName));
int lenRead = 0; // variable to keep track of number of bytes // successfully read
// copy the contents of the input file into the zip file
while((lenRead = fileIn.read(buffer)) > 0) {
// both read and write methods can throw IOException zipFile.write (buffer, 0, lenRead);
}
334
Chapter 11 ■ Exceptions and Assertions
// the streams will be closed automatically because they are // within try-with-resources statement
}
// this can result in multiple exceptions thrown from the try block;
// use "suppressed exceptions" to get the exceptions that were suppressed!
catch(Exception e) {
System.out.println("The caught exception is: " + e);
System.out.print("The suppressed exceptions are: ");
for(Throwable suppressed : e.getSuppressed()) {
System.out.println(suppressed);
}
}
}
}
We’ve already discussed the try-with-resources block part. What we have not discussed is suppressed exceptions. In a try-with-resources statement, there might be more than one exception that could get thrown; for example,
one within the try block, one within the catch block, and another one within the finally block. However, only one exception can be caught, so the other exception(s) will be listed as suppressed exceptions. From a given exception object, you can use the method getSuppressed() to get the list of suppressed exceptions.
Points to Remember
Here are some interesting points about try-with-resources statement that will help you in the OCPJP 7 exam:
•You cannot assign to the resource variables declared in the try-with-resources within the body of the try-with-resources statement. This is to make sure that the same resources acquired in the try-with-resources header are released in the finally block.
•It is a common mistake to close a resource explicitly inside the try-with-resources statement. Remember that try-with-resources expands to calling the close() method in the finally block, so the expanded code will have a double call to the close() method. Consider the following code:
try(Scanner consoleScanner = new Scanner(System.in)) {
System.out.println("You typed the integer value: " + consoleScanner.nextInt()); consoleScanner.close();
//explicit call to close() method - remember that try-with-resources
//statement will also expand to calling close() in finally method;
// hence this will result in call to close() method in Scanner twice!
}
The documentation of the close() method in the Scanner class says that if the scanner object is already closed, then invoking the method again will have no effect. So, you are safe in this case. However, in general, you cannot expect all the resources to have implemented a close() method that is safe to call twice. So, it is a bad practice to explicitly call the close() method inside a try-with-resource statement.
335