MessageFormat parse() method in Java with Example : Set – 2
Last Updated :
06 Oct, 2021
The parse() method of java.text.MessageFormat class is used to parse the string object starting from the passed parse position in the parse() method.
Syntax:
public Object[] parse(String source,
ParsePosition pos)
Parameter: This method takes the following arguments as parameter.
- source :- string over which parsing is going to perform.
- pos :- it is the starting index of parsing.
Return Value: This method returns array of object as an output.
Exception: This method throws NullPointerException if the parse position is null.
Below are the examples to illustrate the parse() 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, #}, {2, number, #.#}, {1, number, #.##}" );
;
String str = "10.456, 20.325, 30.444" ;
ParsePosition pos = new ParsePosition( 3 );
Object[] hash = mf.parse(str, pos);
System.out.println( "Parsed value are :" );
for ( int i = 0 ; i < hash.length; i++)
System.out.println(hash[i]);
}
catch (NullPointerException e) {
System.out.println( "\nParse position is Null" );
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Parsed value are :
456
30.444
20.325
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, #}, {2, number, #.#}, {1, number, #.##}" );
String str = "10.456, 20.325, 30.444" ;
Object[] hash = mf.parse(str, null );
System.out.println( "Parsed value are :" );
for ( int i = 0 ; i < hash.length; i++)
System.out.println(hash[i]);
}
catch (NullPointerException e) {
System.out.println( "Parse position is Null" );
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Parse position is Null
Exception thrown : java.lang.NullPointerException
Reference:https://docs.oracle.com/javase/9/docs/api/java/text/MessageFormat.html#parse-java.lang.String-java.text.ParsePosition-
Share your thoughts in the comments
Please Login to comment...