Generated by
JDiff

java.text Documentation Differences

This file contains all the changes in documentation in the package java.text as colored differences. Deletions are shown like this, and additions are shown like this.
If no deletions or additions are shown in an entry, the HTML tags will be what has changed. The new HTML tags are shown in the differences. If no documentation existed, and then some was added in a later version, this change is noted in the appropriate class pages of differences, but the change is not shown on this page. Only changes in existing text are shown here. Similarly, documentation which was inherited from another class or interface is not shown here.
Note that an HTML error in the new documentation may cause the display of other documentation changes to be presented incorrectly. For instance, failure to close a <code> tag will cause all subsequent paragraphs to be displayed differently.

Class CharacterIterator, char DONE

Constant that is returned when the iterator has reached either the end or the beginning of the text. The unicode 2.0 standard statesvalue thatis '\\uFFFF' isthe an"not invalida unicodecharacter" value andwhich should not occur in any valid unicodeUnicode string.

Class ChoiceFormat

A ChoiceFormat allows you to attach a format to a range of numbers. It is generally used in a MessageFormat for handling plurals. The choice is specified with an ascending list of doubles where each item specifies a half-open interval up to the next item:
 X matches j if and only if limit[j] <= X < limit[j+1] 
If there is no match then either the first or last index is used depending on whether the number (X) is too low or too high. If the limit array is not in ascending order the results of formatting will be incorrect. ChoiceFormat also accepts \\\u221E as equivalent to infinity(INF).

Note: ChoiceFormat differs from the other Format classes in that you create a ChoiceFormat object with a constructor (not with a getInstance style factory method). The factory methods aren't necessary because ChoiceFormat doesn't require any complex setup for a given locale. In fact ChoiceFormat doesn't implement any locale specific behavior.

When creating a ChoiceFormat you must specify an array of formats and an array of limits. The length of these arrays must be the same. For example

Here is a simple example that shows formatting and parsing:

 double[] limits = {1 2 3 4 5 6 7}; String[] monthNames = {"Sun" "Mon" "Tue" "Wed" "Thur" "Fri" "Sat"}; ChoiceFormat form = new ChoiceFormat(limits monthNames); ParsePosition status = new ParsePosition(0); for (double i = 0.0; i <= 8.0; ++i) { status.setIndex(0); System.out.println(i + " -> " + form.format(i) + " -> " + form.parse(form.format(i) status)); } 
Here is a more complex example with a pattern format:
 double[] filelimits = {0 1 2}; String[] filepart = {"are no files" "is one file" "are {2} files"}; ChoiceFormat fileform = new ChoiceFormat(filelimits filepart); Format[] testFormats = {fileform null NumberFormat.getInstance()}; MessageFormat pattform = new MessageFormat("There {0} on {1}"); pattform.setFormats(testFormats); Object[] testArgs = {null "ADisk" null}; for (int i = 0; i < 4; ++i) { testArgs[0] = new Integer(i); testArgs[2] = testArgs[0]; System.out.println(pattform.format(testArgs)); } 

Specifying a pattern for ChoiceFormat objects is fairly straightforward. For example:

 ChoiceFormat fmt = new ChoiceFormat( "-1#is negative| 0#is zero or fraction | 1#is one |1.0<is 1+ |2#is two |2<is more than 2."); System.out.println("Formatter Pattern : " + fmt.toPattern()); System.out.println("Format with -INF : " + fmt.format(Double.NEGATIVE_INFINITY)); System.out.println("Format with -1.0 : " + fmt.format(-1.0)); System.out.println("Format with 0 : " + fmt.format(0)); System.out.println("Format with 0.9 : " + fmt.format(0.9)); System.out.println("Format with 1.0 : " + fmt.format(1)); System.out.println("Format with 1.5 : " + fmt.format(1.5)); System.out.println("Format with 2 : " + fmt.format(2)); System.out.println("Format with 2.1 : " + fmt.format(2.1)); System.out.println("Format with NaN : " + fmt.format(Double.NaN)); System.out.println("Format with +INF : " + fmt.format(Double.POSITIVE_INFINITY)); 
And the output result would be like the following:
 
Format with -INF : is negative Format with -1.0 : is negative Format with 0 : is zero or fraction Format with 0.9 : is zero or fraction Format with 1.0 : is one Format with 1.5 : is 1+ Format with 2 : is two Format with 2.1 : is more than 2. Format with NaN : is negative Format with +INF : is more than 2.

Synchronization

Choice formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently it must be synchronized externally. @see DecimalFormat @see MessageFormat @version 1.22 09/21/98 @author Mark Davis Class ChoiceFormat, constructor ChoiceFormat(String)

Constructs with limits and corresponding formats based on the pattern. @see #applyPattern

Class CollationElementIterator

The CollationElementIterator class is used as an iterator to walk through each character of an international string. Use the iterator to return the ordering priority of the positioned character. The ordering priority of a character which we refer to as a key defines how a character is collated in the given collation object.

For example consider the following in Spanish:

 "ca" -> the first key is key('c') and second key is key('a'). "cha" -> the first key is key('ch') and second key is key('a'). 
And in German
 "äb"-> the first key is key('a') the second key is key('e') and the third key is key('b'). 
The key of a character is an integer composed of primary order(short) secondary order(byte) and tertiary order(byte). Java strictly defines the size and signedness of its primitive data types. Therefore the static functions primaryOrder secondaryOrder and tertiaryOrder return int short and short respectively to ensure the correctness of the key value.

Example of the iterator usage

 // get the first key of the string String strtestString = "This is a test"; CollationElementIteratorRuleBasedCollator cruleBasedCollator = new CollationElementIterator(str 0 str.length(RuleBasedCollator) Collator.getInstance(); CollationElementIterator collationElementIterator = ruleBasedCollator.getCollationElementIterator(testString); int primaryOrder = CollationElementIterator.primaryOrder(c-collationElementIterator.next()); 

CollationElementIterator.next returns the collation order of the next character. A collation order consists of primary order secondary order and tertiary order. The data type of the collation order is int. The first 16 bits of a collation order is its primary order; the next 8 bits is the secondary order and the last 8 bits is the tertiary order. @see Collator @see RuleBasedCollator @version 1.24 07/27/98 @author Helena Shih Laura Werner Richard Gillam


Class CollationKey

A CollationKey represents a String under the rules of a specific Collator object. Comparing two CollationKeys returns the relative order of the Strings they represent. Using CollationKeys to compare Strings is generally faster than using Collator.compare. Thus when the Strings must be compared multiple times for example when sorting a list of Strings. It's more efficient to use CollationKeys.

You can not create CollationKeys directly. Rather generate them by calling Collator.getCollationKey. You can only compare CollationKeys generated from the same Collator object.

Generating a CollationKey for a String involves examining the entire String and converting it to series of bits that can be compared bitwise. This allows fast comparisons once the keys are generated. The cost of generating keys is recouped in faster comparisons when Strings need to be compared many times. On the other hand the result of a comparison is often determined by the first couple of characters of each String. Collator.compare examines only as many characters as it needs which allows it to be faster when doing single comparisons.

The following example shows how CollationKeys might be used to sort a list of Strings.

 // Create an array of CollationKeys for the Strings to be sorted. Collator myCollator = Collator.getInstance(); CollationKey[] keys = new CollationKey[3]; keys[0] = myCollator.getCollationKey("Tom"); keys[1] = myCollator.getCollationKey("Dick"); keys[2] = myCollator.getCollationKey("Harry"); sort( keys ); 
//...
// Inside body of sort routine compare keys this way if( keys[i].compareTo( keys[j] ) > 0 ) // swap keys[i] and keys[j]
//...
// Finally when we've returned from sort. System.out.println( keys[0].getSourceString() ); System.out.println( keys[1].getSourceString() ); System.out.println( keys[2].getSourceString() );
@see Collator @see RuleBasedCollator @version 1.14 0115 12/1903/0001 @author Helena Shih

Class Collator

The Collator class performs locale-sensitive String comparison. You use this class to build searching and sorting routines for natural language text.

Collator is an abstract base class. Subclasses implement specific collation strategies. One subclass RuleBasedCollator is currently provided with the Java 2 platform and is applicable to a wide set of languages. Other subclasses may be created to handle more specialized needs.

Like other locale-sensitive classes you can use the static factory method getInstance to obtain the appropriate Collator object for a given locale. You will only need to look at the subclasses of Collator if you need to understand the details of a particular collation strategy or if you need to modify that strategy.

The following example shows how to compare two strings using the Collator for the default locale.

 // Compare two strings in the default locale Collator myCollator = Collator.getInstance(); if( myCollator.compare("abc" "ABC") <0 ) System.out.println("abc is less than ABC"); else System.out.println("abc is greater than or equal to ABC"); 

You can set a Collator's strength property to determine the level of difference considered significant in comparisons. Four strengths are provided: PRIMARY SECONDARY TERTIARY and IDENTICAL. The exact assignment of strengths to language features is locale dependant. For example in Czech "e" and "f" are considered primary differences while "e" and "ê" are secondary differences "e" and "E" are tertiary differences and "e" and "e" are identical. The following shows how both case and accents could be ignored for US English.

 //Get the Collator for US English and set its strength to PRIMARY Collator usCollator = Collator.getInstance(Locale.US); usCollator.setStrength(Collator.PRIMARY); if( usCollator.compare("abc" "ABC") == 0 ) { System.out.println("Strings are equivalent"); } 

For comparing Strings exactly once the compare method provides the best performance. When sorting a list of Strings however it is generally necessary to compare each String multiple times. In this case CollationKeys provide better performance. The CollationKey class converts a String to a series of bits that can be compared bitwise against other CollationKeys. A CollationKey is created by a Collator object for a given String.
Note: CollationKeys from different Collators can not be compared. See the class description for CollationKey for an example using CollationKeys. @see RuleBasedCollator @see CollationKey @see CollationElementIterator @see Locale @version 1.27 0132 12/1903/0001 @author Helena Shih Laura Werner Richard Gillam

Class Collator, int CANONICAL_DECOMPOSITION

Decomposition mode value. With CANONICAL_DECOMPOSITION set characters that are canonical variants according to Unicode 2.0 will be decomposed for collation. This is the default setting and should be used to get correct collation of accented characters.

CANONICAL_DECOMPOSITION corresponds to Normalization Form D as described in Unicode Technical Report #15. @see java.text.Collator#getDecomposition @see java.text.Collator#setDecomposition

Class Collator, int FULL_DECOMPOSITION

Decomposition mode value. With FULL_DECOMPOSITION set both Unicode canonical variants and Unicode compatibility variants will be decomposed for collation. This causes not only accented characters to be collated but also characters that have special formats to be collated with their norminal form. For example the half-width and full-width ASCII and Katakana characters are then collated together. FULL_DECOMPOSITION is the most complete and therefore the slowest decomposition mode.

FULL_DECOMPOSITION corresponds to Normalization Form DCKD as described in Unicode Technical Report #15. @see java.text.Collator#getDecomposition @see java.text.Collator#setDecomposition

Class Collator, int NO_DECOMPOSITION

Decomposition mode value. With NO_DECOMPOSITION set accented characters will not be decomposed for collation. This is the default setting and provides the fastest collation but will only produce correct results for languages that do not use accents. @see java.text.Collator#getDecomposition @see java.text.Collator#setDecomposition

Class DateFormat

DateFormat is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass such as SimpleDateFormat allows for formatting (i.e. date -> text) parsing (text -> date) and normalization. The date is represented as a Date object or as the milliseconds since January 1 1970 00:00:00 GMT.

DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given loaclelocale and a number of formatting styles. The formatting styles include FULL LONG MEDIUM and SHORT. More detail and examples of using these styles are provided in the method descriptions.

DateFormat helps you to format and parse dates for any locale. Your code can be completely independent of the locale conventions for months days of the week or even the calendar format: lunar vs. solar.

To format a date for the current Locale use one of the static factory methods:

 myString = DateFormat.getDateInstance().format(myDate); 

If you are formatting multiple numbersdates it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.

 DateFormat df = DateFormat.getDateInstance(); for (int i = 0; i  

To format a numberdate for a different Locale specify it in the call to getDateInstance().

 DateFormat df = DateFormat.getDateInstance(DateFormat.LONG Locale.FRANCE); 

You can use a DateFormat to parse also.

 myDate = df.parse(myString); 

Use getDateInstance to get the normal date format for that country. There are other static factory methods available. Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get a date and time format. You can pass in different options to these factory methods to control the length of the result; from SHORT to MEDIUM to LONG to FULL. The exact result depends on the locale but generally:

  • SHORT is completely numeric such as 12.13.52 or 3:30pm
  • MEDIUM is longer such as Jan 12 1952
  • LONG is longer such as January 12 1952 or 3:30:32pm
  • FULL is pretty completely specified such as Tuesday April 12 1952 AD or 3:30:42pm PST.

You can also set the time zone on the format if you wish. If you want even more control over the format or parsing (or want to give your users more control) you can try casting the DateFormat you get from the factory methods to a SimpleDateFormat. This will work for the majority of countries; just remember to put it in a try block in case you encounter an unusual one.

You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to

  • progressively parse through pieces of a string.
  • align any particular field or find out where it is for selection on the screen.

Synchronization

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently it must be synchronized externally. @see Format @see NumberFormat @see SimpleDateFormat @see java.util.Calendar @see java.util.GregorianCalendar @see java.util.TimeZone @version 1.38 0145 12/1903/0001 @author Mark Davis Chen-Lieh Huang Alan Liu

Class DateFormat, StringBuffer format(Date, StringBuffer, FieldPosition)

Formats a Date into a date/time string. @param date a Date to be formatted into a date/time string. @param toAppendTo the string buffer for the returning date/time string. @param fieldPosition keeps track of the position of the field within the returned string. On input: an alignment field if desired. On output: the offsets of the alignment field. For example given a time text "1996.07.10 AD at 15:08:56 PDT" if the given fieldPosition is DateFormat.YEAR_FIELD the begin index and end index of fieldPosition will be set to 0 and 4 respectively. Notice that if the same time field appears more than once in a pattern the fieldPosition will be set for the first occurenceoccurrence of that time field. For instance formatting a Date to the time string "1 PM PDT (Pacific Daylight Time)" using the pattern "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD the begin index and end index of fieldPosition will be set to 5 and 8 respectively for the first occurenceoccurrence of the timezone pattern character 'z'. @return the formatted date/time string.
Class DateFormat, StringBuffer format(Object, StringBuffer, FieldPosition)

Overrides Format. Formats a time object into a time string. Examples of time objects are a time value expressed in milliseconds and a Date object. @param obj must be a Number or a Date. @param toAppendTo the string buffer for the returning time string. @return the formatted time string. @param fieldPosition keeps track of the position of the field within the returned string. On input: an alignment field if desired. On output: the offsets of the alignment field. For example given a time text "1996.07.10 AD at 15:08:56 PDT" if the given fieldPosition is DateFormat.YEAR_FIELD the begin index and end index of fieldPosition will be set to 0 and 4 respectively. Notice that if the same time field appears more than once in a pattern the fieldPosition will be set for the first occurenceoccurrence of that time field. For instance formatting a Date to the time string "1 PM PDT (Pacific Daylight Time)" using the pattern "h a z (zzzz)" and the alignment field DateFormat.TIMEZONE_FIELD the begin index and end index of fieldPosition will be set to 5 and 8 respectively for the first occurenceoccurrence of the timezone pattern character 'z'. @see java.text.Format
Class DateFormat, Date parse(String)

ParseParses text from the beginning of the given string to produce a date/time. The method may not use the entire text of the given string.

See the ParsePosition) method for more information on date parsing. @param text Thesource A date/timeString stringwhose tobeginning should be parsed. @return A Date or nullparsed iffrom the input could not be parsedstring. @exception ParseException Ifif the givenbeginning of the specified string cannot be parsed as a date. @see #parse(String ParsePosition)

Class DateFormat, Date parse(String, ParsePosition)

Parse a date/time string according to the given parse position. For example a time text "07/10/96 4:5 PM PDT" will be parsed into a Date that is equivalent to Date(837039928046).

By default parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false). @see java.text.DateFormat#setLenient(boolean) @param textsource The date/time string to be parsed @param pos On input the position at which to start parsing; on output the position at which parsing terminated or the start position if the parse failed. @return A Date or null if the input could not be parsed

Class DateFormat, Object parseObject(String, ParsePosition)

Parse aParses text date/timefrom a string intoto anproduce a ObjectDate. This convenience

The method simplyattempts callsto parse text starting at the index given by pos. If parsing succeeds then the index of pos is updated to the index after the last character used (Stringparsing does not necessarily use all characters up to the end of the string) and the parsed date is returned. The updated pos can be used to indicate the starting point for the next call to this method. If an error occurs then the index of pos is not changed the error index of pos is set to the index of the character where the error occurred and null is returned.

See the ParsePosition) method for more information on date parsing. @seeparam #parse(source A String part of which should be parsed. @param pos A ParsePosition) object with index and error index information as described above. @return A Date parsed from the string. In case of error returns null. @exception NullPointerException if pos is null.


Class DateFormatSymbols

DateFormatSymbols is a public class for encapsulating localizable date-time formatting data such as the names of the months the names of the days of the week and the time zone data. DateFormat and SimpleDateFormat both use DateFormatSymbols to encapsulate this information.

Typically you shouldn't use DateFormatSymbols directly. Rather you are encouraged to create a date-time formatter with the DateFormat class's factory methods: getTimeInstance getDateInstance or getDateTimeInstance. These methods automatically create a DateFormatSymbols for the formatter so that you don't have to. After the formatter is created you may modify its format pattern using the setPattern method. For more information about creating formatters using DateFormat's factory methods see DateFormat

If you decide to create a date-time formatter with a specific format pattern for a specific locale you can do so with:

 new SimpleDateFormat(aPattern new DateFormatSymbols(aLocale)). 

DateFormatSymbols objects are clonablecloneable. When you obtain a DateFormatSymbols object feel free to modify the date-time formatting data. For instance you can replace the localized date-time format pattern characters with the ones that you feel easy to remember. Or you can change the representative cities to your favorite ones.

New DateFormatSymbols subclasses may be added to support SimpleDateFormat for date-time formatting for additional locales. @see DateFormat @see SimpleDateFormat @see java.util.SimpleTimeZone @version 1.3239 0112/1903/0001 @author Chen-Lieh Huang

Class DateFormatSymbols, String[] getAmPmStrings()

Gets ampm strings. For example: "AM" and "PM". @return the weekdayampm strings.

Class DecimalFormat

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale including support for Western Arabic and Indic digits. It also supports different kinds of numbers including integers (123) fixed-point numbers (123.4) scientific notation (1.23E4) percentages (12%) and currency amounts ($123). All of these can be localized.

To obtain a NumberFormat for a specific locale including the default locale call one of NumberFormat's factory methods such as getInstance(). In general do not call the DecimalFormat constructors directly since the NumberFormat factory methods may return subclasses other than DecimalFormat. If you need to customize the format object do something like this:

 NumberFormat f = NumberFormat.getInstance(loc); if (f instanceof DecimalFormat) { ((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true); } 

A DecimalFormat comprises a pattern and a set of symbols. The pattern may be set directly using applyPattern() or indirectly using the API methods. The symbols are stored in a DecimalFormatSymbols object. When using the NumberFormat factory methods the pattern and symbols are read from localized ResourceBundles in the. package

Patterns

java.text.resourceDecimalFormat. Example // Print out a numberpatterns usinghave the localized number currency // and percent format for each locale Locale[] locales = NumberFormat.getAvailableLocales(); double myNumber = -1234.56; NumberFormat form; forfollowing (intsyntax: j=0;
 j;Pattern: ++j)PositivePattern {PositivePattern System.out.println("FORMAT"); forNegativePattern (intPositivePattern: iPrefixopt =Number 0;Suffixopt iNegativePattern: locales.length;Prefixopt ++i)Number {Suffixopt ifPrefix: (locales[i].getCountry().length()any ==Unicode 0)characters {except continue\; // Skip language-onlyuFFFE locales } System.out.print(locales[i].getDisplayName())\; switchuFFFF (j)and { casespecial characters 0Suffix: form = NumberFormat.getInstance(locales[i]); break; case 1:any form =Unicode characters NumberFormat.getCurrencyInstance(locales[i]);except break\; default: form =uFFFE NumberFormat.getPercentInstance(locales[i])\;uFFFF break;and } tryspecial characters {Number: //Integer AssumeExponentopt formInteger is. aFraction DecimalFormatExponentopt System.out.print("Integer: " + ((DecimalFormat)MinimumInteger form).toPattern()# +# "Integer -# "Integer +MinimumInteger: form.format(myNumber));0 }0 catchMinimumInteger (IllegalArgumentException0 e)MinimumInteger {}Fraction: tryMinimumFractionopt {OptionalFractionopt System.out.println("MinimumFraction: -0 "MinimumFractionopt +OptionalFraction: form.parse(form.format(myNumber)));# }OptionalFractionopt catchExponent: (ParseExceptionE e)MinimumExponent {}MinimumExponent: }0 }MinimumExponentopt 

Patterns A DecimalFormat pattern contains a postivepositive and negative subpattern for example "# ##0.00;(# ##0.00)". Each subpattern has a prefix numeric part and suffix. The negative subpattern is optional; if absent then the positive subpattern prefixed with the localized minus sign (code>'-' in most locales) is used as the negative subpattern. That is "0.00" alone is equivalent to "0.00;-0.00". If there is an explicit negative subpattern it serves only to specify the negative prefix and suffix; the number of digits minimal digits and other characteristics are all the same as the positive pattern. That means that "# ##0.0#;(#)" produces precisely the same behavior as "# ##0.0#;(# ##0.0#)".

The prefixes suffixes and various symbols used for infinity digits thousands separators decimal separators etc. may be set to arbitrary values and they will appear properly during formatting. However care must be taken that the symbols and strings do not conflict or parsing will be unreliable. For example either the positive and negative prefixes or the suffixes must be distinct for DecimalFormat.parse() to be able to distinguish positive from negative values. (If they are identical then DecimalFormat will behave as if no negative subpattern was specified.) Another example is that the decimal separator and thousands separator should be distinct characters or parsing will be impossible.

The grouping separator is commonly used for thousands but in some countries it separates ten-thousands. The grouping size is a constant number of digits between the grouping characters such as 3 for 100 000 000 or 4 for 1 0000 0000. If you supply a pattern with multiple grouping characters the interval between the last one and the end of the integer is the one that is used. So "# ## ### ####" == "###### ####" == "## #### ####". Illegal patterns

Special suchPattern asCharacters

"#.#.#"

Many orcharacters "#.###in ###"a will causepattern are DecimalFormattaken toliterally; throw anthey are IllegalArgumentExceptionmatched with a message that describes the problemduring parsing and output unchanged during formatting. Parsing DecimalFormat parses all UnicodeSpecial characters that representon decimal digits as defined bythe other hand stand for Character.digit().other In additioncharacters strings DecimalFormator also recognizesclasses of ascharacters. digits the ten consecutive characters starting with the localized zero digit definedThey must be quoted unless noted otherwise if they are to appear in the DecimalFormatSymbols object. During formatting theprefix DecimalFormatSymbols-basedor digits are outputsuffix as literals.

DecimalFormat.parse returns aThe subclass ofcharacters listed java.lang.Numberhere representing the parsedare used in numericnon-localized stringpatterns. DecimalFormat chooses the most economical subclass thatLocalized can representpatterns use the numeric string. This means mostcorresponding integer values are returnedcharacters taken from this asformatter's LongDecimalFormatSymbols objects noobject matter how they areinstead and these characters written:lose "17"their andspecial "17status.000" both parse toTwo Long(17).exceptions Values that cannot fit into aare the currency sign and quote Longwhich are returned asnot Doubleslocalized. This includes

values with astring. Doing sothe"10
Symbol fractionalLocation partLocalized infiniteMeaning values
NaN0 andNumber theYes valueDigit -0.0.
DecimalFormat# does not decideNumber whetherYes toDigit return azero shows Doubleas or aabsent
Long. basedNumber onYes theDecimal presence of aseparator or monetary decimal separator in the source
- wouldNumber preventYes integersMinus that overflowsign
mantissa ofNumber aYes doubleGrouping such asseparator
E 000Number 000Yes 000Separates 000mantissa 000.00"and from being parsed accuratelyexponent in scientific notation. Currently theNeed only classes thatnot be quoted DecimalFormatin returns areprefix or Longsuffix. and
Double; but callers should not rely onSubpattern this.boundary CallersYes maySeparates use thepositive and Numbernegative methodssubpatterns doubleValue
longValue% etc. to obtain the type theyPrefix want.or Ifsuffix DecimalFormat.parse(StringYes ParsePosition)Multiply fails to parse a string it returnsby 100 and show as percentage
null\u2030 leaves thePrefix ParsePositionor indexsuffix unchangedYes andMultiply sets theby 1000 ParsePositionand errorshow index.as The convenience methodper mille
DecimalFormat.parse(String)¤ indicates parse failure by throwing a (ParseException\u00A4. Special) ValuesPrefix NaNor issuffix formattedNo asCurrency a single character typicallysign replaced by currency \uFFFDsymbol. This characterIf is determineddoubled replaced by theinternational DecimalFormatSymbolscurrency objectsymbol. This is theIf only value for whichpresent in a pattern the prefixes andmonetary suffixes are notdecimal separator is used. Infinity is formattedinstead as a singleof the decimal characterseparator. typically
\u221E' with the positivePrefix or negative prefixes andsuffix suffixesNo applied.Used The infinity character is determined by theto quote special characters in a prefix DecimalFormatSymbolsor object.suffix Negativefor zero (example "-0'#'#") parsesformats 123 to Double(-0.0)"#123". unlessTo isParseIntegerOnly()create is true in which case it parsesa single quote itself use two in toa row: Long(0)"# o''clock".

Scientific Notation

Numbers in scientific notation are expressed as the product of a mantissa and a power of ten for example 1234 can be expressed as 1.234 x 10^3. The mantissa is often in the range 1.0 < x <10.0 but it need not be. DecimalFormat can be instructed to format and parse scientific notation only via a pattern; there is currently no factory method that creates a scientific notation format. In a pattern the exponent character immediately followed by one or more digit characters indicates scientific notation. Example: "0.###E0" formats the number 1234 as "1.234E3".

Pattern

Rounding

SyntaxDecimalFormat uses patternhalf-even :=rounding pos_pattern{';'(see negROUND_pattern} posHALF_pattern :=EVEN {prefix}number{suffix}for neg_patternformatting. :=

Digits

{prefix}number{suffix}For numberformatting :=DecimalFormat integer{'.'uses fraction}{exponent}the prefixten :=consecutive '\u0000'..'\uFFFD'characters -starting special_characterswith suffixthe :=localized '\u0000'..'\uFFFD'zero -digit special_charactersdefined integerin :=the min_intDecimalFormatSymbols |object '#'as |digits. '#'For integer |parsing these '#'digits ' ' integeras well as min_intall :=Unicode '0'decimal |digits '0'as min_intdefined |by '0'Character.digit 'are 'recognized. min_int

Special fractionValues

:=

NaN '0'*is '#'*formatted exponentas :=a 'E'single '0'character '0'*typically &#3292; Notation: X* 0 or more instances of X { X } 0 or 1 instances of X X | Y either X or Y X.uFFFD.Y anyThis character fromis X up todetermined by the YDecimalFormatSymbols inclusiveobject. S - T characters in S except those in T This is the only value for which the prefixes and suffixes Specialare Patternnot Charactersused.

Many charactersInfinity is informatted as a pattern are takensingle character typically literally\; theyu221E are matched during parsing and output unchanged during formattingwith the positive or negative prefixes and suffixes applied. SpecialThe characters on the other hand standinfinity character is determined by the forDecimalFormatSymbols otherobject. characters

Negative stringszero or("-0") classes ofparses to charactersDouble(-0. They must be quoted0) unless noted otherwise if they areisParseIntegerOnly() to appearis true in thewhich prefix or suffix ascase it parses to literalsLong(0). The

Synchronization

characters listed here

Decimal formats are used ingenerally non-localizednot patternssynchronized. Localized patterns use the corresponding characters taken from this formatter'sIt DecimalFormatSymbolsis object instead and these characters lose their special statusrecommended to create separate format instances for each thread. TwoIf exceptions are the currency sign and quote which are not localizedmultiple threads access a format concurrently it must be synchronized externally.

Example

SymbolLocationLocalized
 Meaning// 0NumberYDigitPrint #NumberYDigitout zero shows asa number using absentthe .NumberYDecimallocalized separator or monetarynumber integer currency decimal// separatorand -NumberYMinuspercent signformat for NumberYGroupingeach separatorlocale ENumberYLocale[] Separateslocales mantissa= andNumberFormat.getAvailableLocales(); exponent in scientificdouble myNumber = notation-1234.56; NeedNumberFormat notform; befor quoted(int inj=0; prefixj<; or++j) suffix.{ System.out.println("FORMAT");Subpattern boundaryY Separatesfor positive(int and negativei = subpatterns0; %Prefixi or<locales.length; suffixYMultiply++i) by 100{ if and(locales[i].getCountry().length() show== as0) percentage{ \continue;u2030Prefix or suffixY Multiply by 1000 and// showSkip aslanguage-only perlocales mille} ¤System.out.print(\u00A4locales[i].getDisplayName()Prefix); orswitch suffixN(j) Currency{ signcase replaced0: by currency symbolform = NumberFormat. IfgetInstance(locales[i]); doubledbreak; replacedcase by1: international currency symbolform = NumberFormat. If present in a patterngetIntegerInstance(locales[i]); thebreak; monetarycase decimal2: separator isform = usedNumberFormat.getCurrencyInstance(locales[i]); insteadbreak; ofdefault: the decimal separatorform = NumberFormat. 'Prefix orgetPercentInstance(locales[i]); suffixNbreak; Used} toif quote(form specialinstanceof charactersDecimalFormat) in{ aSystem.out.print(": prefix or" + suffix((DecimalFormat) forform).toPattern()); example} "'#'#System.out.print(" formats-> 123 to" + "#123"form.format(myNumber)); To createtry { aSystem.out.println(" single-> quote itself" + useform.parse(form.format(myNumber))); two in} catch a(ParseException row:e) "#{} o''clock".} } 
@see java.text.FormatJava Tutorial @see java.text.NumberFormat @see java.text.ChoiceFormatDecimalFormatSymbols @see java.text.ParsePosition @version 1.59 0268 12/0903/01 @author Mark Davis @author Alan Liu
Class DecimalFormat, constructor DecimalFormat()

CreateCreates a DecimalFormat using the default pattern and symbols for the default locale. This is a convenient way to obtain a DecimalFormat when internationalization is not the main concern.

To obtain standard formats for a given locale use the factory methods on NumberFormat such as getNumberInstance. These factories will return the most appropriate sub-class of NumberFormat for a given locale. @see java.text.NumberFormat#getInstance @see java.text.NumberFormat#getNumberInstance @see java.text.NumberFormat#getCurrencyInstance @see java.text.NumberFormat#getPercentInstance

Class DecimalFormat, constructor DecimalFormat(String)

CreateCreates a DecimalFormat fromusing the given pattern and the symbols for the default locale. This is a convenient way to obtain a DecimalFormat when internationalization is not the main concern.

To obtain standard formats for a given locale use the factory methods on NumberFormat such as getNumberInstance. These factories will return the most appropriate sub-class of NumberFormat for a given locale. @param pattern A non-localized pattern string. @exception NullPointerException if pattern is null @exception IllegalArgumentException if the given pattern is invalid. @see java.text.NumberFormat#getInstance @see java.text.NumberFormat#getNumberInstance @see java.text.NumberFormat#getCurrencyInstance @see java.text.NumberFormat#getPercentInstance

Class DecimalFormat, constructor DecimalFormat(String, DecimalFormatSymbols)

CreateCreates a DecimalFormat fromusing the given pattern and symbols. Use this constructor when you need to completely customize the behavior of the format.

To obtain standard formats for a given locale use the factory methods on NumberFormat such as getInstance or getCurrencyInstance. If you need only minor adjustments to a standard format you can modify the format returned by a NumberFormat factory method. @param pattern a non-localized pattern string @param symbols the set of symbols to be used @exception NullPointerException if any of the given arguments is null @exception IllegalArgumentException if the given pattern is invalid @see java.text.NumberFormat#getInstance @see java.text.NumberFormat#getNumberInstance @see java.text.NumberFormat#getCurrencyInstance @see java.text.NumberFormat#getPercentInstance @see java.text.DecimalFormatSymbols

Class DecimalFormat, void applyLocalizedPattern(String)

Apply the given pattern to this Format object. The pattern is assumed to be in a localized notation. A pattern is a short-hand specification for the various formatting properties. These properties can also be changed individually through the various setter methods.

There is no limit to integer digits are set by this routine since that is the typical end-user desire; use setMaximumInteger if you want to set a real value. For negative numbers use a second pattern separated by a semicolon

Example "# #00.0#" -> 1 234.56

This means a minimum of 2 integer digits 1 fraction digit and a maximum of 2 fraction digits.

Example: "# #00.0#;(# #00.0#)" for negatives in paranthesesparentheses.

In negative patterns the minimum and maximum counts are ignored; these are presumed to be set in the positive pattern. @exception NullPointerException if pattern is null @exception IllegalArgumentException if the given pattern is invalid.

Class DecimalFormat, void applyPattern(String)

Apply the given pattern to this Format object. A pattern is a short-hand specification for the various formatting properties. These properties can also be changed individually through the various setter methods.

There is no limit to integer digits are set by this routine since that is the typical end-user desire; use setMaximumInteger if you want to set a real value. For negative numbers use a second pattern separated by a semicolon

Example "# #00.0#" -> 1 234.56

This means a minimum of 2 integer digits 1 fraction digit and a maximum of 2 fraction digits.

Example: "# #00.0#;(# #00.0#)" for negatives in paranthesesparentheses.

In negative patterns the minimum and maximum counts are ignored; these are presumed to be set in the positive pattern. @exception NullPointerException if pattern is null @exception IllegalArgumentException if the given pattern is invalid.

Class DecimalFormat, StringBuffer format(double, StringBuffer, FieldPosition)

Formats a double to produce a string. @param number The double to format @param toAppendToresult where the text is to be appended @param fieldPosition On input: an alignment field if desired. On output: the offsets of the alignment field. @return The value passed in as theformatted result parameternumber string @see java.text.FieldPosition
Class DecimalFormat, StringBuffer format(long, StringBuffer, FieldPosition)

Format a long to produce a string. @param number The long to format @param toAppendToresult where the text is to be appended @param fieldPosition On input: an alignment field if desired. On output: the offsets of the alignment field. @return The value passed in as theformatted result parameternumber string @see java.text.FieldPosition
Class DecimalFormat, Number parse(String, ParsePosition)

Returns an instanceParses text from ofa string to produce a Number. with a value matching

The method attempts to parse text starting at the index given by pos. If parsing succeeds then the index of pos is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string) and the parsed number is returned. The updated pos can be used to indicate the starting point for the next call to this method. If an error occurs then the index of pos is not changed the error index of pos is set to the index of the character where the error occurred and null is returned.

The most economical subclass that can represent all the bits of the sourcenumber given by the string is chosen. @paramMost text theinteger values stringare returned as Long objects no matter how they are written: "17" and "17.000" both parse to beLong(17). parsedValues @paramthat parsePosition on entrycannot fit into wherea Long are returned as Doubles. This includes values with a fractional part infinite values NaN and the value -0.0. DecimalFormat does not decide whether to beginreturn a parsing;Double or a Long based on exitthe presence justof a decimal pastseparator in the lastsource parsedstring. characterDoing so would prevent integers that overflow the mantissa of a double such as "10 000 000 000 000 000.00" If parsingfrom being failsparsed accurately. Currently the index will notonly classes that moveparse returns are Long and Double but callers should not rely on this. Callers may use the Number methods doubleValue longValue etc. to obtain the type they want.

DecimalFormat parses all Unicode characters that represent decimal digits as defined by Character.digit(). In addition DecimalFormat also recognizes as digits the ten consecutive characters starting with the localized zero digit defined in the DecimalFormatSymbols object. @param text the string to be parsed @param pos A ParsePosition object with index and error index will beinformation as setdescribed above. @return the parsed value or null if the parse fails @exception NullPointerException if text or pos is null.


Class DecimalFormatSymbols

This class represents the set of symbols (such as the decimal separator the grouping separator and so on) needed by DecimalFormat to format numbers. DecimalFormat creates for itself an instance of DecimalFormatSymbols from its locale data. If you need to change any of these symbols you can get the DecimalFormatSymbols object from your DecimalFormat and modify it. @see java.util.Locale @see DecimalFormat @version 1.30 0135 12/1903/0001 @author Mark Davis @author Alan Liu
Class DecimalFormatSymbols, constructor DecimalFormatSymbols(Locale)

Create a DecimalFormatSymbols object for the given locale. @exception NullPointerException if locale is null
Class DecimalFormatSymbols, String getCurrencySymbol()

ReturnReturns the stringcurrency denoting the localsymbol for the currency of these DecimalFormatSymbols in their locale.
Class DecimalFormatSymbols, String getInfinity()

Gets the characterstring used to represent infinity. Almost always left unchanged.
Class DecimalFormatSymbols, String getInternationalCurrencySymbol()

ReturnReturns the internationalISO string denoting the4217 currency code localof the currency of these DecimalFormatSymbols.
Class DecimalFormatSymbols, char getMonetaryDecimalSeparator()

ReturnReturns the monetary decimal separator.
Class DecimalFormatSymbols, String getNaN()

Gets the characterstring used to represent NaN"not a number". Almost always left unchanged.
Class DecimalFormatSymbols, void setCurrencySymbol(String)

SetSets the stringcurrency denoting the localsymbol for the currency of these DecimalFormatSymbols in their locale.
Class DecimalFormatSymbols, void setDecimalSeparator(char)

SetSets the character used for decimal sign. Different for French etc.
Class DecimalFormatSymbols, void setDigit(char)

SetSets the character used for a digit in a pattern.
Class DecimalFormatSymbols, void setGroupingSeparator(char)

SetSets the character used for thousands separator. Different for French etc.
Class DecimalFormatSymbols, void setInfinity(String)

SetSets the characterstring used to represent infinity. Almost always left unchanged.
Class DecimalFormatSymbols, void setInternationalCurrencySymbol(String)

SetSets the internationalISO string4217 denotingcurrency code of the currency of these DecimalFormatSymbols. If the currency code is valid (as defined by Currency.getInstance this also sets the currency attribute to the corresponding Currency instance and the currency symbol attribute to the currency's symbol in the DecimalFormatSymbols' locale. If the currency code is not valid then the localcurrency attribute is set to null and the currency symbol attribute is not modified. @see #setCurrency @see #setCurrencySymbol
Class DecimalFormatSymbols, void setMinusSign(char)

SetSets the character used to represent minus sign. If no explicit negative format is specified one is formed by prefixing minusSign to the positive format.
Class DecimalFormatSymbols, void setMonetaryDecimalSeparator(char)

SetSets the monetary decimal separator.
Class DecimalFormatSymbols, void setNaN(String)

SetSets the characterstring used to represent NaN"not a number". Almost always left unchanged.
Class DecimalFormatSymbols, void setPatternSeparator(char)

SetSets the character used to separate positive and negative subpatterns in a pattern.
Class DecimalFormatSymbols, void setPerMill(char)

SetSets the character used for mille percent sign. Different for Arabic etc.
Class DecimalFormatSymbols, void setPercent(char)

SetSets the character used for percent sign. Different for Arabic etc.
Class DecimalFormatSymbols, void setZeroDigit(char)

SetSets the character used for zero. Different for Arabic etc.

Class FieldPosition

FieldPosition is a simple class used by Format and its subclasses to identify fields in formatted output. Fields arecan be identified byin constantstwo ways:

FieldPosition keeps track of the position of the field within the formatted output with two indices: the index of the first character of the field and the index of the last character of the field.

One version of the format method in the various Format classes requires a FieldPosition object as an argument. You use this format method to perform partial formatting or to get information about the formatted output (such as the position of a field).

If you are interested in the positions of all attributes in the formatted string use the Format method formatToCharacterIterator. @version 1.16 0118 12/1903/0001 @author Mark Davis @see java.text.Format


Class Format

Format is an abstract base class for formatting locale-sensitive information such as dates messages and numbers.

Format defines the programming interface for formatting locale-sensitive objects into Strings (the format method) and for parsing Strings back into objects (the parseObject method). Any

StringGenerally formatteda byformat's formatparseObject is guaranteedmethod tomust be parseable by parseObject.able If formatting is unsuccessful because theto parse any string formatted by its Format object cannot format the type of objectmethod. specifiedHowever formatthere throws anmay be IllegalArgumentException.exceptional Otherwise if therecases where this is somethingnot illformedpossible. about the objectFor example a format returns the Unicodemethod replacement charactermight create \\uFFFD.two If there isadjacent integer numbers with no matchseparator when parsingin between parseObject(String)and throws ain this ParseExceptioncase andthe parseObject(String ParsePosition) leaves thecould not ParsePositiontell indexwhich member unchanged and returnsdigits belong to which nullnumber.

Subclassing:

The Java 2 platform provides three concretespecialized subclasses of Format-- DateFormat MessageFormat and NumberFormat--for formatting dates messages and numbers respectively.

Concrete subclasses must implement these twothree methods:

  1. format(Object obj StringBuffer toAppendTo FieldPosition pos)
  2. parseObjectformatToCharacterIterator(Object obj)
  3. parseObject(String source ParsePosition pos)
These general methods allow polymorphic parsing and formatting of objects and are used for example by MessageFormat. Subclasses often also provide additional format methods for specific input types as well as parse methods for specific result types. Any parse method that does not take a ParsePosition argument should throw ParseException when no text in the required format is at the beginning of the input text.

Most subclasses will also implement the following twofactory methods:

  1. getInstance for getting a useful format object appropriate for the current locale
  2. getInstance(Locale) for getting a useful format object appropriate for the specified locale
In addition some subclasses may also choose to implement other getXxxxInstance methods for more specialized control. For example the NumberFormat class provides getPercentInstance and getCurrencyInstance methods for getting specialized number formatters.

Subclasses of Format that allow programmers to create objects for locales (with getInstance(Locale) for example) must also implement the following class method:

 public static Locale[] getAvailableLocales() 

And finally subclasses may define a set of constants to identify the various fields in the formatted output. These constants are used to create a FieldPosition object which identifies what information is contained in the field and its position in the formatted result. These constants should be named item_FIELD where item identifies the field. For examples of these constants see ERA_FIELD and its friends in DateFormat

Synchronization

Formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently it must be synchronized externally. @see java.text.ParsePosition @see java.text.FieldPosition @see java.text.NumberFormat @see java.text.DateFormat @see java.text.MessageFormat @version 1.28 0131 12/1903/0001 @author Mark Davis

Class Format, Object clone()

OverridesCreates Cloneableand returns a copy of this object. @return a clone of this instance.
Class Format, String format(Object)

Formats an object to produce a string. SubclassesThis will override the StringBufferis equivalent to
versionStringBuffe ofFieldPosition) format}(obj new StringBuffer() new FieldPosition(0)).toString();
@param obj The object to format @return Formatted string. @exception IllegalArgumentException whenif the Format cannot format the type ofgiven object. @see MessageFormat @see java.text.Format#format(Object StringBuffer FieldPosition)
Class Format, StringBuffer format(Object, StringBuffer, FieldPosition)

Formats an object to produceand aappends string.the Subclasses will implement for particular objectresulting text to a given string suchbuffer. as:If the StringBufferpos formatargument (Numberidentifies obj StringBuffera field toAppendTo)used Number parseby the (Stringformat str)then These general routines allow polymorphic parsingits indices are set to the beginning and formattingend for objects such as the MessageFormatof the first such field encountered. @param obj The object to format @param toAppendTo where the text is to be appended @param pos OnA input:FieldPosition an alignmentidentifying a field if desired. On output: the offsets ofin the alignmentformatted field.text @return the valuestring buffer passed in as toAppendTo (thiswith allows chaining asformatted text appended with@exception StringBuffer.append())NullPointerException if toAppendTo or pos is null @exception IllegalArgumentException whenif the Format cannot format the given object. @see MessageFormat @see java.text.FieldPosition
Class Format, Object parseObject(String)

Parses atext from the beginning of the given string to produce an object. The method may not use the entire text of the given string. @param source A String whose beginning should be parsed. @return An Object parsed from the string. @exception ParseException if the beginning of the specified string iscannot be invalidparsed.
Class Format, Object parseObject(String, ParsePosition)

Parses text from a string to produce an object. Subclasses will typically implement for particular object such as:

String formatThe method attempts (Numberto obj);parse String formattext starting (longat obj);the String formatindex given (doubleby obj);pos. Number parseIf parsing (Stringsucceeds str);then the @paramindex statusof Input-Outputpos parameter.is Beforeupdated calling setto the status.index toafter the offset you wantlast to startcharacter used (parsing at in thedoes not necessarily source.use After callingall characters status.indexup isto the end of the text you parsed.string) If error occurs indexand the parsed object is unchangedreturned. When parsing leading whitespace is discarded (with successful parse) while trailing whitespace is leftThe asupdated is.pos Example:can Parsingbe "_12_xy"used (whereto _ represents aindicate the starting space)point for a number with index == 0 will result in the number 12 with status.indexnext updatedcall to 3 (just before the secondthis space)method. Parsing a secondIf time will result in a ParseException sincean error occurs then the index of "xy"pos is not a numberchanged and leavethe error index at 3. Subclasses will typically supply specificof parsepos methods that return different typesis set to the index of values. Since methodsthe can'tcharacter overload on return types these will typicallywhere the error occurred and null is bereturned. named@param "parse"source whileA thisString polymorphic method will alwayspart of which should be called parseObjectparsed. Any parse method that does not take a status should throw@param ParseException whenpos A noParsePosition text in the required format is at the start positionobject with index and error index information as described above. @return An Object parsed from the string. In case of error returns null. @seeexception java.textNullPointerException if pos is null.ParsePosition


Class MessageFormat

MessageFormat provides a means to produce concatenated messages in language-neutral way. Use this to construct messages displayed for end users.

MessageFormat takes a set of objects formats them then inserts the formatted strings into the pattern at the appropriate places.

Note: MessageFormat differs from the other Format classes in that you create a MessageFormat object with one of its constructors (not with a getInstance style factory method). The factory methods aren't necessary because MessageFormat itself doesn't require any compleximplement setup forlocale specific abehavior. givenAny locale. In factspecific MessageFormatbehavior doesn'tis implement any locale specific behavior atdefined by the pattern that you all.provide It just needs to be set up onas well as the subformats used for inserted aarguments. sentence

Patterns by sentenceand Their basis.Interpretation

MessageFormat Here are some examples of usageuses patterns of the following form:
 Object[]MessageFormatPattern: argumentsString =MessageFormatPattern FormatElement String FormatElement: { newArgumentIndex Integer(7)} new{ Date(System.currentTimeMillis())ArgumentIndex "aFormatType disturbance in} { theArgumentIndex Force"FormatType FormatStyle }; StringFormatType: result =one of MessageFormat.format( "Atnumber {1date time} onchoice {1FormatStyle: date}short there wasmedium long {2}full on planetinteger currency {0percent numberSubformatPattern integer}."String: arguments);StringPartopt outputString StringPart StringPart: At'' 12' QuotedString ' UnquotedString SubformatPattern: SubformatPatternPartopt SubformatPattern SubformatPatternPart SubFormatPatternPart:30 PM ' onQuotedPattern Jul' 3UnquotedPattern 2053
there was

Within a disturbance inString the"''" Force on planet 7represents a single quote. A QuotedString Typically the message format will comecan contain arbitrary characters except single fromquotes; resources and the arguments willthe surrounding single quotes are beremoved. dynamicallyAn setUnquotedString atcan runtime.contain Examplearbitrary characters 2:except single quotes Object[]and testArgs =left curly {newbrackets. Long(3)Thus "MyDisk"};a MessageFormat form = newstring that should result MessageFormat(in "Thethe diskformatted \message "'{10}\'" containscan be written as "'''{'0} file(s).''"); System.out.println(formor "'''{0}'''".format(testArgs)); //

output withWithin a SubformatPattern different testArgsrules output:apply. TheA diskQuotedPattern "MyDisk"can contains 0contain arbitrary file(s).characters output:except Thesingle diskquotes; "MyDisk"but contains 1the surrounding file(s).single output:quotes Theare disknot "MyDisk"removed contains 1 273so they may file(s).be interpreted by the Thesubformat. pattern isFor example of"{1 thenumber form:$'#' ##}" messageFormatPatternwill produce :=a string (number format "{"with messageFormatElementthe "}"pound-sign stringquoted )*with messageFormatElementa :=result argumentsuch {as: "$#31 45". elementFormatAn }UnquotedPattern elementFormatcan :=contain "time"arbitrary { " " datetimeStyle } |characters except single quotes but curly "date"braces { " " datetimeStylewithin it must be }balanced. |For "numberexample "ab { "0} de" numberStyle } |and "choice"ab {'}' de" " choiceStyle } datetimeStyleare valid subformat patterns :=but "short"ab |{0'}' "mediumde" |and "long"ab |} "fullde" |are dateFormatPatternnot. numberStyle

Warning:=
The "currency"rules |for "percent"using |quotes "integer"within | numberFormatPattern choiceStylemessage format patterns :=unfortunately choiceFormatPattern If therehave shown to be somewhat isconfusing. noIn elementFormatparticular thenit theisn't argument must be a string which isalways obvious to localizers whether single quotes substituted.need If there is noto be doubled or dateTimeStylenot. orMake numberStylesure thento inform localizers about the default format is usedrules and tell them (for example NumberFormat.getInstanceby DateFormat.getTimeInstanceusing orcomments DateFormat.getInstance).in In stringsresource bundle source singlefiles) quotes can be used to quotewhich strings will be processed by theMessageFormat. "{"Note (curlythat brace)localizers ifmay necessary.need A realto use single quotequotes is represented byin translated strings 'where the original version doesn't have them. Inside a

messageFormatElementThe quotesArgumentIndex arevalue notis removed.a Fornon-negative exampleinteger {1written numberusing $the digits '#0' ##}through will'9' produce a number format withand represents an index into the pound-signarguments quoted witharray passed ato the format methods or the result sucharray as:returned "$#31by 45"the parse methods.

IfThe aFormatType patternand isFormatStyle values are used thento create unquoteda bracesFormat ininstance for the patternformat element. if any mustThe following table match:shows that ishow the "abvalues {0}map de"to andFormat "abinstances. '}'Combinations de"not shown in the table are okillegal. butA "abSubformatPattern {0'}'must de"be anda "abvalid }pattern de"string arefor notthe Format subclass used.

The argument iswhichtheanbeIttoarray.argumentsofforathrown.ahasthethen
Format aType numberFormat fromStyle 0Subformat to 9Created
(none) correspondsnull to
number arguments(none) presentedNumberFormat.getInstance(getLocale()) in
integer arrayNumberFormat.getIntegerInstance(getLocale()) to
currency formattedNumberFormat.getCurrencyInstance(getLocale())
percent isNumberFormat.getPercentInstance(getLocale()) ok
SubformatPattern havenew unusedDecimalFormat(subformatPattern argumentsnew inDecimalFormatSymbols(getLocale())) the
date With(none) missingDateFormat.getDateInstance(DateFormat.DEFAULT argumentsgetLocale()) or
short thatDateFormat.getDateInstance(DateFormat.SHORT aregetLocale()) not
medium theDateFormat.getDateInstance(DateFormat.DEFAULT rightgetLocale()) class
long theDateFormat.getDateInstance(DateFormat.LONG specifiedgetLocale()) format
full ParseExceptionDateFormat.getDateInstance(DateFormat.FULL getLocale()) is
SubformatPattern new SimpleDateFormat(subformatPattern getLocale()) First
formattime checks(none) toDateFormat.getTimeInstance(DateFormat.DEFAULT seegetLocale()) if
short FormatDateFormat.getTimeInstance(DateFormat.SHORT getLocale()) object
medium beenDateFormat.getTimeInstance(DateFormat.DEFAULT specifiedgetLocale()) for
long argumentDateFormat.getTimeInstance(DateFormat.LONG withgetLocale()) the
setFormatsfull methodDateFormat.getTimeInstance(DateFormat.FULL IfgetLocale()) so
SubformatPattern formatnew usesSimpleDateFormat(subformatPattern thatgetLocale())
Formatchoice objectSubformatPattern tonew formatChoiceFormat(subformatPattern) the
argument

Usage Information

Here are some examples of usage:

 Object[] arguments = { new Integer(7) new Date(System.currentTimeMillis()) "a Otherwisedisturbance in the argumentForce" is}; formattedString result = MessageFormat.format( "At {1 time} on {1 date} there was based{2} on theplanet object's{0 number typeinteger}." Ifarguments); theoutput: argumentAt is12:30 PM on Jul 3 2053 there was a Numberdisturbance thenin formatthe usesForce NumberFormaton planet 7.getInstance to
Typically the message format will come from resources and the argumentarguments will be dynamically set at runtime.

Example 2:

 Object[] testArgs = {new Long(3) "MyDisk"}; if the argument isMessageFormat form = new aMessageFormat( Date"The thendisk \"{1}\" contains {0} file(s)."); System.out.println(form.format(testArgs)); uses// DateFormatoutput with different testArgs output: The disk "MyDisk" contains 0 file(s).getDateTimeInstance tooutput: format theThe disk argument"MyDisk" contains 1 file(s). Otherwiseoutput: it usesThe disk the"MyDisk" toStringcontains method1 273 file(s). 

For more sophisticated patterns you can use a ChoiceFormat to get output such as:

 MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}."); double[] filelimits = {0 1 2}; String[] filepart = {"no files" "one file" "{0 number} files"}; ChoiceFormat fileform = new ChoiceFormat(filelimits filepart); form.setFormatsetFormatByArgumentIndex(10 fileform); // NOT zero see below Object[] testArgs = {new Long(12373) "MyDisk"}; System.out.println(form.format(testArgs)); // output with different testArgs output: The disk "MyDisk" contains no files. output: The disk "MyDisk" contains one file. output: The disk "MyDisk" contains 1 273 files. 
You can either do this programmatically as in the above example or by using a pattern (see ChoiceFormat for more information) as in:
 form.applyPattern( "There {0 choice 0#are no files|1#is one file|1#<are {0 number integer} files}."); 

Note: As we see above the string produced by a ChoiceFormat in MessageFormat is treated specially; occurances of '{' are used to indicated subformats and cause recursion. If you create both a MessageFormat and ChoiceFormat programmatically (instead of using the string patterns) then be careful not to produce a format that recurses on itself which will cause an infinite loop.

Note: formats are numbered by order of variable in the string. This is not the same as the argument numbering For example: with "abc{2}def{3}ghi{0}..." format0 affects the first variable {2} format1 affects the second variable {3} format2 affects the second variable {0} and so on. When a single argument is parsed more than once in the string the last match will be the final result of the parsing. For example

 MessageFormat mf = new MessageFormat("{0 number #.##} {0 number #.#}"); Object[] objs = {new Double(3.1415)}; String result = mf.format( objs ); // result now equals "3.14 3.1" objs = null; objs = mf.parse(result new ParsePosition(0)); // objs now equals {new Double(3.1)} 

Likewise parsing with a MessageFormat object using patterns containing multiple occurances of the same argument would return the last match. For example

 MessageFormat mf = new MessageFormat("{0} {0} {0}"); String forParsing = "x y z"; Object[] objs = mf.parse(forParsing new ParsePosition(0)); // result now equals {new String("z")} 

Synchronization

You can useMessage formats are setLocalenot followedsynchronized. byIt applyPatternis (andrecommended then possiblyto create setFormat)separate toformat re-initializeinstances afor MessageFormateach withthread. If multiple threads access a differentformat localeconcurrently it must be synchronized externally. @see java.util.Locale @see Format @see NumberFormat @see DecimalFormat @see ChoiceFormat @version 1.38 0147 12/1903/0001 @author Mark Davis

Class MessageFormat, constructor MessageFormat(String)

Constructs witha MessageFormat for the default locale and the specified pattern. The constructor first sets the locale then parses the pattern and creates a list of subformats for the format elements contained in it. Patterns and their interpretation are specified in the class description. @seeparam MessageFormat#applyPatternpattern the pattern for this message format @exception IllegalArgumentException if the pattern is invalid
Class MessageFormat, void applyPattern(String)

Sets the pattern used by this message format. The method parses the pattern and creates a list of subformats for the format elements contained in it. SeePatterns and their interpretation are specified in the class description. @param pattern the pattern for this message format @exception IllegalArgumentException if the pattern is invalid
Class MessageFormat, Object clone()

OverridesCreates Cloneableand returns a copy of this object. @return a clone of this instance.
Class MessageFormat, boolean equals(Object)

Equality comparisioncomparison between two message format objects
Class MessageFormat, StringBuffer format(Object, StringBuffer, FieldPosition)

Returns pattern with formattedFormats an array of objects. If source is nulland appends the originalMessageFormat's pattern is returnedwith format ifelements replaced source contains nullby the formatted objects to the formattedprovided resultStringBuffer. This will substitute each argumentis equivalent to
with{@link the#format(java.lang.Object[] stringjava.lang.StringBuffer "null"java.text.FieldPosition) format}((Object[]) arguments result pos)
@param sourcearguments an array of objects to be formatted &and substituted. @param result where text is appended. @param ignorepos On input: an alignment field if desired. On output: the offsets of the alignment field. @exception IllegalArgumentException if an argument in nothe usefularguments
statusarray is returnednot of the type expected by the format element(s) that use it.
Class MessageFormat, StringBuffer format(Object[], StringBuffer, FieldPosition)

ReturnsFormats an array of objects and appends the MessageFormat's pattern with format elements replaced by the formatted objects to the provided StringBuffer. If source is

The text nullsubstituted for the originalindividual patternformat elements is returned if source contains null objectsderived from the current subformat of the formattedformat resultelement willand the arguments element at substitutethe format eachelement's argument withindex as indicated by the stringfirst matching line of the following table. An argument is unavailable if arguments is null or has fewer than argumentIndex+1 elements.

Subformat Argument Formatted Text
any unavailable "{" + argumentIndex + "}"
any null "null"
instanceof ChoiceFormat any subformat.format(argument).indexOf('{') >= 0
(new MessageFormat(subformat.format(argument) getLocale())).format(argument) : subformat.format(argument)
= null any subformat.format(argument)
null instanceof Number NumberFormat.getInstance(getLocale()).format(argument)
null instanceof Date DateFormat.getDateTimeInstance(DateFormat.SHORT DateFormat.SHORT getLocale()).format(argument)
null instanceof String argument
null any argument.toString()

If pos is non-null and refers to Field.ARGUMENT the location of the first formatted string will be returned. @param sourcearguments an array of objects to be formatted &and substituted. @param result where text is appended. @param ignorepos On input: an alignment field if desired. On output: the offsets of the alignment field. @exception IllegalArgumentException if an argument in nothe usefularguments statusarray is returnednot of the type expected by the format element(s) that use it.

Class MessageFormat, String format(String, Object[])

ConvenienceCreates routinea MessageFormat with the given pattern and uses it to format the given arguments. Avoids explicit creationThis is equivalent ofto
(new MessageFormat}(pattern)).{@lin #format(java.lang.Object[] java.lang.StringBuffer java.text.FieldPosition) format}(arguments new StringBuffer() null).toString()
@exception IllegalArgumentException if the pattern is invalid or if an argument in the arguments array is not of the type expected by the
butformat doesn'telement(s) allow future optimizationsthat use it.
Class MessageFormat, Format[] getFormats()

Gets the formats thatused for the format elements in the werepreviously set withpattern string. The order of formats in the returned array corresponds to the order of format elements in the pattern setFormatsstring. See

Since the order of format elements in a pattern string often changes during localization it's generally better to use the getFormatsByArgumentIndex method which assumes an order of formats corresponding to the order of elements in the classarguments array description aboutpassed to the format methods numberingor the result array returned by the parse methods. @return the formats used for the format elements in the pattern

Class MessageFormat, Locale getLocale()

Gets the locale. Thisthat's locale is used for fetchingused when creating or comparing defaultsubformats. number@return orthe datelocale used formatwhen information.creating or comparing subformats
Class MessageFormat, Object[] parse(String)

Parses text from the beginning of the given string to produce an object array. DoesThe method may not yetuse the handle recursionentire text (whereof the substitutedgiven stringsstring. contain

{n}See references.the ParsePosition) method for more information on message parsing. @param source A String whose beginning should be parsed. @return An Object array parsed from the string. @exception ParseException if the beginning of the specified string can'tcannot be parsed.

Class MessageFormat, Object[] parse(String, ParsePosition)

Parses the string.

Caveats: The parse may fail in a number of circumstances. For example:

When the parse fails use ParsePosition.getErrorIndex() to find out where in the string did the parsing failed. The returned error index is the starting offset of the sub-patterns that the string is comparing with. For example if the parsing string "AAA {0} BBB" is comparing against the pattern "AAD {0} BBB" the error index is 0. When an error occurs the call to this method will return null. If the sorucesource is null return an empty array.
Class MessageFormat, Object parseObject(String, ParsePosition)

Parses text from a string to produce an object array.

The method attempts to parse text starting at the index given by pos. If parsing succeeds then the index of pos is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string) and the parsed object array is returned. The updated pos can be used to indicate the starting point for the next call to this method. DoesIf an error occurs then the index of pos is not yetchanged the handle recursionerror index (of pos is set to the index of the character where the substituted strings containerror occurred and %nnull referencesis returned.

See the ParsePosition) method for more information on message parsing. @param source A String part of which should be parsed. @param pos A ParsePosition object with index and error index information as described above. @return An Object array parsed from the string. In case of error returns null. @exception NullPointerException if pos is null.

Class MessageFormat, void setFormat(int, Format)

Set aSets the format to beuse used on a variablefor the format element inwith the given format element index within the previously set pattern string. @paramThe format variableelement index is the zero-based number of the variableformat element incounting from the formatstart of the pattern string. This

Since the order of format elements in a pattern string often changes during localization it is notgenerally better to use the setFormatByArgumentIndex method which accesses format elements based on the argument numberindex they specify. If@param variableformatElementIndex is outthe index of rangea format anelement ArrayIndexOutOfBoundsExceptionwithin isthe thrown.pattern @param newFormat the format to use for the specified variableformat element @exception ArrayIndexOutOfBoundsException if formatElementIndex is equal to or larger than the number of format elements in the pattern string

Class MessageFormat, void setFormats(Format[])

Sets the formats to use onfor the format elements in the previously set pattern string. The order of formats in newFormats corresponds to the order of format elements in the pattern string.

If more formats are provided than needed by the pattern string the remaining ones are ignored. If fewer formats are provided than needed then only the first newFormats.length formats are parametersreplaced. See

Since the order of format elements in a pattern string often changes during localization it is generally better to use the setFormatsByArgumentIndex method which assumes an order of formats corresponding to the class description aboutorder of elements in the arguments array passed to the format methods or the result array returned by the parse numberingmethods. @param newFormats the new formats to use @exception NullPointerException if newFormats is null

Class MessageFormat, void setLocale(Locale)

ConstructsSets with the specifiedlocale to be used when creating or comparing subformats. This affects subsequent calls patternto the applyPattern and formatstoPattern methods foras well as to the argumentsformat inand thatformatToCharacterIterator patternmethods. @param locale the locale to be used when creating or comparing subformats
Class MessageFormat, String toPattern()

Gets theReturns a pattern representing the current state of the message format. SeeThe string is constructed from internal information and therefore does not necessarily equal the classpreviously descriptionapplied pattern. @return a pattern representing the current state of the message format

Class NumberFormat

NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats and what their names are.

NumberFormat helps you to format and parse numbers for any locale. Your code can be completely independent of the locale conventions for decimal points thousands-separators or even the particular decimal digits used or whether the number format is even decimal.

To format a number for the current Locale use one of the factory class methods:

 myString = NumberFormat.getInstance().format(myNumber); 
If you are formatting multiple numbers it is more efficient to get the format and use it multiple times so that the system doesn't have to fetch the information about the local language and country conventions multiple times.
 NumberFormat nf = NumberFormat.getInstance(); for (int i = 0; i  
To format a number for a different Locale specify it in the call to getInstance.
 NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH); 
You can also use a NumberFormat to parse numbers:
 myNumber = nf.parse(myString); 
Use getInstance or getNumberInstance to get the normal number format. Use getIntegerInstance to get an integer number format. Use getCurrencyInstance to get the currency number format. And use getPercentInstance to get a format for displaying percentages. With this format a fraction like 0.53 is displayed as 53%.

You can also control the display of numbers with such methods as setMinimumFractionDigits. If you want even more control over the format or parsing or want to give your users more control you can try casting the NumberFormat you get from the factory methods to a DecimalNumberFormatDecimalFormat. This will work for the vast majority of locales; just remember to put it in a try block in case you encounter an unusual one.

NumberFormat and DecimalFormat are designed such that some controls work for formatting and others work for parsing. The following is the detailed description for each these control methods

setParseIntegerOnly : only affects parsing e.g. if true "3456.78" -> 3456 (and leaves the parse position just after index 6) if false "3456.78" -> 3456.78 (and leaves the parse position just after index 8) This is independent of formatting. If you want to not show a decimal point where there might be no digits after the decimal point use setDecimalSeparatorAlwaysShown.

setDecimalSeparatorAlwaysShown : only affects formatting and only where there might be no digits after the decimal point such as with a pattern like "# ##0.##" e.g. if true 3456.00 -> "3 456." if false 3456.00 -> "3456" This is independent of parsing. If you want parsing to stop at the decimal point use setParseIntegerOnly.

You can also use forms of the parse and format methods with ParsePosition and FieldPosition to allow you to:

For example you can align numbers in two ways:
  1. If you are using a monospaced font with spacing for alignment you can pass the FieldPosition in your format call with field = INTEGER_FIELD. On output getEndIndex will be set to the offset between the last character of the integer and the decimal. Add (desiredSpaceCount - getEndIndex) spaces at the front of the string.
  2. If you are using proportional fonts instead of padding with spaces measure the width of the string in pixels from the start to getEndIndex. Then move the pen by (desiredPixelWidth - widthToAlignmentPoint) before drawing the text. It also works where there is no decimal but possibly additional characters at the end e.g. with parentheses in negative numbers: "(12)" for -12.

Synchronization

Number formats are generally not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently it must be synchronized externally. @see DecimalFormat @see ChoiceFormat @version 1.47 0157 12/1903/0001 @author Mark Davis @author Helena Shih

Class NumberFormat, StringBuffer format(Object, StringBuffer, FieldPosition)

Formats an object to produce a string. This general routines allows polymorphic parsing and formatting for objectstobjects. @param obj The object to format @param toAppendTo where the text is to be appended @param pos On input: an alignment field if desired. On output: the offsets of the alignment field. @return the value passed in as toAppendTo (this allows chaining as with StringBuffer.append()) @exception IllegalArgumentException when the Format cannot format the given object. @see java.text.FieldPosition
Class NumberFormat, NumberFormat getInstance()

Returns the default number format for the current default locale. The default format is one of the styles provided by the other factory methods: getNumberInstance getIntegerInstance getCurrencyInstance or getPercentInstance. Exactly which one is locale dependant.
Class NumberFormat, NumberFormat getInstance(Locale)

Returns the default number format for the specified locale. The default format is one of the styles provided by the other factory methods: getNumberInstance getIntegerInstance getCurrencyInstance or getPercentInstance. Exactly which one is locale dependant.
Class NumberFormat, Number parse(String)

ConvenienceParses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.

See the ParsePosition) method for more information on number parsing. @param source A String whose beginning should be parsed. @return A Number parsed from the string. @exception ParseException if the beginning of the specified string iscannot invalid. @seebe #formatparsed.

Class NumberFormat, Object parseObject(String, ParsePosition)

Parses text from a string to produce ana objectNumber. @param

source the stringThe method attempts to parse. @paramtext starting at parsePositionthe index given Input-Outputby parameterpos. OnIf parsing succeeds inputthen the positionindex of pos is updated to beginthe index after the last character used (parsing does not necessarily use all characters up to the end of the string) and the parsed number is returned. The updated pos can be used to indicate the starting point for the next call to this method. OnIf an error occurs outputthen the positionindex of pos is not changed the error index of pos is set to the firstindex of unparsethe character where the error occurred and null is returned.

See the ParsePosition) method for more information on number parsing. @param source A String part of which should be parsed. @param pos A ParsePosition object with index and error index information as described above. @return ObjectA Number parsed from the string. In case of error returns null. @seeexception java.textNullPointerException if pos is null.ParsePosition


Class ParseException

Signals that an error has been reached unexpectedly while parsing. @see java.lang.Exception @see java.text.Format @see java.text.FieldPosition @version 1.13 0114 12/1903/0001 @author Mark Davis

Class ParsePosition

ParsePosition is a simple class used by Format and its subclasses to keep track of the current position during parsing. The parseObject method in the various Format classes requires a ParsePosition object as an argument.

By design as you parse through a string with different formats you can use the same ParsePosition since the index parameter records the current position. @version 1.15 0116 12/1903/0001 @author Mark Davis @see java.text.Format


Class RuleBasedCollator

The RuleBasedCollator class is a concrete subclass of Collator that provides a simple data-driven table collator. With this class you can create a customized table-based Collator. RuleBasedCollator maps characters to sort keys.

RuleBasedCollator has the following restrictions for efficiency (other subclasses may be used for more complex languages) :

  1. If a French secondaryspecial collation orderingrule controlled by a <modifier> is specified it applies to the whole collator object.
  2. All non-mentioned Unicode characters are at the end of the collation order.

The collation table is composed of a list of collation rules where each rule is of one of three forms:

 <modifier > <relation > <text-argument > <reset > <text-argument > 
The following demonstratesdefinitions how to create your own collation rulesof the rule elements is as follows:

This sounds more complicated than it is in practice. For example the following are equivalent ways of expressing the same thing:

 a < b < c a < b &amp; b < c a < c &amp; a < b 
Notice that the order is important as the subsequent item goes immediately after the text-argument. The following are not equivalent:
 a < b &amp; a < c a < c &amp; a < b 
Either the text-argument must already be present in the sequence or some initial substring of the text-argument must be present. (e.g. "a < b &amp; ae < e" is valid since "a" is present in the sequence before "ae" is reset). In this latter case "ae" is not entered and treated as a single character; instead "e" is sorted as if it were expanded to two characters: "a" followed by an "e". This difference appears in natural languages: in traditional Spanish "ch" is treated as though it contracts to a single character (expressed as "c < ch < d") while in traditional German a-umlaut is treated as though it expanded to two characters (expressed as "a A < b B ... & amp;ae;ã & #92;u00e3&AE;Ã\u00c3"). [ã\u00e3 and Ã\u00c3 are of course the escape sequences for a-umlaut.]

Ignorable Characters

For ignorable characters the first rule must start with a relation (the examples we have used above are really fragments; "a < b" really should be "< a < b"). If however the first relation is not "<" then all the all text-arguments up to the first "<" are ignorable. For example " - < a < b" makes "-" an ignorable character as we saw earlier in the word "black-birds". In the samples for different languages you see that most accents are ignorable.

Normalization and Accents

RuleBasedCollator automatically processes its rule table to include both pre-composed and combining-character versions of accented characters. Even if the provided rule string contains only base characters and separate combining accent characters the pre-composed accented characters matching all canonical combinations of characters from the rule string will be entered in the table.

This allows you to use a RuleBasedCollator to compare accented strings even when the collator is set to NO_DECOMPOSITION. There are two caveats however. First if the strings to be collated contain combining sequences that may not be in canonical order you should set the collator to CANONICAL_DECOMPOSITION or FULL_DECOMPOSITION to enable sorting of combining sequences. Second if the strings contain characters with compatibility decompositions (such as full-width and half-width forms) you must use FULL_DECOMPOSITION since the rule tables only include canonical mappings. For more information see The Unicode Standard Version 2.0.)

Errors

The following are errors:

If you produce one of these errors a RuleBasedCollator throws a ParseException.

Examples

Simple: "< a < b < c < d"

Norwegian: "< a A< b B< c C< d D< e E< f F< g G< h H< i I< j J < k K< l L< m M< n N< o O< p P< q Q< r R< s S< t T < u U< v V< w W< x X< y Y< z Z å< \u00E5=a&#92;u030A Å\u00C5=A&#92;u030A ;aa AAæ< \u00E6 \u00C6< Æø\u00F8 Ø\u00D8"

Normally to create a rule-based Collator object you will use Collator's factory method getInstance. However to create a rule-based Collator object with specialized rules tailored to your needs you construct the RuleBasedCollator with the rules contained in a String object. For example:

 String Simple = "< a< b< c< d"; RuleBasedCollator mySimple = new RuleBasedCollator(Simple); 
Or:
 String Norwegian = "< a A< b B< c C< d D< e E< f F< g G< h H< i I< j J" + "< k K< l L< m M< n N< o O< p P< q Q< r R< s S< t T" + "< u U< v V< w W< x X< y Y< z Z" + "å< \u00E5=a&#92;u030A Å\u00C5=A&#92;u030A" + ";aa AAæ< \u00E6 \u00C6< Æø\u00F8 Ø\u00D8"; RuleBasedCollator myNorwegian = new RuleBasedCollator(Norwegian); 

Combining Collators is as simple as concatenating strings. Here's an example that combines two Collators from two different locales:

 // Create an en_US Collator object RuleBasedCollator en_USCollator = (RuleBasedCollator) Collator.getInstance(new Locale("en" "US" "")); // Create a da_DK Collator object RuleBasedCollator da_DKCollator = (RuleBasedCollator) Collator.getInstance(new Locale("da" "DK" "")); // Combine the two // First get the collation rules from en_USCollator String en_USRules = en_USCollator.getRules(); // Second get the collation rules from da_DKCollator String da_DKRules = da_DKCollator.getRules(); RuleBasedCollator newCollator = new RuleBasedCollator(en_USRules + da_DKRules); // newCollator has the combined rules 

Another more interesting example would be to make changes on an existing table to create a new Collator object. For example add "& amp;C< ch cH Ch CH" to the en_USCollator object to create your own:

 // Create a new Collator object with additional rules String addRules = "& amp;C< ch cH Ch CH"; RuleBasedCollator myCollator = new RuleBasedCollator(en_USCollator + addRules); // myCollator contains the new rules 

The following example demonstrates how to change the order of non-spacing accents

 // old rule String oldRules = "=&#92;u0301;&#92;u0300;&#92;u0302;&#92;u0308" // main accents + ";&#92;u0327;&#92;u0303;&#92;u0304;&#92;u0305" // main accents + ";&#92;u0306;&#92;u0307;&#92;u0309;&#92;u030A" // main accents + ";&#92;u030B;&#92;u030C;&#92;u030D;&#92;u030E" // main accents + ";&#92;u030F;&#92;u0310;&#92;u0311;&#92;u0312" // main accents + "< a A ; ae AE ; æ\u00e6 Æ\u00c6" + "< b B < c C < e E & C < d D"; // change the order of accent characters String addOn = "& &#92;u0300 ; &#92;u0308 ; &#92;u0302"; RuleBasedCollator myCollator = new RuleBasedCollator(oldRules + addOn); 

The last example shows how to put new primary ordering in before the default setting. For example in Japanese Collator you can either sort English characters before or after Japanese characters

 // get en_US Collator rules RuleBasedCollator en_USCollator = (RuleBasedCollator)Collator.getInstance(Locale.US); // add a few Japanese character to sort before English characters // suppose the last character before the first base letter 'a' in // the English collation rule is &#92;u2212 String jaString = "& \u2212 < \u3041 \u3042 < &#92;u3043 \u3044"; RuleBasedCollator myJapaneseCollator = new RuleBasedCollator(en_USCollator.getRules() + jaString); 
@see Collator @see CollationElementIterator @version 1.25 07/24/98 @author Helena Shih Laura Werner Richard Gillam

Class SimpleDateFormat

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text) parsing (text -> date) and normalization.

SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. However you are encouraged to create a date-time formatter with either getTimeInstance getDateInstance or getDateTimeInstance in DateFormat. Each of these class methods can return a date/time formatter initialized with a default format pattern. You may modify the format pattern using the applyPattern methods as desired. For more information on using these methods see DateFormat

Date Timeand FormatTime Syntax:Patterns

To specifyDate theand time formatformats are use aspecified by date and time pattern stringstrings. InWithin thisdate and time pattern all ASCIIstrings unquoted letters arefrom reserved'A' asto pattern'Z' lettersand from 'a' to which'z' are definedinterpreted as pattern letters representing the following:components Symbol Meaning Presentationof a date or time Examplestring. ------Text -------can ------------be -------quoted G era designatorusing single quotes (Text') AD yto yearavoid (Number)interpretation. 1996"''" M month inrepresents a single yearquote. (TextAll &other Number)characters July &are not 07interpreted; dthey're day in monthsimply copied into (Number)the 10 h hour inoutput string during formatting am/pmor (1~12)matched (Number)against 12 H hour inthe input string during dayparsing. (0~23)

(Number)The 0 m minute in hourfollowing pattern letters are defined (Number)all 30 s secondother characters from in'A' minuteto (Number)'Z' 55and Sfrom 'a' millisecondto (Number'z' are reserved): 978 E day

in(Number)in khourtimetextdetermineletters--useifdigits.YeartheYear2use
Letter weekDate (Text)or Tuesday DTime Component dayPresentation inExamples year
G 189Era Fdesignator dayText ofAD week
y monthYear (Number)Year 21996; (2nd96 Wed
M Month in year Month July); Jul; 07
w weekWeek in year (Number) 27
W weekWeek in month (Number) 2 a am/pm marker (Text) PM
D hourDay in day (1~24)year (Number) 24189 K
d inDay am/pmin (0~11)month (Number) 010 z
F zoneDay (Text)of Pacific Standard Timeweek in month 'Number escape2 for
E (Delimiter)Day ''in singleweek quoteText (Literal)Tuesday; 'Tue
a TheAm/pm countmarker ofText patternPM letters
H theHour format.in day (Text0-23): 4 orNumber more0 pattern
k fullHour formin <day 4-(1-use short24) orNumber abbreviated24 form
K oneHour exists.in am/pm (Number0-11): the minimumNumber number0 of
h ShorterHour numbersin aream/pm zero(1-padded12) toNumber this12 amount.
m isMinute handledin specially;hour thatNumber is30 if
s countSecond ofin 'y'minute isNumber 255 the
S willMillisecond beNumber truncated978 to
z digits.Time zone (TextGeneral &time Number):zone 3Pacific orStandard overTime; usePST; textGMT-08:00 otherwise
Z number.Time zone AnyRFC characters in822 time thezone pattern-0800 that are not in the ranges of
Pattern letters are usually repeated ['a'..'z']as andtheir ['A'..'Z']number will be treateddetermines the exact aspresentation: quoted SimpleDateFormat also supports localized date and time pattern strings. In these strings the first daypattern letters ofdescribed above may be replaced with other locale dependent pattern letters. SimpleDateFormat does not deal with the weeklocalization of text other than the firstpattern weekletters; that's up to the client of the yearclass.

Examples

The
whetherfollowing examples show how date and hourstime patterns are zero based orinterpreted in the notU.S. (0locale. The given date and time are vs2001-07-04 12:08:56 orlocal 24)time andin the U.S. Pacific Time time zone. There
Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE MMM d ''yy" Wed Jul 4 '01
"h:mm a" 12:08 PM
"hh 'o''clock' a zzzz" 12 o'clock PM Pacific Daylight Time
"K:mm a z" 0:08 PM PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE d MMM yyyy HH:mm:ss Z" Wed 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700

Synchronization

Date formats are not synchronized. It is onerecommended to common decimalcreate separate format toinstances handle allfor each thethread. numbers;If the digit count is handled programmatically according to themultiple threads access a format concurrently it must be patternsynchronized externally. @see java.util.CalendarJava Tutorial @see java.util.GregorianCalendarCalendar @see java.util.TimeZone @see DateFormat @see DateFormatSymbols @see DecimalFormat @version 1.52 0168 12/1903/0001 @author Mark Davis Chen-Lieh Huang Alan Liu

Class SimpleDateFormat, constructor SimpleDateFormat()

ConstructConstructs a SimpleDateFormat using the default pattern and date format symbols for the default locale. Note: Not allThis constructor localesmay not support SimpleDateFormat;all forlocales. For full generalitycoverage use the factory methods in the DateFormat class. @see java.text.DateFormat
Class SimpleDateFormat, constructor SimpleDateFormat(String)

ConstructConstructs a SimpleDateFormat using the given pattern inand the default date format symbols for the default locale. Note: Not allThis constructor localesmay not support SimpleDateFormat;all forlocales. For full generalitycoverage use the factory methods in the DateFormat class. @param pattern the pattern describing the date and time format @exception NullPointerException if the given pattern is null @exception IllegalArgumentException if the given pattern is invalid
Class SimpleDateFormat, constructor SimpleDateFormat(String, DateFormatSymbols)

ConstructConstructs a SimpleDateFormat using the given pattern and locale-specificdate symbol dataformat symbols. @param pattern the pattern describing the date and time format @param formatSymbols the date format symbols to be used for formatting @exception NullPointerException if the given pattern or formatSymbols is null @exception IllegalArgumentException if the given pattern is invalid
Class SimpleDateFormat, constructor SimpleDateFormat(String, Locale)

ConstructConstructs a SimpleDateFormat using the given pattern and the default date format symbols for the given locale. Note: Not all localesThis constructor may not support SimpleDateFormat;all forlocales. For full generalitycoverage use the factory methods in the DateFormat class. @param pattern the pattern describing the date and time format @param locale the locale whose date format symbols should be used @exception NullPointerException if the given pattern is null @exception IllegalArgumentException if the given pattern is invalid
Class SimpleDateFormat, void applyLocalizedPattern(String)

ApplyApplies the given localized pattern string to this date format. @param pattern a String to be mapped to the new date and time format pattern for this format @exception NullPointerException if the given pattern is null @exception IllegalArgumentException if the given pattern is invalid
Class SimpleDateFormat, void applyPattern(String)

ApplyApplies the given unlocalized pattern string to this date format. @param pattern the new date and time pattern for this date format @exception NullPointerException if the given pattern is null @exception IllegalArgumentException if the given pattern is invalid
Class SimpleDateFormat, Object clone()

OverridesCreates Cloneablea copy of this SimpleDateFormat. This also clones the format's date format symbols. @return a clone of this SimpleDateFormat
Class SimpleDateFormat, boolean equals(Object)

OverrideCompares equalsthe given object with this SimpleDateFormat for equality. @return true if the given object is equal to this SimpleDateFormat
Class SimpleDateFormat, StringBuffer format(Date, StringBuffer, FieldPosition)

Overrides DateFormat Formats a date or time which is the standard millis sincegiven JanuaryDate 1 1970into a 00:00:00date/time GMT.string Example:and usingappends the US locale: "yyyy.MM.dd G 'at'result HH:mm:ssto zzz"the -given 1996StringBuffer.07.10 AD at 15:08:56 PDT @param date the date-time value to be formatted into a date-time string. @param toAppendTo where the new date-time text is to be appended. @param pos the formatting position. On input: an alignment field if desired. On output: the offsets of the alignment field. @return the formatted date-time string. @seeexception java.text.DateFormatNullPointerException if the given date is null
Class SimpleDateFormat, Date get2DigitYearStart()

Returns the beginning date of the 100-year period 2-digit years are interpreted as being within. @return the start of the 100-year period into which two digit years are parsed @see #set2DigitYearStart
Class SimpleDateFormat, DateFormatSymbols getDateFormatSymbols()

Gets a copy of the date/ and time formattingformat data.symbols @returnof a copythis date offormat. @return the date-time and formatting data associated withtime format symbols of this date-time formatter.format @see #setDateFormatSymbols
Class SimpleDateFormat, int hashCode()

OverrideReturns hashCodethe hash code value for this SimpleDateFormat object. Generates@return the hash code value for thethis SimpleDateFormat object.
Class SimpleDateFormat, Date parse(String, ParsePosition)

OverridesParses DateFormattext from a string to produce a Date.

The method attempts to parse text starting at the index given by pos. If parsing succeeds then the index of pos is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string) and the parsed date is returned. The updated pos can be used to indicate the starting point for the next call to this method. If an error occurs then the index of pos is not changed the error index of pos is set to the index of the character where the error occurred and null is returned. @param source A String part of which should be parsed. @param pos A ParsePosition object with index and error index information as described above. @seereturn A javaDate parsed from the string. In case of error returns null. @exception NullPointerException if text or pos is null.DateFormat

Class SimpleDateFormat, void set2DigitYearStart(Date)

Sets the 100-year period 2-digit years will be interpreted as being in to begin on the date the user specifies. @param startDate During parsing two digit years will be placed in the range startDate to startDate + 100 years. @see #get2DigitYearStart
Class SimpleDateFormat, void setDateFormatSymbols(DateFormatSymbols)

AllowsSets you to set the date/ and time formattingformat symbols of datathis date format. @param newFormatDatanewFormatSymbols the givennew date- and time formattingformat data.symbols @exception NullPointerException if the given newFormatSymbols is null @see #getDateFormatSymbols
Class SimpleDateFormat, String toLocalizedPattern()

ReturnReturns a localized pattern string describing this date format. @return a localized pattern string describing this date format.
Class SimpleDateFormat, String toPattern()

ReturnReturns a pattern string describing this date format. @return a pattern string describing this date format.