In this article we are going to discuss converting String to int (primitive type) and Object type (wrapper) Integer. There are many ways to do it in Java.
How to convert String to int in Java
Here is a couple of ways to convert string to int, Java lets do it usingparseInt()
and valueOf()
methods.
Java string to int using Integer.parseInt(String)
parseInt
is a static method of the Integer class that returns an integer object representing the specified String parameter.Syntax:
public static int parseInt(String str) throws NumberFormatException
Or
public static int parseInt(String str, int radix) throws NumberFormatException
Where
str
is a String you need to convert andradix
is a base of the parsed numberConverting String to Integer, Java example using parseInt()
public class Demo2 { // convert string to int java public static void main(String args[]) { String str = "111"; int num1 = Integer.parseInt(str); System.out.println("parseInt of the String = " + num1); int num2 = Integer.parseInt(str, 2);//binary number System.out.println("parseInt of the String with radix parameter = " + num2); } }
The output is:
parseInt of the String = 111 parseInt of the String with radix parameter = 7
Here we’ve got 111 in the first variant and 7 for the second. 7 is a decimal form of binary 111.
Convert using Integer.valueOf(String)
Integer.valueOf(String s) is a Java method of Integer class. It returns an Integer decimal interpretation of a String object so it is used to convert String to Integer.
Syntax:
public static Integer valueOf(String str) Example Java String to Integer using valueOf method: public class Demo2 { // java convert string to int using valueOf() String myString = "578"; int parNum = Integer.valueOf(myString); System.out.println("Integer from String using valueOf() = " + parNum); } }
Output:
Integer from String using valueOf() = 578
GO TO FULL VERSION