InterviewSolution
Saved Bookmarks
| 1. |
NumberFormatException in Java |
|
Answer» A NumberFormatException in Java is an exception of the java.lang package which is thrown when we try to convert a String into a numeric DATA TYPE such as int, float, double, long and short. This happens when the String does not have an appropriate format. Take for example, we try to PARSE a String which is not of numeric type into an integer: public class Example { public static void main(String[] args) { String str = "Number"; int intVal = Integer.parseInt(str); System.out.println(intVal); } }The above CODE will throw a NumberFormatException: $javac Example.java $java -Xmx128M -Xms16M Example Exception in thread "main" java.lang.NumberFormatException: For input string: "Number" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at Example.main(Example.java:8)But if the String is of numeric type, it will successfully parse it to an integer public class Example { public static void main(String[] args) { String str = "12"; int intVal = Integer.parseInt(str); System.out.println(intVal); } }The OUTPUT is the following: $javac Example.java $java -Xmx128M -Xms16M Example 12 |
|