How to Convert Integer to String in Java: A Complete Guide
Converting an int (or Integer) to a String is one of the most common tasks in Java programming. Whether you need to display a number in a GUI, write it to a file, or concatenate it with other text, knowing the right conversion technique makes your code cleaner, safer, and more efficient. This article walks you through every reliable method, explains when to use each one, and highlights performance considerations so you can choose the best approach for any situation.
Why Converting Integer to String Matters
In Java, primitive types like int are not objects, whereas String is a full‑featured class in the java.lang package. Many APIs—such as System.out.But println, JLabel. setText, or JDBC prepared statements—expect a String argument.
- Display numeric values in user interfaces or console output.
- Build dynamic messages (e.g., “You have scored 42 points”).
- Serialize data for storage or transmission (JSON, CSV, XML).
- Avoid concatenation errors that can arise when mixing primitives with strings.
Understanding the nuances of each conversion method helps you write code that is both readable and performant.
Core Methods for Integer‑to‑String Conversion
Java provides several built‑in ways to turn an integer into a string. Below are the most widely used techniques, each with its own strengths The details matter here. Still holds up..
1. String.valueOf(int i)
int number = 123;
String str = String.valueOf(number);
- What it does: Internally delegates to
Integer.toString(i), but handlesnullsafely (returns"null"if the argument werenull; not relevant for primitives). - When to use: Preferred for generic code where the argument might be an
Objector you want a single, consistent utility method. - Performance: Very fast; the JVM often inlines the call.
2. Integer.toString(int i)
int number = 123;
String str = Integer.toString(number);
- What it does: Directly converts the primitive
intto its decimal string representation. - When to use: When you are certain you are working with an
int(orInteger) and want the most explicit, type‑specific call. - Performance: Slightly faster than
String.valueOfbecause it skips the extra indirection, though the difference is negligible in most applications.
3. Empty String Concatenation ("" + i)
int number = 123;
String str = "" + number;
- What it does: The
+operator triggers string concatenation, which the compiler translates into aStringBuilder.appendchain. - When to use: Quick‑and‑dirty debugging or one‑liners where readability is not a concern.
- Performance: Creates a temporary
StringBuilderobject each time, making it less efficient than the dedicated conversion methods, especially inside loops.
4. String.format("%d", i)
int number = 123;
String str = String.format("%d", number);
- What it does: Uses the formatter syntax familiar from C’s
printf. The%dspecifier formats an integer in base‑10. - When to use: When you need additional formatting (padding, locale‑specific grouping, etc.) alongside the conversion.
- Performance: Slightly slower due to parsing the format pattern, but still acceptable for infrequent calls.
5. DecimalFormat for Custom Patterns
int number = 123;
DecimalFormat df = new DecimalFormat("00000");
String str = df.format(number); // "00123"
- What it does: Allows sophisticated patterns such as leading zeros, thousand separators, or custom symbols.
- When to use: Financial reports, ID generation, or any scenario where the raw integer needs a specific visual layout.
- Performance: Higher overhead because it creates a formatter object; reuse the same
DecimalFormatinstance if you call it repeatedly.
6. StringBuilder or StringBuffer Append
int number = 123;
StringBuilder sb = new StringBuilder();
sb.append(number);
String str = sb.toString();
- What it does: Manual append to a mutable character sequence, then extracts the final string.
- When to use: Building a larger string that already contains other parts; avoids multiple immutable string creations.
- Performance: Efficient for concatenating many pieces in a loop.
7. Apache Commons Lang StringUtils
import org.apache.commons.lang3.StringUtils;
int number = 123;
String str = StringUtils.valueOf(number);
- What it does: Wrapper around
String.valueOfthat also handlesnullgracefully. - When to use: Projects already depending on Apache Commons Lang for other utilities.
- Performance: Same as
String.valueOf; the benefit is consistency with other null‑safe helpers.
Choosing the Right Method: Decision Factors
| Factor | Best Choice | Reason |
|---|---|---|
| Simplicity & readability | String.Which means valueOf or Integer. Because of that, toString |
Clear intent, no extra objects. Plus, |
| Need for formatting (padding, commas) | String. format or DecimalFormat |
Direct pattern support. |
| Inside a tight loop | Integer.toString or StringBuilder.That's why append |
Minimal allocation overhead. |
| Already using Apache Commons | StringUtils.valueOf |
Leverages existing dependency. |
| Debugging / quick test | "" + number |
Fast to type, acceptable for non‑performance‑critical code. |
| Null safety with Object input | String.valueOf(Object) |
Returns "null" instead of throwing NPE. |
Easier said than done, but still worth knowing.
Under the Hood: How Java Performs the Conversion
When the JVM executes Integer.toString(int i), it follows these steps:
- Sign handling: If
iis negative, a'-'character is prefixed and the absolute value is processed. - Digit extraction: The algorithm repeatedly divides the number by 10, collecting remainders (the least‑significant digit) into a character array.
- Reverse: Because digits are obtained backwards, the array is reversed to produce the correct order.
- String construction: A new
Stringis created from the character array, using the UTF‑16 encoding that Java strings employ internally.
String.valueOf simply calls Integer.toString for primitive int arguments, adding a null‑check branch that is bypassed for primitives.
new StringBuilder().append("").append(i).toString()
which explains why it creates an extra StringBuilder object each time.
Understanding this process helps you appreciate why the direct Integer.toString
method avoids the intermediate StringBuilder allocation and the extra method call indirection, making it the fastest option for raw conversion Took long enough..
Micro‑Benchmark Perspective (JMH)
To quantify the differences, a simple JMH benchmark running on a modern JDK (21+) with default GC settings yields results in the same ballpark as the table below. Numbers are nanoseconds per operation (lower is better); actual values vary by hardware and JVM warm‑up state.
| Benchmark Mode | Integer.Plus, toString | String. valueOf | "" + i | String.format | `StringBuilder No workaround needed..
Quick note before moving on.
Key Takeaways:
Integer.toStringandString.valueOfare statistically tied. The JIT compiler inlines the trivialString.valueOfcall, eliminating any overhead."" + iis measurably slower due to the mandatoryStringBuilderallocation (though Escape Analysis can sometimes scalar-replace it, it is not guaranteed).String.formatis an order of magnitude slower because it parses the format string, creates aFormatterinstance, and uses locale-sensitive machinery. Reserve it for actual formatting needs.StringBuildershines only when aggregating multiple values; for a single integer, it adds object allocation without benefit.
Common Pitfalls & Edge Cases
-
Integer.MIN_VALUE(-2,147,483,648): The absolute value ofInteger.MIN_VALUEcannot be represented as a positiveint(overflow). The JDK implementation handles this special case explicitly before the standard division loop. Custom implementations often fail here. -
Locale Sensitivity:
String.format("%d", number)andDecimalFormatrespect the defaultLocale(e.g., using,as a grouping separator or different digit shapes in Arabic/Thai locales).Integer.toStringalways produces ASCII digits0-9and an ASCII minus sign-. For machine-readable output (logs, JSON, DB keys),Integer.toStringis safer But it adds up.. -
Boxing Overhead: Passing an
intto a method acceptingObject(e.g.,String.valueOf(Object)) triggers autoboxing toIntegerThe details matter here. Simple as that..// Avoid in hot paths: String s = String.valueOf((Object) myInt); // Allocates Integer object // Prefer: String s = String.valueOf(myInt); // Primitive overload, no boxing -
Null Handling:
String.valueOf(null)→"null"(String literal).String.valueOf((Integer) null)→"null".Integer.toString(null)→ Compile Error (primitives cannot be null).Objects.toString(null, "default")→"default"(Java 9+).
Summary: The "Default" Rule
For the vast majority of production code converting an int to a String:
- Use
Integer.toString(i)— It communicates intent precisely ("convert this primitive"), has zero overhead, and is the intrinsic the JIT expects. - Use
String.valueOf(i)— If you prefer a method that works uniformly on primitives and object references without changing the call site. - Reach for
String.format/DecimalFormat— Only when the requirement includes padding, grouping separators, or locale-specific rendering. - Use
StringBuilder— Only when building a composite string containing multiple data points.
By aligning your choice with the specific context—performance-critical loop, formatted report, or quick log statement—you ensure the code remains readable, maintainable, and efficient Not complicated — just consistent..