Integer.parseInt(“text”)
What will happen if we execute the program int a = Integer.parseInt(“text”) ?
class HelloWorld {
public static void main(String[] args) {
int a = Integer.parseInt(“text”);
System.out.print(a);
}
}
When this program is executed this will throw the following Exception
Exception in thread "main" java.lang.NumberFormatException: For input string: "text"at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)at java.base/java.lang.Integer.parseInt(Integer.java:652)at java.base/java.lang.Integer.parseInt(Integer.java:770)
at HelloWorld.main(HelloWorld.java:7)
This is because parseInt() is used to get the primitive data type of the given string.
It need to accepts the Integer in the form of String. But here we have given "text" as an Input in place of Integer. So it has thrown Number for Exception.
It can be corrected by giving any Integer as an Input.
class HelloWorld {
public static void main(String[] args) {
String s="200";
int i=Integer.parseInt(s);
System.out.println(i+100);
}
}
This shows the Output as
300
Comments
Post a Comment