Convert String to int in Java
The following list shows various ways to convert String to int (Integer) in Java. If your string contains only numbers and if you want to return the number it represents you can make use of the following ways.
Integer.parseInt()
String str="4857"; Integer i=Integer.parseInt(str); // or int i = Integer.parseInt(str)
Integer.valueOf()
String str="4857"; Integer i=Integer.valueOf(str); // or int i = Integer.valueOf(str)
Number.intValue()
The abstract class Number
is the superclass of classes BigDecimal
, BigInteger
, Byte
, Double
, Float
, Integer
, Long
, and Short
. We can take advantage of intValue() method in Number class to convert String to int.
String str="4857"; int i = NumberFormat.getInstance().parse("str").intValue()