• Home
  • Testing
  • SAP
  • Web
  • Must Learn!
  • Big Data
  • Live Projects
  • Blog

There are many ways you can do this, but the easiest way is simply use the method Integer.parseInt(). Example: How to convert a Java 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.

Example : Integer.parseInt()

Now make use of ParseInt method as follows:
int <IntVariableName> = Integer.parseInt(<StringVariableName>);

Pass the string variable as the argument.

This will convert the java String to java Integer and store it into the specified integer variable

Check the below code snippaet-

Java Example: String to Integer

class StrConvert{
  public static void main(String []args){
    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 show some arithmetic operation
    System.out.println("Arithmetic Operation on Int:" + (iTest/4));

How to convert a Java String to Integer?