String to Integer Conversion

If you want to utilize a number in calculations which you have received as string, it might create some unexpected issues.

For example, below program simply appends two numbers instead of performing addition.

String strNum1 = "10";
String strNum2 = "20";
System.out.println(strNum1 + strNum2);
// Output
1020
Integer.parseInt(String)

Package java.lang provides a wrapper class called as Integer which has parseInt method that can convert string to signed decimal integer.

String strNum1 = "10";
String strNum2 = "20";
int num1 = Integer.parseInt(strNum1);
int num2 = Integer.parseInt(strNum2);
System.out.println(num1 + num2);
// Output
30
Integer.valueOf(String)

If you need a wrapper object of Integer after conversion, you can use valueOf method.

String strNum = "10";
Integer num = Integer.valueOf(strNum1);
System.out.println(num.compareTo(20));
// Output
-1
See also  Can Abstract Class have a Constructor in Java?