Wednesday, August 4, 2021

How to Convert String to Integer to String in Java with Example

Converting String to integer and Integer to String is one of the basic tasks of Java and most people learned about it when they learn Java programming. Even though String to integer and Integer to String conversion is basic stuff at the same time it's most useful also because of its frequent need given that String and Integer are the two most widely used types in all sorts of programs and you often get data between any of these formats. One of the common tasks of programming is converting one data type to another like Converting Enum to String or Converting Double to String, Which is similar to converting String to Integer. 

Some programmers asked a question that why not Autoboxing can be used to convert String to int primitive or Integer Object? 

Remember autoboxing only converts primitive to Object it doesn't convert one data type to others. A few days back I had to convert a binary String into integer number and then I thought about this post to document all the way I know to convert Integer to String Object and String to Integer object. 




String to Integer Conversion in Java - Examples

Here is my way of converting String to Integer in Java with an example :


1. By using Intger.parseInt() method


This is my preferred way of converting an String to int in Java, Extremely easy and most flexible way of converting String to Integer. Let see an example of String to int conversion:

 //using Integer.parseInt
 int i = Integer.parseInt("123");
 System.out.println("i: " + i);

Integer.parseInt() method will throw NumberFormatException if String provided is not a proper number. Same technique can be used to convert other data type like float and Double to String in Java. Java API provides static methods like Float.parseFloat() and Double.parseDouble() to perform data type conversion.



2. Integer.valueOf() method

There is another way of converting String into Integer which was hidden to me for long time mostly because I was satisfied with Integer.parseInt() method. This is an example of Factory method design pattern in Java and known as Integer.valueOf(), this is also a static method like main and can be used as utility for string to int conversion. Let’s see an example of using Integer.valueOf() to convert String into int in java.

//How to convert numeric string = "000000081" into Integer value = 81
int i = Integer.parseInt("000000081");
System.out.println("i: " + i);

It will ignore the leading zeros and convert the string into an int. This method also throws NumberFormatException if the string provided does not represent the actual number. 

Another interesting point about static valueOf() method is that it is used to create an instance of wrapper class during Autoboxing in Java and can cause subtle issues while comparing primitive to Object e.g. int to Integer using equality operator (==),  because of caches Integer instance in the range -128 to 127.




How to convert Integer to String in Java? Example

String to integer conversion, Int to string example In the previous example of this String to int  conversion  we have seen changing String value into int primitive type and this part of Java tutorial we will see opposite i.e. conversion of Integer Object to String. In my opinion this is simpler than previous one. 

You can simply concatenate any number with empty String and it will create a new String. Under the carpet + operator uses either StringBuffer or StringBuilder to concatenate String in Java. anyway, there are a couple of more ways to convert int into String and we will see those here with examples.

1. Int to String in Java using "+" operator

Anything could not be more easy and simple than this. You don't have to do anything special just use "+" concatenation operator with String to convert int variable into String object as shown in the following example:

String price = "" + 123;

Simplicity aside, Using String concatenation for converting int to String is also one of the most poor way of doing it. I know it's temptation because, it's also the most easiest way to do and that's the main reason of it polluting code. When you write code like "" + 10 to convert numeric 10 to String, your code is translated into following :


new StringBuilder().append( "" ).append( 10 ).toString();

StringBuilder(String) constructor allocates a buffer containing 16 characters. So, appending up to 16 characters to that StringBuilder will not require buffer reallocation, but appending more than 16 characters will expand StringBuider buffer. Though it's not going to happen because Integer.MAX_VALUE is 2147483647, which is less than 16 characters. 

At the end, StringBuilder.toString() will create a new String object with a copy of the StringBuilder buffer. This means for converting a single integer value to String you will need to allocate: one StringBuilder, one char array char[16], one String and one char[] of appropriate size to fit your input value. 

If you use String.vauleOf() will not only benefit from a cached set of values but also you will at least avoid creating a StringBuilder. To learn more about these two, see my post about StringBuffer vs StringBuilder vs String 




One more example of converting int to String

There are many ways to convert an int variable into String,  In case if you don't like above example of string conversion than here is one more example of doing the same thing. 

In this example of converting Integer to String we have used String.valueOf() method which is another static utility method to convert any integer value to String. 

In-fact String.valueOf() method is overloaded to accept almost all primitive type so you can use it convert char, double, float or any other data type into String. Static binding is used to call the corresponding method in Java. Here is an example of int to String using String.valueOf()

String price = String.valueOf(123);

After execution of the above line, Integer 123 will be converted into String “123”.


Int to a string using String. format()

This is a new way of converting an int primitive to String object and introduced in JDK 1.5 along-with several other important features like Enum, Generics and Variable argument methods. String.format() is even more powerful and can be used in a variety of ways to format String in Java

This is just another use case of String.format() method for displaying int as string. Here is an example of converting int to String using String.format method:

String price = String.format ("%d", 123);

Indeed conversion of String to Integer object or int primitive to String is pretty basic stuff but I thought let's document for quick reference of anyone who might forget it or just wanted to refresh it. By the way if you know any other way of string-int-string conversion than please let us know and I will include it here.


33 comments :

Jirka Pinkas said...

Hi, you have a typo in second example. Instead of
int i = Integer.parseInt("000000081");
you surely meant:
int i = Integer.valueOf("000000081");

Also there's another way to convert String to Integer using a constructor:
int i = new Integer("81");
But I guess that this is dumb, because there's autoboxing involved, so I always use static method Integer.parseInt()

Anand Vijayakumar said...

Nice one Javin.

To add on - It is always a good idea to surround the parseInt method with a try catch block to ensure that the parsing process doesnt break the code esp in cases where the value being converted is a user input (@ run time)

like:

try {
int i = Integer.parseInt(x);
} catch(Exception e){
return 0;
}

This way, even if x is an invalid number, i will just be 0 and carry on to the next line of code instead of crashing....

The String class is loaded with features and can be found by clicking here

Anand.

Anonymous said...

perfect examples of converting String to int and than int to String , easy to read, understand and use. Thanks for your java tips and tutorial.

Anonymous said...

even a Integer.toString()method also convert a int value into string.

Anonymous said...

Changing String to Integer is easy as compared to Changing Integer to String. But Java should have generic utility method for such kind though nothing wrong with toString().

Anonymous said...

Does anyone know a way of doing this that does not remove zeros? I need to take 100193 and turn it into 00193 carry 1. All methods I've seen give a 193 for that. Also, it needs to be an integer so I can copy it to a array like
14205 12480 52954 00193
to make a 20-digit number. Please help!

Anonymous said...

isn't it better to write a Utility function to convert String to int or Integer and just pass it String and it would return an int or Integer based upon requirement ?

Rashimi said...

There is another advantage of converting String to Integer using Integer.valueOf() because it can cache frequently used Integer values for better performance. since Integer is immutable and you can safely cache converted Integer and avoid creating duplicate Integer object. That's the reason Integer.valueOf() is the best way to convert Java String to Integer.

Sujata said...

What is difference on converting String to int and String to Integer ? to me both looks same because auto-boxing will convert int to Integer automatically. By the way you should use String.valueOf() to convert String to Int or Integer because its a static factory method and can cache frequently used Integers. since Integers are immutable object caching and reusing them will prevent from creating unnecessary object. String to int conversion examples are simple and good but Integer to String conversion are great :)

Anonymous said...

@Sujata, Converting to int or Integer is different as former is primitive type while later is an Object. Though with auto-boxing in Java 5 you can convert int to Integer automatically but still you need to convert String to int or String to Integer before auto boxing can take place.

Anonymous said...

Always use Integer.valueOf() to convert String to Integer object, that's it.

Riya said...

Integer.parseInt() is best way to convert numeric String to integer. It takes care of negative integers as well.

Anonymous said...

Does this method works for negative integer value as well? How about handling Integer overflow ?

suresh said...

What is the best way to convert String to int primitive variable in Java? Best in terms of ease of use, performance and without any gotcha.

Anonymous said...

From JDK 1.5 allows you to convert like Integer i = new Integer("000000081");

Anonymous said...

Another way to convert from String to int is "int i = new Integer(String).intValue();"

Anonymous said...

is there are safe way to convert various kinds of numeric String values to integer or int in Java? currently I am loading data from a file and one of the field which supposed to be number contains different kinds of String values which is not int e.g. empty string "", number in exponential format e.g. 3.9535733E6, -7723 and simple 2.38494. When I use Integer.valueOf() to convert, I get NumberFormatException as shown below
Exception in thread "main" java.lang.NumberFormatException: For input string: "2.38494"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)

Anonymous said...

how to convert int to String in Java? you read it write, I am interested in primitive int not Integer object.

Unknown said...

Check whether String contains only digit and parse the value .

public class ConvertStringToInt {
public static void main(String[] args) {

String str = "6789";
boolean validDigit=convertStringToInt(str);

if(validDigit){
int digit=Integer.parseInt(str);
System.out.println(digit);
}else{
System.out.println("given string is not a number");
}
}



public static boolean convertStringToInt(String str){
boolean validDigit=true;
Pattern pattern=Pattern.compile(".*[^0-9].*");
boolean digitsArePresent=!pattern.matcher(str).matches();
if(!digitsArePresent){
validDigit=false;
}else{
validDigit=true;
}

return validDigit;
}
}

Anonymous said...

if i have String stringNo = "10Y"

then how can i convert it in int intNo=10
('Y' should be added afterwards)

then again set String stringFinal="10Y"

Anonymous said...

if i have string like "1+2+3" and i want convert into number having ans 3+2+1=7 .so final Ans would be 7.

Ankit Verma said...

ParseInt is better to call as Value of is internally calling parse Int

javin paul said...

@Ankit, even though valueOf() calls parseInt() internally, it's better to use the valueOf() method because it caches the frequently used numbers e.g. from -128 to 127. So, if you already parsed "127" then valueOf() will return cached value but parseInt will always parse it.

Unknown said...

entire string in the form of string and interger how to split it in the form of split

Anonymous said...

There is some difference between an int and an integer, former is a primitive data type which can never be null while later is a wrapper object which can be null. The default value for int is zero while for Integer it is null. So, if you are looking to convert a String to an int in Java, you need to use the parseInt() method as described in this article.

Unknown said...

if string is like this "as3 fsd3 s1d d2" and i want sum of the number i.e 3+3+1+2=9.then what is the solution for it?

shim said...

In your last example I m not able to under stand meaning of %d

Anonymous said...

There is error of exception processing occurred when converting string array to integer array....
Then how to convert string array to integer array...
Please help me out if anyone knows...
Thanks in advance....

Liam Melaugh said...

Thanks, Javin. That was very helpful. I just needed to know how to parse a string into an int but your explanation about the exception made me put it in a try catch statement with NumberFormatException e and it works perfectly. So thanks again, Javin.

javin paul said...

Your most welcome Liam :-)

javin paul said...

@Anonymous, there is no direct way to convert String array to integer array, you need to loop though the array and convert each element to integer and then store into an integer array, that's it.

Ahmed said...

2.238494 is a float not a int or Integer ,can't convertbconvert directly ata greater value tosmall value need downcasting expoucily

javin paul said...

Hello Ahmed, sorry, didn't get the context of your comment, can you describe please?

Post a Comment