HomeLanguagesJavaNumberFormat parseObject() method in Java with Examples

NumberFormat parseObject() method in Java with Examples

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)));
    }
}


Output:

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);
        }
    }
}


Output:

Exception: java.lang.NullPointerException

Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#parseObject(java.lang.String, java.text.ParsePosition)

RELATED ARTICLES

4 COMMENTS

Most Popular

Dominic
32707 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7081 POSTS0 COMMENTS
Nicole Veronica
12218 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12306 POSTS0 COMMENTS
Shaida Kate Naidoo
7200 POSTS0 COMMENTS
Ted Musemwa
7460 POSTS0 COMMENTS
Thapelo Manthata
7180 POSTS0 COMMENTS
Umr Jansen
7166 POSTS0 COMMENTS