EN
Java - convert string to integer
0
points
In this article, we would like to show you how to convert string to integer in Java.
1. Using Integer parseInt()
In this example, we use Integer parseInt()
method to convert text
string to the integer.
public class Example {
public static void main(String[] args) {
String text = "10";
try {
int number = Integer.parseInt(text);
System.out.println(number); // 10
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
Note:
If the string doesn't contain a valid integer it will throw a NumberFormatException.
2. Using Integer valueOf()
In this example, we use Integer valueOf()
method to convert text
string to the integer.
public class Example {
public static void main(String[] args) {
String text = "10";
try {
Integer number = Integer.valueOf(text);
System.out.println(number); // 10
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
Note:
If the string doesn't contain a valid integer it will throw a NumberFormatException.