How to Convert String to Integer in Java

Filed Under: Java
String To Integer

Strings and integers are two different data types in Java. Strings in Java stores multiple characters together. Integer stores….well, integers.

Converting String to Integer in Java

Sometimes strings can contain numbers as characters. This is often the case when data is retrieved in tables from APIs. Converting Sring into int is easy for computation.

What happens if you perform arithmetic operations on numbers in the form of strings? Let’s try running the code below.

package com.journaldev.java;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
    public static void main(String[] args) {
      String a = "100";
      String b = "50";
      String c = a+b;
      System.out.println(c); 
    }
}
Strings Addition

Addition in strings is concatenation. Let’s see a few methods to convert strings into integers.

1. Using Integer.Valueof()

Integer.valueOf() converts a String into an Integer object. Let’s see a code that explains it.

package com.journaldev.java;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {

    public static void main(String[] args) {
	// write your code here
      String a = "100";
      String b= "50";
      int A = Integer.valueOf(a);
      int B = Integer.valueOf(b);

      int c = A+B;
      System.out.println(c);
    }
}

Integer.Valueof()
Intgeger Valueof

2. Using Integer.parseInt()

Integer.parseInt() returns primitive int type as output.

package com.journaldev.java;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {

    public static void main(String[] args) {
	// write your code here
      String a = "100";
      String b= "50";
      int A = Integer.parseInt(a);
      int B = Integer.parseInt(b);

      int c = A+B;
      System.out.println(c);

    }

}
integer.parseInt()

3. Using good old for loop

If you are a programmer then you are probably not satisfied util and unless you design your own function from scratch. We will do just that! We will use a for loop to convert a string into an integer.

For this, you need to know a little about ASCII codes. All characters have a code to identify them, this code is the ASCII code.

If you subtract character ‘0’ from any character digit then you get the absolute value of that character as an integer.

We will use this fact and iterate over the string from the end character by character. While iterating we will make sure that we add int value of each character to a common variable. Position of the character in the string is important to note as going left the value of each digit increases 10 times. Therefore we will need a variable to factor in the multiplying factor of each position.

package com.journaldev.java;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {

    public static void main(String[] args) {
	// write your code here
      String a = "100";
      String b= "50";
      int A=string_to_int(a);
      int B=string_to_int(b);
      int c= A+B;
      System.out.println(c);

    }
    public static int string_to_int (String s){
        int num=0;
        int pos =1;
        for(int i=s.length()-1;i>=0;i--){
            num+= (s.charAt(i)-'0')*pos;
            pos*=10;

        }
        return num;

    }

}
For Loop String To Integer

This code, however, doesn’t take care of negative integers. To modify the program to include negative integers use a flag to check the first position of the string. After that exclude the position if it contains a ‘-‘. The following code demonstrates this :

package com.journaldev.java;
import java.util.ArrayList;
import java.util.Arrays;
public class Main {

    public static void main(String[] args) {
	// write your code here
      String a = "100";
      String b= "-50";
      int A=string_to_int(a);
      int B=string_to_int(b);
      int c= A+B;
      System.out.println(c);

    }
    public static int string_to_int (String s){
        int num=0;
        int pos =1;
        boolean flag = false;
        if(s.charAt(0)=='-'){
            s=s.substring(1);
            flag=true;
        }

        for(int i=s.length()-1;i>=0;i--){
            num+= (s.charAt(i)-'0')*pos;
            pos*=10;

        }
        if(flag){
            num=-1*num;
        }
        return num;
    }
}
Negative Numbers In For Loop

As much fun it was to write our own function, please don’t use it in your production servers. It’s good for practice only, for real programming you should stick to the Integer class methods.

Conclusion

Converting String to Integer is a trivial task. It often comes in handy in case data is imported from an external source and it contains numbers as strings.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages