java 8 convert string to int

If you have a string that contains only numbers and you want to extract the number it represents then you have several ways to convert a String to an int in Java 8?

You can find more info about java 8 and 9 here:

Class Integer

You can also see:
java 8 convert string to double

java convert string to int by valueOf

First way is to use instance method: valueOf. It returns java.lang.Integer,the object representation of the integer.

Integer resultV = Integer.valueOf(numberV);
String numberV = "100";
Integer resultV = Integer.valueOf(numberV);
System.out.println(resultV);

result

100

Note: that difference between valueOf and parseInt can be represented as:

Integer.valueOf(s) == new Integer(Integer.parseInt(s))

also throws: NumberFormatException - check explanation below.

java convert string to int by parseInt

Next one is to use classic static method which returns primitive type int:

Integer.parseInt(number);
String number = "100";
int result = Integer.parseInt(number);
System.out.println(result);

result

100

The only issue is exception:

NumberFormatException
which is thrown if the string does not contain a parsable integer.

int result = Integer.parseInt("AAAA");

result:

Exception in thread "main" java.lang.NumberFormatException: For input string: "AAA"
	at java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at java.lang.Integer.valueOf(Unknown Source)

java convert mix string characters and digits by regex

Regex can be used to clean mixed strings numbers and letters.

.replaceAll("[\\D]", ""));

example

String strNum="myNumberIs100OK";
int myint=Integer.parseInt(strNum.replaceAll("[\\D]", ""));
System.out.println(myint);

result

100

Related Article