Java Convert Integer to String

Introduction

Converting a primitive int, or its respective wrapper class Integer, to a String is a common and simple operation. The same goes for the other way around, converting a String to Integer.

Converting Integer to String

When converting an int or Integer to a String, there are four approaches. The String class provides a couple of methods - valueOf() and format() for this purpose, though the already mentioned Integer class also offers a toString() method that takes care of this problem. Additionally, you could also rely on StringBuilder's append() method, though this isn't a commonly used scenario:

  • String.valueOf(int i) - This approach is considered best practice due to simplicity. This method accepts other types as well - boolean, char, char[], double, float, long, Object
  • Integer.toString(int i) - This approach is older than valueOf() and simply utilizes the method every Java object has to return a String representing the given int. This approach, unlike the previous, can return a NullPointerException though.
  • String.format(String format, Object... args) - Returns a String formatted according to the format specifier and the following arguments
  • StringBuilder.append(int i).toString() - Same as the valueOf() method, this method accepts all primitive types with the addition of some other types like String, StringBuffer and CharSequence.

String.valueOf()

The valueOf() method is the static method of String class that returns the String representation of the specified type.

There are many types allowed here:

  • Object
  • char[]
  • boolean
  • char
  • int
  • long
  • float
  • double

But we'll be focusing on int for this tutorial. The representation returned exactly matches the representation returned by Integer.toString() when passing the same argument:

int i = 12345;

String string = String.valueOf(i);
String otherString = Integer.toString(i);

System.out.println(string.equals(otherString));
System.out.println(string == otherString);
System.out.println(string);
System.out.println(otherString);

Running this piece of code will yield:

true
false
12345
12345

This makes sense since both of these methods return a new String. The equals() method returns true, because their value is the same, whereas == returns false since their reference variables don't point to the same object in memory.

Using valueOf() keeps your code consistent across conversion of one data type to another. In the case of an Integer, the valueOf() method is also able to cache frequently used numbers e.g. from -127 to 128, in order to speed up the conversion and reduce memory.

Because of this, it's encouraged to use the valueOf() method for both String and Integer conversion.

Integer.toString()

This approach utilizes one of the most common Java methods - toString() shared amongst all objects.

The method has many usages and warrants a detailed explanation. If you'd like to read more about it, we've got a great article already covering it!

In this case, the method returns a String object representing the specified int. The argument is converted to signed decimal representation and returned as a String:

int i = 12345;

String string = Integer.toString(i);
String otherString = new Integer(i).toString();

System.out.println(string.equals(otherString));
System.out.println(string == otherString);
System.out.println(string);
System.out.println(otherString);

Running this piece of code will yield:

true
false
12345
12345

If your variable is of primitive type (int), it is better to use Integer.toString(int) or String.valueOf(int). But if your variable is already an instance of Integer (wrapper class of the primitive type int), it is better to just invoke its toString() method as shown above.

String.format()

Returns a String formatted according to the format specifier and the following arguments. While the purpose of this method isn't exactly to convert, but rather format a String, it can also be used for conversion.

There are quite a few specifiers to choose from:

  • %a - Hex output of a floating point number
  • %b - true if not null, false if null
  • %c - Unicode character
  • %d - Decimal Integer
  • %e - Scientific notation of a decimal Integer
  • %f - Decimal floating point number
  • %g - Same as above, but possibly scientific, depending on the value
  • %h - Hex String of hashCode() return value
  • %n - Line separator
  • %o - Octal Integer
  • %s - String
  • %t - Date/Time conversion
  • %x - Hex String

We'll be focusing on %d for this tutorial:

int i = 12345;

String string = String.format("%d", i);

System.out.println(string);

Running this piece of code will yield:

12345
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The format() method throws an IllegalFormatConversionException if you pass an incompatible type e.g. passing Integer for specifier %s, which expects a String object.

Some of the most common specifiers are %s for String, %d for decimal integer and %n.

StringBuilder and StringBuffer

Both StringBuffer and StringBuilder are classes used to concatenate multiple values into a single String.

StringBuffer is thread safe but slower, whereas StringBuilder isn't thread safe but is faster.

int i = 12345;

String string = new StringBuilder().append(i).toString();
String otherString = new StringBuffer().append(i).toString();

System.out.println(string.equals(otherString));
System.out.println(string == otherString);
System.out.println(string);
System.out.println(otherString);

Running this piece of code will yield:

true
false
12345
12345

Conclusion

We've covered one of the fundamental topics of Java and common problem developers face - Converting an int or Integer to a String using tools shipped with the JDK.

Last Updated: February 8th, 2019
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms