Convert integer to String in Java

In this post, we will discuss how to convert an integer to string in Java. If the value of specified integer is negative, the sign should be preserved in resultant string.


 

There are many instances where we need to convert int, double or float values into string (and vice-versa). Conversion to string is also needed to prevent arithmetic overflow. For example, 2147483648 number which represents Integer.MAX_VALUE + 1 is too large to store in an int data type and throws an error, but same value can be stored in a string object as "2147483648".

 
There are many ways to convert an integer to string in Java –

 

1. String.valueOf()

String class provides valueOf() static method that returns the string representation of the specified integer argument.

 

2. Integer.toString()

Integer class toString() can be used for conversion from integer to string. It has two overloaded versions as shown below:

 

3. String.format()

String format() returns a formatted string that can be used for converting an integer to string.

 

4. DecimalFormat.format()

DecimalFormat class provides a variety of features to parse and format numbers. We can use it in many ways to format an integer to produce a string as shown below:

 

5. StringBuffer or StringBuilder

StringBuilder class append() method is overloaded so as to accept data of any type. It can be used for conversion from integer to string as shown below.

StringBuffer works in similar way but is thread safe and hence slower.

 

6. String Concatenation

We can use the expression "" + n to convert an integer n to a string.

This approach is unconventional and above code will translate to below code at runtime –

 
 
Related Post: Convert String to integer in Java

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz