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.

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.

2. Using Integer.parseInt()

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

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.

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 :

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.


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.

By admin

Leave a Reply

%d bloggers like this: