Number Format Exceptions in java
NumberFormatException is a subclass of the Runtime Exception class. A Number Format Exception occurs in the java code when a programmer tries to convert a String into a number. The Number might be int,float or any java numeric values.
Understand Number Format Exception
The conversions are done by the functions Integer.parseInt and Integer.parseDouble. Consider the function call Integer.parseInt(str) where str is a variable of type String. Suppose the value of str is "60", then the function call and convert the string into the int 60. However, if you give the value of str is "akilraj1255", the function call will fail to compile because "akilraj1255" is not a legal string representation of an int value. In such case, NumberFormatException will occurs
public class ConvertStringToNumber
{
public static void main(String[] args)
{
try
{
String s = "akilraj1255";
int i = Integer.parseInt(s);
// this line of code will never be reached//
System.out.println("int value = " + i);
}
catch (NumberFormatException nfe)
{
nfe.printStackTrace();
}
}
}
Output on Command Prompt
C:\Documents and Settings\Administrator>cd\
C:\>cd akilraj1255\
C:\akilraj1255>javac ConvertStringToNumber.java
C:\akilraj1255>java ConvertStringToNumber
java.lang.NumberFormatException: For input string: "akilraj1255"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at ConvertStringToNumber.main(ConvertStringToNumber.java:9)
0 comments:
Post a Comment