Saturday, August 6, 2011

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 andInteger to String conversion is basic stuff but same time its most useful also because of its frequent need given that String and Integer are two most widely used type in all sort of program and you often gets data between any of these format. One of the common task of programming is converting one data type another e.g. Converting Enum to String or Converting Double to String, Which are similar to converting String to Integer. Some programmer asked 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 other. 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. Here is my way of converting String to Integer in Java with example :

String to Integer Conversion in Java

here are four different ways of converting String object into int or Integer in Java :1) By using Intger.parseInt(String string-to-be-converted) 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 NumberFormatExceptionif 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() methodThere 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 int. This method also throws NumberFormatException if string provided does not represent actual number. Another interesting point about static valueOf() method is that it is used to create 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 caches Integer instance in the range -128 to 127.

How to convert Integer to String in Java

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 couple of more ways to convert int into String and we will see those here with examples.

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 :

newStringBuilder().append( "" ).append( 10 ).toString();

StringBuilder(String) constructor allocates a buffer containing 16 characters. So , appending upto to 16 characters to that StringBuilder will not require buffer reallocation, but appending more than 16 character will expand StringBuider buffer. Though it's not going to happen because Integer.MAX_VALUE is 2147483647, which is less than 16 character. At the end, StringBuilder.toString() will create a new String object with a copy of StringBuider 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 cached set of values but also you will at least avoid creating a StringBuilder. To learn more about these two, see my post 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 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 corresponding method in Java. Here is an example of int to String using String.valueOf()

String price = String.valueOf(123);

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

Int to 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 variety of way 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 conversionthan please let us know and I will include it here.

18 comments
:

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()

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

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 like14205 12480 52954 00193to make a 20-digit number. Please help!

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.

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 :)

@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.

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)