ChoiceFormat format() method in Java with Examples

The java.text.ChoiceFormat is a class containing a format() as a function. To obtain the appended string builder of the format value of a specific limit value given as a parameter and text passed as a parameter in this method, utilize the ChoiceFormat class.

Syntax:

Parameters:

number: which is the particular choiceformat limit object for which it should be appended and must be stored

toAppendTo: which is the updated text that needs to be attached along with the format

status: which determines whether a special status needs to be returned.

Return Value: The StringBuffer object is the result of this method's inserted text and format value.

Exception: If the value of toAppendto is null, this function raises a NullPointerException.

Example 1:

The given Java program demonstrates how to format integers into corresponding string representations using the ChoiceFormat class in accordance with predefined patterns. A ChoiceFormat object is initialized with a pattern that associates the digits 0 through 5 with the months ranging from January to June. The text "Month" is used to initialize a StringBuffer object. The relevant month for the number 6 is then appended to the StringBuffer by the program using the format() function of the ChoiceFormat object. The format() function appends the default representation of the value 6 as it is not present in the defined pattern. The string "Month6" that is generated is printed.

Implementation:

FileName: ChoiceFormatExample1.java

Output:

The Formatted text with appended value is given by: MonthJUNE

Example 2:

The following Java program shows how to handle a NullPointerException when working with null StringBuffer objects and shows how to format integers into equivalent string representations using the ChoiceFormat class. A ChoiceFormat object is initialized by the program with a pattern that maps integers 0 through 5 to January through June. After converting the StringBuffer object to null, it tries to format the number 6 by calling the ChoiceFormat object's format() method. This operation causes a NullPointerException, which is handled by the catch block since the StringBuffer is null. The program shows an illustration of the exception thrown and puts out a message stating that the string is null.

Implementation:

FileName: ChoiceFormatExample2.java

Output:

The String is Null
The Exception thrown is : java.lang.NullPointerException: Cannot invoke "java.lang.StringBuffer.append(String)" because "toAppendTo" is null