Search This Blog

Monday, January 31, 2011

Question 22

What is the result of compiling and running the given code? (Choose 1 Answer)

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class NumberFormatClass {
  public static void main(String[] args){
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);
    try{
      Number number = numberFormat.parse("4,455.67");
      System.out.println(number.intValue());
    }catch(ParseException ex){
      ex.printStackTrace();
    }
  }
}
Options :

a. Compiler error :intValue method not defined in Number
b. Prints "Error"
c. Prints 4,455
d. Prints 4455
e. Prints 4455.67



Answer : C.

There are two important methods used in this question. The first one is numberFormat.parse() and number.intValue(). According to the method declaration parse method parses the given string and converts it into a number. The method definition is as follows :



public Number parse(String source)
throws ParseException


Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.

See the parse(String, ParsePosition) method for more information on number parsing.




Parameters:
source - A String whose beginning should be parsed.
Returns:
A Number parsed from the string.
Throws:
ParseException - if the beginning of the specified string cannot be parsed.



Similarly Number class has a method which can return a int value of a number. This process may involve truncation or rounding of the number.
Question 22SocialTwist Tell-a-Friend

No comments:

Post a Comment