String mystr = "100";
int intVal = Integer.parseInt(mystr);
System.out.println(intVal);
In the above code example, we have defined a String variable 'mystr' and want to convert it to integer type values using Java. We are using Integer.parseInt() function to do that.
Integer.parseInt(MyString)
If the string value is not valid then the program will throw an error. You can handle it using the below code.
try {
String mystr = "abc";
int val = Integer.parseInt(mystr);
}
catch (NumberFormatException e) {
System.out.println("Not a valid value");
}
Output
Not a valid value
We can also use the Java method Integer.valueOf() to convert the given String value to Integer type value. The function takes the string as a parameter and returns the numeric value. Below is the code example for that.
String mystr = "10";
int val = Integer.valueOf(mystr);
System.out.println(val);
Output
10
0 Comments