Sabtu, 01 Maret 2014

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


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




new StringBuilder().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 conversion than please let us know and I will include it here.

























Source:http://javarevisited.blogspot.com/2011/08/convert-string-to-integer-to-string.html

Tidak ada komentar:

Posting Komentar