ChoiceFormat applyPattern() method in Java with ExamplesThe java.text.ChoiceFormat is a class containing an applyPattern() as a function. Using the ChoiceFormat class, the current limit and format can be overridden to set the new pattern text for the ChoiceFormat. The combination of the ChoiceFormat format and limit will be this new pattern. Syntax: Parameter: The new text pattern for ChoiceFormat is called newPattern, and it is the parameter for the above method. Return Value: No value is returned by implementing this method Exception: In the case that the given newPattern is null, this function raises a NullPointerException. Example 1: The Java program that is included demonstrates the way to convert numerical limits to particular string values using the ChoiceFormat class. First of all, it generates a ChoiceFormat object with six number limits, one for each month from January to June. The program then prints the ChoiceFormat object's current pattern. After that, it maps numbers from 7 to 12 to the months of July through December by applying a new pattern using the applyPattern() function. Lastly, the updated pattern with the modified mappings is printed. Implementation:FileName: ChoiceFormatApplyPatternExample1.java Output: The current ChoiceFormat pattern : 1.0#JANUARY|2.0#FEBRUARY|3.0#MARCH|4.0#APRIL|5.0#MAY|6.0#JUNE The new ChoiceFormat pattern : 7.0#JULY|8.0#AUGUST |9.0#SEPTEMBER |10.0#OCTOBER |11.0#NOVEMBER |12.0#DECEMBER Example 2: The Java program given shows how to handle a NullPointerException when utilizing the ChoiceFormat class's applyPattern() function. It first creates a ChoiceFormat object and prints the current pattern, setting boundaries from 1 to 6, which represent the months of January through June. It then throws a NullPointerException when attempting to apply a null pattern. When the application detects this exception, it displays the relevant error message and a description of the issue. Implementation:FileName: ChoiceFormatApplyPatternExample2.java Output: The current ChoiceFormat pattern : 1.0#JANUARY|2.0#FEBRUARY|3.0#MARCH|4.0#APRIL|5.0#MAY|6.0#JUNE The String is Null The Exception thrown is : java.lang.NullPointerException: Cannot invoke "String.length()" because "newPattern" is null |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India