How to I convert a String to Integer?
Let’s say you have a string – strTest – that contains a numeric value.
String strTest = “100”;
Try to perform some arithmetic operation like divide by 4 – This immediately shows you a compilation error.
Now make use of ParseInt method as follows:
int <IntVariableName> = Integer.parseInt(<StringVariableName>);
Pass the string variable as the argument.
This will convert the String to Integer and store it into the specified integer variable
Check the below code snippet-
String strTest = "100";
//This statement results in a compilation error as you
//cannot do arithmetic operation on Strings
//System.out.println("Using String:" + (strTest/4));
//Convert the String to Integer
int iTest = Integer.parseInt(strTest);
System.out.println("Actual String:"+ strTest);
System.out.println("Converted to Int:" + iTest);
//This will now execute some arithmetic operation
System.out.println("Arithmetic Operation on Int:" + (iTest/4));
|
Output of the above code snippet- Actual String:100 Converted to Int:100 Arithmetic Operation on Int:25 |
![]() |


