Java

4 ways to Convert String to int in Java


In Java, you can convert String to int has many way are listed below

1. Using Integer.parseInt()

for example you have one string is called “12” now we convert it into primitive int.

String numberStr = "12";
int result = Integer.parseInt(numberStr);
System.out.println("After Convert String to int using Integer.parseInt() :: "+result);

Output

After Convert String to int :: 12

2. Using Integer.valueOf()

Another way to convert String to int is  Integer.valueOf()  like this

String numberStr = "12";
int result = Integer.valueOf(numberStr);
System.out.println("After Convert String to int using Integer.valueOf() :: "+result);

Output

After Convert String to int :: 12
Note :
Here slight difference between these methods:

  1.  Integer.valueOf(String) are returns a new or cached instance of java.lang.Integer
  2.  Integer.parseInt(String) are returns primitive int.

3. Using NumberUtils.toInt()

Another alternative solution is to use third party libraries like Apache Commons. This library gives one utility class is called  NumberUtils . When you pass an invalid value, then it will return 0.

String numberStr = "12";
int result = NumberUtils.toInt(numberStr);
System.out.println("After Convert String to int using NumberUtils.toInt() :: "+result);

Output

After Convert String to int :: 12

4. Using Integer.decode()

Using  Integer.decode() work same like  Integer.valueOf() , but slight difference is Integer.decode() method you can pass octal and hexadecimal strings in addition to decimal strings where you can’t do this with Integer.valueOf() because it with single parameter version.

Unboxing

int result = Integer.decode(numberStr);

intValue

Integer.decode("12").intValue();

4. NumberFormatException

When you give an invalid integer, then it will throw NumberFormatException .

String numberStr = "12Divyesh";
int result = Integer.parseInt(numberStr);
System.out.println("After Convert String to int using Integer.parseInt() :: "+result);

Output

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

References

  1. Integer.parseInt() from JavaDoc
  2. NumberUtils from Apache Commons
  3. Integer.decode() from JavaDoc
Java
Java Enum example with advantages and disadvantages
Java
Java Copy File with 5 different ways
There are currently no comments.