
- •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 12 ■ Localization
+" \n The currency symbol is " + currencyInstance.getSymbol()
+" \n The currency name is " + currencyInstance.getDisplayName());
}
}
It prints the following:
The currency code for locale en_US is: USD The currency symbol is $
The currency name is US Dollar
The output is self-explanatory. Note that for many locales where there is no symbol involved, getSymbol() will just return the currency code.
The DateFormat Class
The DateFormat class provides support for processing date and time in a locale-sensitive manner (the name simply says DateFormat, but it supports both date and time). Table 12-5 lists some of the important methods in the
DateFormat class.
Table 12-5. Important Methods in the DateFormat Class
|
|
Method |
Short Description |
String format(Date date) |
Formats the given date for the default locale and returns a textual |
|
representation. Its overloaded version takes a StringBuffer and |
|
position as arguments and returns a StringBuffer object; useful |
|
if an existing StringBuffer needs to be formatted for date. |
Date parse(String source) |
Reads the given String according to the default locale conventions |
|
to return a Date object; throws ParseException if it fails. It has an |
|
overloaded version that takes ParsePosition (the position from |
|
which to parse the String) as an additional argument. |
String format(Date date) |
Formats the given date for the default locale and returns a textual |
|
representation. |
static Locale[] getAvailableLocales() |
Returns an array of Locales that are supported by the Java |
|
runtime for date/time formatting. |
static DateFormat getInstance() |
Returns the default DateFormat instance that supports both date |
|
and time; it uses DateFormat.SHORT style for both date and time. |
static DateFormat getDateInstance() |
Returns the DateFormat instance suitable for processing dates for |
|
default locale; its two overloaded versions take style and Locale |
|
as additional arguments. |
static DateFormat getTimeInstance() |
Returns the DateFormat instance suitable for processing time |
|
for a default locale; its two overloaded versions take style and |
|
Locale as additional arguments. |
static DateFormat getDateTimeInstance() |
Returns the DateFormat instance suitable for processing both |
|
date and time for a default locale; its two overloaded versions take |
|
style and Locale as additional arguments. |
|
|
381
Chapter 12 ■ Localization
Depending on the locale, the displayed date or time can be considerably different, as shown from the output of the program in Listing 12-12 for four locales.
Listing 12-12. DatePrint.java
import java.util.*; import java.text.*;
// Class to demonstrate the use of DateFormat class to format the date and print it class DatePrint {
public static void main(String[] args) {
//the default constructor for the Date
//sets the date/time for current date/time Date today = new Date();
Locale [] locales = { Locale.CANADA, Locale.FRANCE, Locale.GERMANY, Locale.ITALY }; for(Locale locale : locales) {
// DateFormat.FULL refers to the full details of the date
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, locale); System.out.println("Date in locale " + locale + " is: " + dateFormat. format(today));
}
}
}
When this program was run on Sept 4, 2012, it printed the following:
Date in locale en_CA is: Tuesday, September 4, 2012 Date in locale fr_FR is: mardi 4 septembre 2012
Date in locale de_DE is: Dienstag, 4. September 2012 Date in locale it_IT is: martedì 4 settembre 2012
This program gets an instance of the DateFormat class using one of the overloaded versions of the getDateInstance() method. This method takes the display format style as the first argument, and the locale to be used for formatting the date as the second argument. What are those display format styles? Listing 12-13 shows the four styles and how the dates look different for these styles.
Listing 12-13. DateStyleFormats.java
import java.util.*; import java.text.*;
// Demonstrates the use of constants in DateFormat that determines the display style class DateStyleFormats {
public static void main(String []args) { Date now = new Date();
int [] dateStyleFormats = { DateFormat.SHORT, DateFormat.MEDIUM, DateFormat.LONG, DateFormat.FULL, DateFormat.DEFAULT};
System.out.println("Today's date in different styles are: ");
//print today's date in all four formats plus
//the default format in the default Locale for(int dateStyleFormat : dateStyleFormats) {
382
Chapter 12 ■ Localization
DateFormat dateFormat = DateFormat.getDateInstance(dateStyleFormat); System.out.println(dateFormat.format(now));
}
}
}
When run on Sept 5, 2012, it printed the following:
Today's date in different styles are: 9/5/12
Sep 5, 2012 September 5, 2012
Wednesday, September 5, 2012 Sep 5, 2012
As you can see, you can get an instance of DateFormat for a preferred style based on the need. The default style is
DateFormat.MEDIUM.
The DateFormat has three overloaded factory methods—getDateInstance(), getTimeInstance(), and getDateTimeInstance()—that return DateFormat instances for processing date, time, and both date and time, respectively. Listing 12-14 shows how to use them.
Listing 12-14. DateTimePrint.java
import java.util.*; import java.text.*;
// Class to demonstrate the use of DateFormat class to get date, time, or date with time class DateTimePrint {
public static void main(String []args) {
//the default constructor for the Date gets the current time and date Date today = new Date();
Locale [] locales =
{Locale.CANADA, Locale.FRANCE, Locale.GERMANY, Locale.ITALY };
//print the header first
System.out.printf("%5s \t %10s \t %10s \t %10s %n", "Locale", "Date", "Time", "Date with Time");
// print the date, time, and date & time for each locale for(Locale locale : locales) {
//DateFormat.SHORT is for giving the date or
//time details in compact format
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale); DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
// now, for Date & Time, change the styles to MEDIUM and FULL DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat. MEDIUM, DateFormat.FULL, locale);
System.out.printf("%5s \t %10s \t %10s \t %20s %n", locale, dateFormat.format(today), timeFormat.format(today), dateTimeFormat.format(today));
}
}
}
383
Chapter 12 ■ Localization
When run on Sept 5, 2012 in the afternoon, it printed the following:
|
|
|
|
Locale |
Date |
Time |
Date with Time |
en_CA |
05/09/12 |
2:32 PM |
5-Sep-2012 2:32:56 o'clock PM GMT + 05:30 |
fr_FR |
05/09/12 |
14:32 |
5 sept. 2012 14 h 32 GMT + 05:30 |
de_DE |
05.09.12 |
14:32 |
05.09.2012 14:32 Uhr GMT + 05:30 |
it_IT |
05/09/12 |
14.32 |
5-set-2012 14.32.56 GMT + 05:30 |
|
|
|
|
This program shows how to get instances of DateFormat for processing date, time, or both date and time. You can also see the effect of using different styles for different locales.
Until now you have only used DateFormat to process predefined date and time for different locales. If you want to create your own format or pattern for processing the date or time, can you do that? Yes, the SimpleDateFormat class provides this facility.
The SimpleDateFormat Class
SimpleDateFormat extends the DateFormat class. SimpleDateFormat uses the concept of a pattern string to format the date and time. Before you delve deeper into creating pattern strings, first look at a simple example to learn how to create a custom format for printing date and time (Listing 12-15).
Listing 12-15. PatternStringExample.java
import java.util.*; import java.text.*;
// Use SimpleDateFormat for creating custom date and time formats as a pattern string class PatternStringExample {
public static void main(String []args) {
String pattern = "dd-MM-yy"; /* d for day, M for month, y for year */ SimpleDateFormat formatter = new SimpleDateFormat(pattern);
// the default Date constructor initializes to current date/time System.out.println(formatter.format(new Date()));
}
}
It prints the date in following format:
05-09-12
You encode the format of the date or time using letters to form a date or time pattern string. Usually these letters are repeated in the pattern. Note that the uppercase and lowercase letters can have similar or different meanings, so read the documentation carefully when trying to use these letters. For example, in dd-MM-yy, MM refers to month; however, in dd-mm-yy, mm refers to minutes!
In this program, you’ve given a simple example for creating a custom format for date. Similar letters are available for creating custom date and time pattern strings. Here is the list of important letters and their meanings for creating patterns for dates:
G |
Era (BC/AD) |
y |
Year |
Y |
Week year |
M |
Month (in year) |
w |
Week (in year) |
384
Chapter 12 ■ Localization
W Week (in month) D Day (in year)
d Day (in month)
F Day of week in month E Day name in week
u Day number of week (value range 1-7)
Listing 12-16 is a program that uses simple to difficult pattern strings for creating custom date formats.
Listing 12-16. CustomDatePatterns.java
import java.util.*; import java.text.*;
// Using an example, illustrates the use of "pattern strings" for printing dates class CustomDatePatterns {
public static void main(String []args) {
// patterns from simple to complex ones String [] dateFormats = {
"dd-MM-yyyy", /* d is day (in month), M is month, y is year */
"d '('E')' MMM, YYYY", /*E is name of the day (in week), Y is year*/ "w'th week of' YYYY", /* w is the week of the year */
"EEEE, dd'th' MMMM, YYYY" /*E is day name in the week */
};
Date today = new Date();
System.out.println("Default format for the date is " + DateFormat.getDateInstance().format(today)); for(String dateFormat : dateFormats) {
System.out.printf("Date in pattern \"%s\" is %s %n", dateFormat, new SimpleDateFormat(dateFormat).format(today));
}
}
}
In a sample run, it printed the following:
Default format for the date is Sep 5, 2012 Date in pattern "dd-MM-yyyy" is 05-09-2012
Date in pattern "d '('E')' MMM, YYYY" is 5 (Wed) Sep, 2012 Date in pattern "w'th week of' YYYY" is 36th week of 2012
Date in pattern "EEEE, dd'th' MMMM, YYYY" is Wednesday, 05th September, 2012
As you can see, repeating letters result in a longer form for an entry. For example, when you use E (which is the name of the day in the week), it prints Wed, whereas when you use EEEE, it prints the full form of the day name, which is Wednesday.
Another important thing to notice is how to print text within the given pattern string. For that you use text separated by single quotes, as in ‘within single quotes’ which will be printed as it is by the SimpleDateFormat. For example, ‘(‘E’)’ prints (Wed). If you give an incorrect pattern or forget to use single quotes for separating your text from pattern letters inside the pattern string, you’ll get an IllegalArgumentException exception for passing an “Illegal pattern.”
385
Chapter 12 ■ Localization
Now, look at a similar example for creating custom time pattern strings. Here is the list of important letters useful for defining a custom time pattern:
a Marker for the text am/pm marker H Hour (value range 0-23)
k Hour (value range 1-24)
K Hour in am/pm (value range 0-11) h Hour in am/pm (value range 1-12)
m |
Minute |
s |
Second |
S |
Millisecond |
z |
Time zone (general time zone format) |
For more letters and their descriptions, see the JavaDoc for the SimpleDateFormat class. Listing 12-17 is a program that uses simple to difficult pattern strings for creating custom time formats.
Listing 12-17. CustomTimePatterns.java
import java.util.*; import java.text.*;
// Using an example, illustrates the use of "pattern strings" for constructing custom time formats class TimePattern {
public static void main(String []args) {
// patterns from simple to complex ones String [] timeFormats = {
"h:mm", /* h is hour in am/pm (1-12), m is minute */
"hh 'o''clock'", /* '' is the escape sequence to print a single quote */ "H:mm a", /* H is hour in day (0-23), a is am/pm*/
"hh:mm:ss:SS", /* s is seconds, S is milliseconds */
"K:mm:ss a, zzzz" /*K is hour in am/pm(0-11), z is time zone */
};
Date today = new Date();
System.out.println("Default format for the time is " + DateFormat.getTimeInstance().format(today)); for(String timeFormat : timeFormats) {
System.out.printf("Time in pattern \"%s\" is %s %n", timeFormat, new SimpleDateFormat(timeFormat).format(today));
}
}
}
It printed the following:
Default format for the time is 3:10:05 PM Time in pattern "hh 'o''clock'" is 03 o'clock Time in pattern "h:mm" is 3:10
Time in pattern "H:mm a" is 15:10 PM
Time in pattern "hh:mm:ss:SS" is 03:10:05:355
Time in pattern "K:mm:ss a, zzzz" is 3:10:05 PM, GMT + 05:30
Note that the output differs based on the pattern string you use in this program.
386