
- •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
The NumberFormat Class
The NumberFormat class provides support for processing numbers in a locale-sensitive manner. For example, depending on the locale, how thousands are separated, the punctuation characters used for separating them, printing an amount as a currency value, etc. are different, and the NumberFormat class provides this functionality.
The NumberFormat class provides methods to format or parse numbers. Here “formatting” means converting a numeric value to a string value in a culture-sensitive way; similarly, “parsing” means converting a number back to numeric form. For example, if you want to print the long constant value 10_000_000L into ten million in German locale, you format this value by passing it to the format() method in the NumberFormat class, and this method will return the String “10.000.000” (note the use of dot as a separation character for thousands). Now, if you read the
input value 10 million in German locale to convert that value to a long value to use it in the program, you can pass the string to the parse() method. Listing 12-8 shows the steps to perform these conversions.
Listing 12-8. FormatNumber.java
import java.util.*; import java.text.*;
// class to demonstrate how to format or parse numbers for a particular locale class FormatNumber {
public static void main(String []args) { long tenMillion = 10_000_000L;
// first print ten million in German locale
NumberFormat germanFormat = NumberFormat.getInstance(Locale.GERMANY); String localizedTenMillion = germanFormat.format(tenMillion);
System.out.println("Ten million in German locale is " + localizedTenMillion);
// now, scan the value ten million given in German locale try {
Number parsedAmount = germanFormat.parse(localizedTenMillion); if(tenMillion == parsedAmount.longValue()) {
System.out.println("Successfully parsed the number for the locale");
}
}
catch (ParseException pe) {
System.err.println("Error: Cannot parse the number for the locale");
}
}
}
It prints the following:
Ten million in German locale is 10.000.000
Successfully parsed the number value back to Number value based on the locale
As you can see, the value 10 million is printed in this format in German locale: 10.000.000. To parse such a number in a given locale, you can use the NumberFormat’s parse() method, which returns a Number if the parsing is successful—or else the method throws a checked exception, ParseException.
Note that the parse() method is different from the format() method. The parse() method is meant for reading numbers provided as String and trying to convert it to Number. The format() method is used for printing the values according to the values set in the NumberFormat object. Listing 12-9 illustrates the difference between the two.
377

Chapter 12 ■ Localization
Listing 12-9. FractionDigits.java
import java.util.*; import java.text.*;
public class FractionDigits {
public static void main(String[] args) throws ParseException { String[] numbers = {"1.222", "0.12345F"};
double[] doubles = {1.222, 0.12345F};
NumberFormat numberFormat = NumberFormat.getInstance(); numberFormat.setMaximumFractionDigits(2); System.out.println("Using format method: ");
for(double val : doubles) { System.out.println(numberFormat.format(val));
}
System.out.println("Using parse method: "); for(String number : numbers) {
System.out.println(numberFormat.parse(number));
}
}
}
It prints the following:
Using format method: 1.22 0.12
Using parse method: 1.222 0.12345
The parse() method reads the values and converts it to Number if it succeeds. So, it does not use the maximum fraction digits set using setMaximumFractionDigits(); however, if it were to use the format() method, which is meant for printing numbers, it would use this maximum fraction digits limit set, which explains the difference between the outputs.
Important methods in the NumberFormat class are listed in Table 12-3. The static methods that start with the “get” prefix and end with the “Instance” suffix—such as getCurrencyInstance()—are factory methods supported by this class.
Table 12-3. Important Methods in the NumberFormat Class
Method |
Short Description |
String format(double number)
String format(long number)
Formats the number according to the NumberFormat’s locale. The first two overloaded methods use an implicit StringBuffer, whereas the last two use an explicit StringBuffer to build the String.
Number parse(String source) |
Parses the number from the given String. It returns a Long or |
|
Double instance depending on the value of the number given |
|
in source. Throws a ParseException if the parse fails. |
|
|
|
(continued ) |
378
|
Chapter 12 ■ Localization |
Table 12-3. (continued ) |
|
|
|
Method |
Short Description |
static Locale[] getAvailableLocales() |
Returns the list of the locales supported by the Java runtime for |
|
number formatting. |
static NumberFormat getInstance() |
Factory method that returns a NumberFormat object for the |
|
default locale. |
Currency getCurrency() |
Returns the currency instance used by this NumberFormat object. |
static NumberFormat getCurrencyInstance() |
Returns the instance of NumberFormat suitable for currency |
|
formatting purposes; an overloaded version of this method |
|
takes a Locale as an argument. |
static NumberFormat getIntegerInstance() |
Returns the instance of NumberFormat suitable for use for |
|
formatting integer numbers; an overloaded version of this |
|
method takes a Locale as an argument. |
static NumberFormat getPercentInstance() |
Returns the instance of NumberFormat suitable for use for |
|
formatting for percentages; an overloaded version of this |
|
method takes a Locale as an argument. |
|
|
The NumberFormat class supports printing currency values. You can use its getCurrencyInstance() method, which returns a Currency object. Listing 12-10 illustrates how to make use of this method for printing the value 10 million in four different locales (without performing exchange rate conversions).
Listing 12-10. LocalizedCurrency.java
import java.util.*; import java.text.*;
// Ilustrates how to use NumberFormat class to get Currency instance class LocalizedCurrency {
public static void main(String []args) {
long tenMillion = 10000000L; // this is ten million Locale [] locales =
{ Locale.CANADA, Locale.FRANCE, Locale.GERMANY, Locale.TAIWAN };
//for each of the four locales,
//print the currency amount as it looks in that locale for(Locale locale : locales) {
System.out.println("Ten million in " + locale.getDisplayName() + " is " + NumberFormat.getCurrencyInstance(locale).format(tenMillion));
}
}
}
It prints:
Ten million in English (Canada) is $10,000,000.00 Ten million in French (France) is 10 000 000,00 € Ten million in German (Germany) is 10.000.000,00 € Ten million in Chinese (Taiwan) is NT$10,000,000.00
379

Chapter 12 ■ LoCaLization
As you can see, by using the NumberFormat object returned from getCurrencyInstance(Locale), you can format numbers to print them as currency values for a locale. You can also use the Currency class independently of the NumberFormat class, as we’ll discuss now.
The Currency Class
Table 12-4 lists important methods the Currency class.
Table 12-4. Important Methods in the Currency Class |
|
|
|
Method |
Short Description |
int getNumericCode() |
Returns ISO 4217 numeric code for the currency. |
int getDefaultFractionDigits() |
Returns the default number of digits used with the |
|
currency, such as zero for the Japanese Yen and two |
|
for the US Dollar. |
String getDisplayName() |
Returns the readable description of the Currency for |
|
the underlying locale, for example, US Dollar. |
String getDisplayName(Locale) |
Returns the readable description of the Currency for |
|
the given locale. |
static Currency getInstance(String currencyCode) |
Returns the Currency object corresponding to the |
|
given currency code. |
static Currency getInstance(Locale locale)
static Set < Currency > getAvailableCurrencies()
String getSymbol()
String getSymbol(Locale)
String getCurrencyCode()
Returns the Currency object corresponding to the given Locale object.
Get the list of Currency instances available in the JDK.
Returns the currency symbol, if any; otherwise, returns the currency code.
Returns the currency symbol for the given Locale object.
Returns the currency code (ISO 4217) for locale of the Currency instance.
Listing 12-11 shows how to make use of few of these methods listed in Table 12-4.
Listing 12-11. CurrencyDetails.java
import java.util.*;
// Get the currency details of the default locale (en_US locale) class CurrencyDetails {
public static void main(String []args) { Locale locale = Locale.getDefault();
Currency currencyInstance = Currency.getInstance(locale); System.out.println(" The currency code for locale " + locale
+ " is: " + currencyInstance.getCurrencyCode()
380