The parseObject() method is a built-in method of the java.text.NumberFormat which parses a text from a string to produce a Number. The function attempts to parse text starting at a given index. When parsing occurs, the given index is set to the last character used, in case parsing fails, the given index is not changed and the error index is set to the index where the error occurs.
Syntax:
public final Object parseObject(String source, ParsePosition pos)
Parameters: The function accepts two parameters which are described below:
- source: specifies the string to be parsed
- pos: specifoes the ParsePosition object with index and error index information as described
Return Value: The function returns a boolean value, it returns true if numbers can be parsed as integers, else it returns false.
Exceptions: The function throws a NullPointerException if source or pos is initialized as null.
Below is the implementation of the above function:
Program 1:
// Java program to implement // the above function import java.text.NumberFormat; import java.util.Locale; import java.text.ParsePosition; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat.getNumberInstance(); // Prints the parsed number or NULL System.out.println(nF .parseObject( "456" , new ParsePosition( 0 ))); } } |
456
Program 2:
// Java program to implement // the above function import java.text.NumberFormat; import java.util.Locale; import java.text.ParsePosition; public class Main { public static void main(String[] args) throws Exception { try { // Get the instance NumberFormat nF = NumberFormat.getNumberInstance(); // Prints the parsed number or NULL System.out.println( nF .parseObject( null , new ParsePosition( 0 ))); } catch (Exception e) { System.out.println( "Exception: " + e); } } } |
Exception: java.lang.NullPointerException