MessageFormat formatToCharacterIterator() method in Java with Example
Last Updated :
19 Apr, 2023
The formatToCharacterIterator() method of java.text.MessageFormat class is used to format an array of object and insert them into the pattern of message format object.
Syntax:
public AttributedCharacterIterator formatToCharacterIterator(Object arguments)
Parameter: This method takes array of object as an parameter over which formatting is going to take place.
Return Value: This method returns attribute character iterator which will describe the formatted value .
Exception: This method throws NullPointerException if argument is null.
Below are the examples to illustrate the formatToCharacterIterator() method:
Example 1:
Java
import java.text.*;
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] argv)
{
try {
MessageFormat mf
= new MessageFormat("{ 0 , number, #}, { 0 , number, #.##}, { 0 , number}");
Object[] objs = { new Double( 4.234567 ) };
CharacterIterator str = mf.formatToCharacterIterator(objs);
System.out.print("formatted array : ");
System.out.print(str.first());
for ( int i = 0 ; i <= str.getEndIndex() - 2 ; i++)
System.out.print(str.next());
}
catch (NullPointerException e) {
System.out.println("pattern is null ");
System.out.println("Exception thrown : " + e);
}
}
}
|
Output:
formatted array : 4, 4.23, 4.235
Example 2:
Java
import java.text.*;
import java.util.*;
import java.io.*;
public class GFG {
public static void main(String[] argv)
{
try {
MessageFormat mf
= new MessageFormat("{ 0 , number, #}, { 0 , number, #.##}, { 0 , number}");
Object[] objs = { new Double( 4.234567 ) };
CharacterIterator str = mf.formatToCharacterIterator( null );
System.out.print("formatted array : ");
System.out.print(str.first());
for ( int i = 0 ; i <= str.getEndIndex() - 2 ; i++)
System.out.print(str.next());
}
catch (NullPointerException e) {
System.out.println("argument is null ");
System.out.println("Exception thrown : " + e);
}
}
}
|
Output:
argument is null
Exception thrown : java.lang.NullPointerException: formatToCharacterIterator must be passed non-null object
Reference: https://docs.oracle.com/javase/9/docs/api/java/text/MessageFormat.html#formatToCharacterIterator-java.lang.Object-
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...