- •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
Introduction
Localization is all about making the software relevant and usable for the users from different cultures—in other words, customizing software for people from different countries or languages. How do you localize a software application? Two important guidelines should be heeded when you localize a software application:
•Do not hardcode text (such as messages to the users, textual elements in GUIs, etc.) and separate them into external files or dedicated classes. With this accomplished there is usually minimal effort to add support for a new locale in your software.
•Handle cultural-specific aspects such as date, time, currency, and formatting numbers with localization in mind. Instead of assuming a default locale, design in such a way that the current locale is fetched and customized.
Text may not be the only thing that needs to be localized in an application. For example, if your application uses audio sounds to give instructions, they will need to be changed for localization. Similarly, if the software displays some glyphs or pictures for a specific locale, they also need to be transformed.
Locales
A locale is “a place representing a country, language, or culture.” Consider the Canada-French locale. French is spoken in many parts of Canada, and this could be a locale. In other words, if you want to sell software that is customized
for Canadians who speak French, then you need to facilitate your software for this locale. In Java, this locale is represented by the code fr_CA where fr is short for French and CA is short for Canada; we’ll discuss the naming scheme for locales in more detail later in this section.
The Locale Class
In Java, the Locale class provides programming support for locales. Table 12-1 lists important methods in this class.
Table 12-1. Important Methods in the Locale Class |
|
|
|
Method |
Short Description |
static Locale[] getAvailableLocales() |
Returns a list of available locales (i.e., installed locales) |
|
supported by the JVM. |
static Locale getDefault() |
Returns the default locale of the JVM. |
static void setDefault(Locale newLocale) |
Sets the default locale of the JVM. |
String getCountry() |
Returns the country code for the locale object. |
String getDisplayCountry() |
Returns the country name for the locale object. |
String getLanguage() |
Returns the language code for the locale object. |
String getDisplayLanguage() |
Returns the language name for the locale object. |
|
|
|
(continued ) |
362
|
Chapter 12 ■ Localization |
Table 12-1. (continued ) |
|
|
|
Method |
Short Description |
String getVariant() |
Returns the variant code for the locale object. |
String getDisplayVariant() |
Returns the name of the variant code for the locale object. |
String toString() |
Returns a String composed of the codes for the locale’s |
|
language, country, variant, etc. |
|
|
The code in Listing 12-1 detects the default locale and checks the available locales in the JVM.
Listing 12-1. AvailableLocales.java
import java.util.Locale;
class AvailableLocales {
public static void main(String []args) {
System.out.println("The default locale is: " + Locale.getDefault()); Locale [] locales = Locale.getAvailableLocales();
System.out.printf("No. of other available locales is: %d, and they are: %n", locales.length);
for(Locale locale : locales) {
System.out.printf("Locale code: %s and it stands for %s %n", locale, locale.getDisplayName());
}
}
}
It prints the following:
The default locale is: en_US
No. of other available locales is: 156, and they are: Locale code: ms_MY and it stands for Malay (Malaysia) Locale code: ar_QA and it stands for Arabic (Qatar)
Locale code: is_IS and it stands for Icelandic (Iceland)
Locale code: sr_RS_#Latn and it stands for Serbian (Latin,Serbia) Locale code: no_NO_NY and it stands for Norwegian (Norway,Nynorsk) Locale code: th_TH_TH_#u-nu-thai and it stands for Thai (Thailand,TH) Locale code: fr_FR and it stands for French (France)
Locale code: tr and it stands for Turkish
Locale code: es_CO and it stands for Spanish (Colombia) Locale code: en_PH and it stands for English (Philippines) Locale code: et_EE and it stands for Estonian (Estonia) Locale code: el_CY and it stands for Greek (Cyprus)
Locale code: hu and it stands for Hungarian [...rest of the output elided...]
Let’s look at the methods in the program before analyzing the output. You use the method getDefault() in Locale to get the code of the default locale. After that you use getAvailableLocales() in the Locale class to get the list of available locales in your JVM. Now, for each locale you print the code for the locale by implicitly calling the toString() method of locale and also print the descriptive name using the getDisplayName() method of Locale.
363
Chapter 12 ■ Localization
The program prints the default locale as en_US for this JVM, which means the default is the English language spoken in US. Then it prints a very long list of available locales; to save space, we’ve shown only small part of the output. From this program, you know that there are many locales available and supported, and there is a default locale associated with every JVM.
There are four different kinds of locale codes in this output:
•Just one code, as in the last entry shown above: hu for Hungarian.
•Two codes separated by underscore, as in the first locale shown, ms_MY, where ms stands for Malaysia and MY stands for Malay.
•Three codes separated by underscores, as in no_NO_NY where no stands for Norway, NO for Norwegian, and NY for Nynorsk.
•Two or three initial codes separated by underscores and the final one by # or _#, as in th_TH_TH_#u-nu-thai, which we’ll discuss now. Here is how these locale names are encoded:
language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions
For the locale code of th_TH_TH_#u-nu-thai,
•The language code is th (Thai) and it is always written in lowercase.
•The country code is TH (Thailand) and it is always written in uppercase.
•The variant name is TH; here it repeats the country code, but it could be any string.
•The script name is an empty string here; if given, it will be a four-letter string with the first letter in uppercase and the rest in lowercase (e.g., Latn).
•The extension follows the # or _# character; it is u-nu-thai in this example.
This coding scheme is to allow programming variations even within the same language. For example, English is spoken in many countries, and there are variations in the language based on the country in which English is spoken. We all know that American English is different from British English, but there are many such versions. Let’s change the loop in Listing 12-1 to list only the locales that are related to English, like so:
for(Locale locale : locales) {
// filter and display only English locales if(locale.getLanguage().equals("en")) {
System.out.printf("Locale code: %s and it stands for %s %n", locale, locale.getDisplayName());
}
}
It prints the following:
Locale code: en_MT and it stands for English (Malta)
Locale code: en_GB and it stands for English (United Kingdom) Locale code: en_CA and it stands for English (Canada)
Locale code: en_US and it stands for English (United States) Locale code: en_ZA and it stands for English (South Africa) Locale code: en and it stands for English
Locale code: en_SG and it stands for English (Singapore) Locale code: en_IE and it stands for English (Ireland)
364
Chapter 12 ■ Localization
Locale code: en_IN and it stands for English (India) Locale code: en_AU and it stands for English (Australia) Locale code: en_NZ and it stands for English (New Zealand) Locale code: en_PH and it stands for English (Philippines)
The output refers to different locales in English. You use the getLanguage() method in Locale, which returns the locale code. What are other such methods? You’ll explore the methods available in the Locale class now.
Getting Locale Details
The getter methods in the Locale class such as getLanguage(), getCountry(), and getVariant() return codes, whereas the similar methods getDisplayCountry(), getDisplayLanguage(), and getDisplayVariant() return names. Listing 12-2 illustrates how to use these methods for the locale Locale.CANADA_FRENCH.
Listing 12-2. LocaleDetails.java
import java.util.Locale;
public class LocaleDetails {
public static void main(String args[]) { Locale.setDefault(Locale.CANADA_FRENCH); Locale defaultLocale = Locale.getDefault();
System.out.printf("The default locale is %s %n", defaultLocale); System.out.printf("The default language code is %s and the name is %s %n", defaultLocale.getLanguage(), defaultLocale.getDisplayLanguage()); System.out.printf("The default country code is %s and the name is %s %n", defaultLocale.getCountry(), defaultLocale.getDisplayCountry()); System.out.printf("The default variant code is %s and the name is %s %n", defaultLocale.getVariant(), defaultLocale.getDisplayVariant());
}
}
It prints the following:
The default locale is fr_CA
The default language code is fr and the name is français The default country code is CA and the name is Canada The default variant code is and the name is Canada
Let’s understand the program. The setDefault() method takes a Locale object as argument. In this program, you set the default locale as Locale.CANADA_FRENCH with this statement:
Locale.setDefault(Locale.CANADA_FRENCH);
The Locale class has many static Locale objects representing common locales so that you don’t have to instantiate them and use them directly in your programs. In this case, Locale.CANADA_FRENCH is a static Locale object. Instead of using this static Locale object, you can choose to instantiate a Locale object. Here is an alternative way to set the default locale by creating a new Canada (French) locale object:
Locale newLocale = new Locale("fr", "CA", ""); Locale.setDefault(newLocale);
365